var Prototype={Version:'1.6.0.3',Browser:{IE:!!(window.attachEvent&&navigator.userAgent.indexOf('Opera')===-1),Opera:navigator.userAgent.indexOf('Opera')>-1,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,SelectorsAPI:!!document.querySelector,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 parent=null,properties=$A(arguments);if(Object.isFunction(properties[0]))
parent=properties.shift();function klass(){this.initialize.apply(this,arguments);}
Object.extend(klass,Class.Methods);klass.superclass=parent;klass.subclasses=[];if(parent){var subclass=function(){};subclass.prototype=parent.prototype;klass.prototype=new subclass;parent.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(source){var ancestor=this.superclass&&this.superclass.prototype;var properties=Object.keys(source);if(!Object.keys({toString:true}).length)
properties.push("toString","valueOf");for(var i=0,length=properties.length;i<length;i++){var property=properties[i],value=source[property];if(ancestor&&Object.isFunction(value)&&value.argumentNames().first()=="$super"){var method=value;value=(function(m){return function(){return ancestor[m].apply(this,arguments)};})(property).wrap(method);value.valueOf=method.valueOf.bind(method);value.toString=method.toString.bind(method);}
this.prototype[property]=value;}
return this;}};var Abstract={};Object.extend=function(destination,source){for(var property in source)
destination[property]=source[property];return destination;};Object.extend(Object,{inspect:function(object){try{if(Object.isUndefined(object))return'undefined';if(object===null)return'null';return object.inspect?object.inspect():String(object);}catch(e){if(e instanceof RangeError)return'...';throw e;}},toJSON:function(object){var type=typeof object;switch(type){case'undefined':case'function':case'unknown':return;case'boolean':return object.toString();}
if(object===null)return'null';if(object.toJSON)return object.toJSON();if(Object.isElement(object))return;var results=[];for(var property in object){var value=Object.toJSON(object[property]);if(!Object.isUndefined(value))
results.push(property.toJSON()+': '+value);}
return'{'+results.join(', ')+'}';},toQueryString:function(object){return $H(object).toQueryString();},toHTML:function(object){return object&&object.toHTML?object.toHTML():String.interpret(object);},keys:function(object){var keys=[];for(var property in object)
keys.push(property);return keys;},values:function(object){var values=[];for(var property in object)
values.push(object[property]);return values;},clone:function(object){return Object.extend({},object);},isElement:function(object){return!!(object&&object.nodeType==1);},isArray:function(object){return object!=null&&typeof object=="object"&&'splice'in object&&'join'in object;},isHash:function(object){return object instanceof Hash;},isFunction:function(object){return typeof object=="function";},isString:function(object){return typeof object=="string";},isNumber:function(object){return typeof object=="number";},isUndefined:function(object){return typeof object=="undefined";}});Object.extend(Function.prototype,{argumentNames:function(){var names=this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1].replace(/\s+/g,'').split(',');return names.length==1&&!names[0]?[]:names;},bind:function(){if(arguments.length<2&&Object.isUndefined(arguments[0]))return this;var __method=this,args=$A(arguments),object=args.shift();return function(){return __method.apply(object,args.concat($A(arguments)));}},bindAsEventListener:function(){var __method=this,args=$A(arguments),object=args.shift();return function(event){return __method.apply(object,[event||window.event].concat(args));}},curry:function(){if(!arguments.length)return this;var __method=this,args=$A(arguments);return function(){return __method.apply(this,args.concat($A(arguments)));}},delay:function(){var __method=this,args=$A(arguments),timeout=args.shift()*1000;return window.setTimeout(function(){return __method.apply(__method,args);},timeout);},defer:function(){var args=[0.01].concat($A(arguments));return this.delay.apply(this,args);},wrap:function(wrapper){var __method=this;return function(){return wrapper.apply(this,[__method.bind(this)].concat($A(arguments)));}},methodize:function(){if(this._methodized)return this._methodized;var __method=this;return this._methodized=function(){return __method.apply(null,[this].concat($A(arguments)));};}});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 returnValue;for(var i=0,length=arguments.length;i<length;i++){var lambda=arguments[i];try{returnValue=lambda();break;}catch(e){}}
return returnValue;}};RegExp.prototype.match=RegExp.prototype.test;RegExp.escape=function(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');};var PeriodicalExecuter=Class.create({initialize:function(callback,frequency){this.callback=callback;this.frequency=frequency;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(value){return value==null?'':String(value);},specialChar:{'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','\\':'\\\\'}});Object.extend(String.prototype,{gsub:function(pattern,replacement){var result='',source=this,match;replacement=arguments.callee.prepareReplacement(replacement);while(source.length>0){if(match=source.match(pattern)){result+=source.slice(0,match.index);result+=String.interpret(replacement(match));source=source.slice(match.index+match[0].length);}else{result+=source,source='';}}
return result;},sub:function(pattern,replacement,count){replacement=this.gsub.prepareReplacement(replacement);count=Object.isUndefined(count)?1:count;return this.gsub(pattern,function(match){if(--count<0)return match[0];return replacement(match);});},scan:function(pattern,iterator){this.gsub(pattern,iterator);return String(this);},truncate:function(length,truncation){length=length||30;truncation=Object.isUndefined(truncation)?'...':truncation;return this.length>length?this.slice(0,length-truncation.length)+truncation: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 matchAll=new RegExp(Prototype.ScriptFragment,'img');var matchOne=new RegExp(Prototype.ScriptFragment,'im');return(this.match(matchAll)||[]).map(function(scriptTag){return(scriptTag.match(matchOne)||['',''])[1];});},evalScripts:function(){return this.extractScripts().map(function(script){return eval(script)});},escapeHTML:function(){var self=arguments.callee;self.text.data=this;return self.div.innerHTML;},unescapeHTML:function(){var div=new Element('div');div.innerHTML=this.stripTags();return div.childNodes[0]?(div.childNodes.length>1?$A(div.childNodes).inject('',function(memo,node){return memo+node.nodeValue}):div.childNodes[0].nodeValue):'';},toQueryParams:function(separator){var match=this.strip().match(/([^?#]*)(#.*)?$/);if(!match)return{};return match[1].split(separator||'&').inject({},function(hash,pair){if((pair=pair.split('='))[0]){var key=decodeURIComponent(pair.shift());var value=pair.length>1?pair.join('='):pair[0];if(value!=undefined)value=decodeURIComponent(value);if(key in hash){if(!Object.isArray(hash[key]))hash[key]=[hash[key]];hash[key].push(value);}
else hash[key]=value;}
return hash;});},toArray:function(){return this.split('');},succ:function(){return this.slice(0,this.length-1)+
String.fromCharCode(this.charCodeAt(this.length-1)+1);},times:function(count){return count<1?'':new Array(count+1).join(this);},camelize:function(){var parts=this.split('-'),len=parts.length;if(len==1)return parts[0];var camelized=this.charAt(0)=='-'?parts[0].charAt(0).toUpperCase()+parts[0].substring(1):parts[0];for(var i=1;i<len;i++)
camelized+=parts[i].charAt(0).toUpperCase()+parts[i].substring(1);return camelized;},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(useDoubleQuotes){var escapedString=this.gsub(/[\x00-\x1f\\]/,function(match){var character=String.specialChar[match[0]];return character?character:'\\u00'+match[0].charCodeAt().toPaddedString(2,16);});if(useDoubleQuotes)return'"'+escapedString.replace(/"/g,'\\"')+'"';return"'"+escapedString.replace(/'/g,'\\\'')+"'";},toJSON:function(){return this.inspect(true);},unfilterJSON:function(filter){return this.sub(filter||Prototype.JSONFilter,'#{1}');},isJSON:function(){var str=this;if(str.blank())return false;str=this.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"/g,'');return(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);},evalJSON:function(sanitize){var json=this.unfilterJSON();try{if(!sanitize||json.isJSON())return eval('('+json+')');}catch(e){}
throw new SyntaxError('Badly formed JSON string: '+this.inspect());},include:function(pattern){return this.indexOf(pattern)>-1;},startsWith:function(pattern){return this.indexOf(pattern)===0;},endsWith:function(pattern){var d=this.length-pattern.length;return d>=0&&this.lastIndexOf(pattern)===d;},empty:function(){return this=='';},blank:function(){return/^\s*$/.test(this);},interpolate:function(object,pattern){return new Template(this,pattern).evaluate(object);}});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.stripTags().replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');}});String.prototype.gsub.prepareReplacement=function(replacement){if(Object.isFunction(replacement))return replacement;var template=new Template(replacement);return function(match){return template.evaluate(match)};};String.prototype.parseQuery=String.prototype.toQueryParams;Object.extend(String.prototype.escapeHTML,{div:document.createElement('div'),text:document.createTextNode('')});String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);var Template=Class.create({initialize:function(template,pattern){this.template=template.toString();this.pattern=pattern||Template.Pattern;},evaluate:function(object){if(Object.isFunction(object.toTemplateReplacements))
object=object.toTemplateReplacements();return this.template.gsub(this.pattern,function(match){if(object==null)return'';var before=match[1]||'';if(before=='\\')return match[2];var ctx=object,expr=match[3];var pattern=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;match=pattern.exec(expr);if(match==null)return before;while(match!=null){var comp=match[1].startsWith('[')?match[2].gsub('\\\\]',']'):match[1];ctx=ctx[comp];if(null==ctx||''==match[3])break;expr=expr.substring('['==match[3]?match[1].length:match[0].length);match=pattern.exec(expr);}
return before+String.interpret(ctx);});}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;var $break={};var Enumerable={each:function(iterator,context){var index=0;try{this._each(function(value){iterator.call(context,value,index++);});}catch(e){if(e!=$break)throw e;}
return this;},eachSlice:function(number,iterator,context){var index=-number,slices=[],array=this.toArray();if(number<1)return array;while((index+=number)<array.length)
slices.push(array.slice(index,index+number));return slices.collect(iterator,context);},all:function(iterator,context){iterator=iterator||Prototype.K;var result=true;this.each(function(value,index){result=result&&!!iterator.call(context,value,index);if(!result)throw $break;});return result;},any:function(iterator,context){iterator=iterator||Prototype.K;var result=false;this.each(function(value,index){if(result=!!iterator.call(context,value,index))
throw $break;});return result;},collect:function(iterator,context){iterator=iterator||Prototype.K;var results=[];this.each(function(value,index){results.push(iterator.call(context,value,index));});return results;},detect:function(iterator,context){var result;this.each(function(value,index){if(iterator.call(context,value,index)){result=value;throw $break;}});return result;},findAll:function(iterator,context){var results=[];this.each(function(value,index){if(iterator.call(context,value,index))
results.push(value);});return results;},grep:function(filter,iterator,context){iterator=iterator||Prototype.K;var results=[];if(Object.isString(filter))
filter=new RegExp(filter);this.each(function(value,index){if(filter.match(value))
results.push(iterator.call(context,value,index));});return results;},include:function(object){if(Object.isFunction(this.indexOf))
if(this.indexOf(object)!=-1)return true;var found=false;this.each(function(value){if(value==object){found=true;throw $break;}});return found;},inGroupsOf:function(number,fillWith){fillWith=Object.isUndefined(fillWith)?null:fillWith;return this.eachSlice(number,function(slice){while(slice.length<number)slice.push(fillWith);return slice;});},inject:function(memo,iterator,context){this.each(function(value,index){memo=iterator.call(context,memo,value,index);});return memo;},invoke:function(method){var args=$A(arguments).slice(1);return this.map(function(value){return value[method].apply(value,args);});},max:function(iterator,context){iterator=iterator||Prototype.K;var result;this.each(function(value,index){value=iterator.call(context,value,index);if(result==null||value>=result)
result=value;});return result;},min:function(iterator,context){iterator=iterator||Prototype.K;var result;this.each(function(value,index){value=iterator.call(context,value,index);if(result==null||value<result)
result=value;});return result;},partition:function(iterator,context){iterator=iterator||Prototype.K;var trues=[],falses=[];this.each(function(value,index){(iterator.call(context,value,index)?trues:falses).push(value);});return[trues,falses];},pluck:function(property){var results=[];this.each(function(value){results.push(value[property]);});return results;},reject:function(iterator,context){var results=[];this.each(function(value,index){if(!iterator.call(context,value,index))
results.push(value);});return results;},sortBy:function(iterator,context){return this.map(function(value,index){return{value:value,criteria:iterator.call(context,value,index)};}).sort(function(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0;}).pluck('value');},toArray:function(){return this.map();},zip:function(){var iterator=Prototype.K,args=$A(arguments);if(Object.isFunction(args.last()))
iterator=args.pop();var collections=[this].concat(args).map($A);return this.map(function(value,index){return iterator(collections.pluck(index));});},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(iterable){if(!iterable)return[];if(iterable.toArray)return iterable.toArray();var length=iterable.length||0,results=new Array(length);while(length--)results[length]=iterable[length];return results;}
if(Prototype.Browser.WebKit){$A=function(iterable){if(!iterable)return[];if(!(typeof iterable==='function'&&typeof iterable.length==='number'&&typeof iterable.item==='function')&&iterable.toArray)
return iterable.toArray();var length=iterable.length||0,results=new Array(length);while(length--)results[length]=iterable[length];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(iterator){for(var i=0,length=this.length;i<length;i++)
iterator(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(value){return value!=null;});},flatten:function(){return this.inject([],function(array,value){return array.concat(Object.isArray(value)?value.flatten():[value]);});},without:function(){var values=$A(arguments);return this.select(function(value){return!values.include(value);});},reverse:function(inline){return(inline!==false?this:this.toArray())._reverse();},reduce:function(){return this.length>1?this:this[0];},uniq:function(sorted){return this.inject([],function(array,value,index){if(0==index||(sorted?array.last()!=value:!array.include(value)))
array.push(value);return array;});},intersect:function(array){return this.uniq().findAll(function(item){return array.detect(function(value){return item===value});});},clone:function(){return[].concat(this);},size:function(){return this.length;},inspect:function(){return'['+this.map(Object.inspect).join(', ')+']';},toJSON:function(){var results=[];this.each(function(object){var value=Object.toJSON(object);if(!Object.isUndefined(value))results.push(value);});return'['+results.join(', ')+']';}});if(Object.isFunction(Array.prototype.forEach))
Array.prototype._each=Array.prototype.forEach;if(!Array.prototype.indexOf)Array.prototype.indexOf=function(item,i){i||(i=0);var length=this.length;if(i<0)i=length+i;for(;i<length;i++)
if(this[i]===item)return i;return-1;};if(!Array.prototype.lastIndexOf)Array.prototype.lastIndexOf=function(item,i){i=isNaN(i)?this.length:(i<0?this.length+i:i)+1;var n=this.slice(0,i).reverse().indexOf(item);return(n<0)?n:i-n-1;};Array.prototype.toArray=Array.prototype.clone;function $w(string){if(!Object.isString(string))return[];string=string.strip();return string?string.split(/\s+/):[];}
if(Prototype.Browser.Opera){Array.prototype.concat=function(){var array=[];for(var i=0,length=this.length;i<length;i++)array.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++)
array.push(arguments[i][j]);}else{array.push(arguments[i]);}}
return array;};}
Object.extend(Number.prototype,{toColorPart:function(){return this.toPaddedString(2,16);},succ:function(){return this+1;},times:function(iterator,context){$R(0,this,true).each(iterator,context);return this;},toPaddedString:function(length,radix){var string=this.toString(radix||10);return'0'.times(length-string.length)+string;},toJSON:function(){return isFinite(this)?this.toString():'null';}});$w('abs round ceil floor').each(function(method){Number.prototype[method]=Math[method].methodize();});function $H(object){return new Hash(object);};var Hash=Class.create(Enumerable,(function(){function toQueryPair(key,value){if(Object.isUndefined(value))return key;return key+'='+encodeURIComponent(String.interpret(value));}
return{initialize:function(object){this._object=Object.isHash(object)?object.toObject():Object.clone(object);},_each:function(iterator){for(var key in this._object){var value=this._object[key],pair=[key,value];pair.key=key;pair.value=value;iterator(pair);}},set:function(key,value){return this._object[key]=value;},get:function(key){if(this._object[key]!==Object.prototype[key])
return this._object[key];},unset:function(key){var value=this._object[key];delete this._object[key];return value;},toObject:function(){return Object.clone(this._object);},keys:function(){return this.pluck('key');},values:function(){return this.pluck('value');},index:function(value){var match=this.detect(function(pair){return pair.value===value;});return match&&match.key;},merge:function(object){return this.clone().update(object);},update:function(object){return new Hash(object).inject(this,function(result,pair){result.set(pair.key,pair.value);return result;});},toQueryString:function(){return this.inject([],function(results,pair){var key=encodeURIComponent(pair.key),values=pair.value;if(values&&typeof values=='object'){if(Object.isArray(values))
return results.concat(values.map(toQueryPair.curry(key)));}else results.push(toQueryPair(key,values));return results;}).join('&');},inspect:function(){return'#<Hash:{'+this.map(function(pair){return pair.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(start,end,exclusive){this.start=start;this.end=end;this.exclusive=exclusive;},_each:function(iterator){var value=this.start;while(this.include(value)){iterator(value);value=value.succ();}},include:function(value){if(value<this.start)
return false;if(this.exclusive)
return value<this.end;return value<=this.end;}});var $R=function(start,end,exclusive){return new ObjectRange(start,end,exclusive);};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(iterator){this.responders._each(iterator);},register:function(responder){if(!this.include(responder))
this.responders.push(responder);},unregister:function(responder){this.responders=this.responders.without(responder);},dispatch:function(callback,request,transport,json){this.each(function(responder){if(Object.isFunction(responder[callback])){try{responder[callback].apply(responder,[request,transport,json]);}catch(e){}}});}};Object.extend(Ajax.Responders,Enumerable);Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++},onComplete:function(){Ajax.activeRequestCount--}});Ajax.Base=Class.create({initialize:function(options){this.options={method:'post',asynchronous:true,contentType:'application/x-www-form-urlencoded',encoding:'UTF-8',parameters:'',evalJSON:true,evalJS:true};Object.extend(this.options,options||{});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,url,options){$super(options);this.transport=Ajax.getTransport();this.request(url);},request:function(url){this.url=url;this.method=this.options.method;var params=Object.clone(this.options.parameters);if(!['get','post'].include(this.method)){params['_method']=this.method;this.method='post';}
this.parameters=params;if(params=Object.toQueryString(params)){if(this.method=='get')
this.url+=(this.url.include('?')?'&':'?')+params;else if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
params+='&_=';}
try{var response=new Ajax.Response(this);if(this.options.onCreate)this.options.onCreate(response);Ajax.Responders.dispatch('onCreate',this,response);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||params):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType)
this.onStateChange();}
catch(e){this.dispatchException(e);}},onStateChange:function(){var readyState=this.transport.readyState;if(readyState>1&&!((readyState==4)&&this._complete))
this.respondToReadyState(this.transport.readyState);},setRequestHeaders:function(){var headers={'X-Requested-With':'XMLHttpRequest','X-Prototype-Version':Prototype.Version,'Accept':'text/javascript, text/html, application/xml, text/xml, */*'};if(this.method=='post'){headers['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)
headers['Connection']='close';}
if(typeof this.options.requestHeaders=='object'){var extras=this.options.requestHeaders;if(Object.isFunction(extras.push))
for(var i=0,length=extras.length;i<length;i+=2)
headers[extras[i]]=extras[i+1];else
$H(extras).each(function(pair){headers[pair.key]=pair.value});}
for(var name in headers)
this.transport.setRequestHeader(name,headers[name]);},success:function(){var status=this.getStatus();return!status||(status>=200&&status<300);},getStatus:function(){try{return this.transport.status||0;}catch(e){return 0}},respondToReadyState:function(readyState){var state=Ajax.Request.Events[readyState],response=new Ajax.Response(this);if(state=='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 contentType=response.getHeader('Content-type');if(this.options.evalJS=='force'||(this.options.evalJS&&this.isSameOrigin()&&contentType&&contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
this.evalResponse();}
try{(this.options['on'+state]||Prototype.emptyFunction)(response,response.headerJSON);Ajax.Responders.dispatch('on'+state,this,response,response.headerJSON);}catch(e){this.dispatchException(e);}
if(state=='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(name){try{return this.transport.getResponseHeader(name)||null;}catch(e){return null}},evalResponse:function(){try{return eval((this.transport.responseText||'').unfilterJSON());}catch(e){this.dispatchException(e);}},dispatchException:function(exception){(this.options.onException||Prototype.emptyFunction)(this,exception);Ajax.Responders.dispatch('onException',this,exception);}});Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Ajax.Response=Class.create({initialize:function(request){this.request=request;var transport=this.transport=request.transport,readyState=this.readyState=transport.readyState;if((readyState>2&&!Prototype.Browser.IE)||readyState==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=String.interpret(transport.responseText);this.headerJSON=this._getHeaderJSON();}
if(readyState==4){var xml=transport.responseXML;this.responseXML=Object.isUndefined(xml)?null:xml;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(name){return this.transport.getResponseHeader(name);},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders();},_getHeaderJSON:function(){var json=this.getHeader('X-JSON');if(!json)return null;json=decodeURIComponent(escape(json));try{return json.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin());}catch(e){this.request.dispatchException(e);}},_getResponseJSON:function(){var options=this.request.options;if(!options.evalJSON||(options.evalJSON!='force'&&!(this.getHeader('Content-type')||'').include('application/json'))||this.responseText.blank())
return null;try{return this.responseText.evalJSON(options.sanitizeJSON||!this.request.isSameOrigin());}catch(e){this.request.dispatchException(e);}}});Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,container,url,options){this.container={success:(container.success||container),failure:(container.failure||(container.success?null:container))};options=Object.clone(options);var onComplete=options.onComplete;options.onComplete=(function(response,json){this.updateContent(response.responseText);if(Object.isFunction(onComplete))onComplete(response,json);}).bind(this);$super(url,options);},updateContent:function(responseText){var receiver=this.container[this.success()?'success':'failure'],options=this.options;if(!options.evalScripts)responseText=responseText.stripScripts();if(receiver=$(receiver)){if(options.insertion){if(Object.isString(options.insertion)){var insertion={};insertion[options.insertion]=responseText;receiver.insert(insertion);}
else options.insertion(receiver,responseText);}
else receiver.update(responseText);}}});Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,container,url,options){$super(options);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=container;this.url=url;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(response){if(this.options.decay){this.decay=(response.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=response.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 $(element){if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i<length;i++)
elements.push($(arguments[i]));return elements;}
if(Object.isString(element))
element=document.getElementById(element);return Element.extend(element);}
if(Prototype.BrowserFeatures.XPath){document._getElementsByXPath=function(expression,parentElement){var results=[];var query=document.evaluate(expression,$(parentElement)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(var i=0,length=query.snapshotLength;i<length;i++)
results.push(Element.extend(query.snapshotItem(i)));return results;};}
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 element=this.Element;this.Element=function(tagName,attributes){attributes=attributes||{};tagName=tagName.toLowerCase();var cache=Element.cache;if(Prototype.Browser.IE&&attributes.name){tagName='<'+tagName+' name="'+attributes.name+'">';delete attributes.name;return Element.writeAttribute(document.createElement(tagName),attributes);}
if(!cache[tagName])cache[tagName]=Element.extend(document.createElement(tagName));return Element.writeAttribute(cache[tagName].cloneNode(false),attributes);};Object.extend(this.Element,element||{});if(element)this.Element.prototype=element.prototype;}).call(window);Element.cache={};Element.Methods={visible:function(element){return $(element).style.display!='none';},toggle:function(element){element=$(element);Element[Element.visible(element)?'hide':'show'](element);return element;},hide:function(element){element=$(element);element.style.display='none';return element;},show:function(element){element=$(element);element.style.display='';return element;},remove:function(element){element=$(element);element.parentNode.removeChild(element);return element;},update:function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();if(Object.isElement(content))return element.update().insert(content);content=Object.toHTML(content);element.innerHTML=content.stripScripts();content.evalScripts.bind(content).defer();return element;},replace:function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();else if(!Object.isElement(content)){content=Object.toHTML(content);var range=element.ownerDocument.createRange();range.selectNode(element);content.evalScripts.bind(content).defer();content=range.createContextualFragment(content.stripScripts());}
element.parentNode.replaceChild(content,element);return element;},insert:function(element,insertions){element=$(element);if(Object.isString(insertions)||Object.isNumber(insertions)||Object.isElement(insertions)||(insertions&&(insertions.toElement||insertions.toHTML)))
insertions={bottom:insertions};var content,insert,tagName,childNodes;for(var position in insertions){content=insertions[position];position=position.toLowerCase();insert=Element._insertionTranslations[position];if(content&&content.toElement)content=content.toElement();if(Object.isElement(content)){insert(element,content);continue;}
content=Object.toHTML(content);tagName=((position=='before'||position=='after')?element.parentNode:element).tagName.toUpperCase();childNodes=Element._getContentFromAnonymousElement(tagName,content.stripScripts());if(position=='top'||position=='after')childNodes.reverse();childNodes.each(insert.curry(element));content.evalScripts.bind(content).defer();}
return element;},wrap:function(element,wrapper,attributes){element=$(element);if(Object.isElement(wrapper))
$(wrapper).writeAttribute(attributes||{});else if(Object.isString(wrapper))wrapper=new Element(wrapper,attributes);else wrapper=new Element('div',wrapper);if(element.parentNode)
element.parentNode.replaceChild(wrapper,element);wrapper.appendChild(element);return wrapper;},inspect:function(element){element=$(element);var result='<'+element.tagName.toLowerCase();$H({'id':'id','className':'class'}).each(function(pair){var property=pair.first(),attribute=pair.last();var value=(element[property]||'').toString();if(value)result+=' '+attribute+'='+value.inspect(true);});return result+'>';},recursivelyCollect:function(element,property){element=$(element);var elements=[];while(element=element[property])
if(element.nodeType==1)
elements.push(Element.extend(element));return elements;},ancestors:function(element){return $(element).recursivelyCollect('parentNode');},descendants:function(element){return $(element).select("*");},firstDescendant:function(element){element=$(element).firstChild;while(element&&element.nodeType!=1)element=element.nextSibling;return $(element);},immediateDescendants:function(element){if(!(element=$(element).firstChild))return[];while(element&&element.nodeType!=1)element=element.nextSibling;if(element)return[element].concat($(element).nextSiblings());return[];},previousSiblings:function(element){return $(element).recursivelyCollect('previousSibling');},nextSiblings:function(element){return $(element).recursivelyCollect('nextSibling');},siblings:function(element){element=$(element);return element.previousSiblings().reverse().concat(element.nextSiblings());},match:function(element,selector){if(Object.isString(selector))
selector=new Selector(selector);return selector.match($(element));},up:function(element,expression,index){element=$(element);if(arguments.length==1)return $(element.parentNode);var ancestors=element.ancestors();return Object.isNumber(expression)?ancestors[expression]:Selector.findElement(ancestors,expression,index);},down:function(element,expression,index){element=$(element);if(arguments.length==1)return element.firstDescendant();return Object.isNumber(expression)?element.descendants()[expression]:Element.select(element,expression)[index||0];},previous:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.previousElementSibling(element));var previousSiblings=element.previousSiblings();return Object.isNumber(expression)?previousSiblings[expression]:Selector.findElement(previousSiblings,expression,index);},next:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.nextElementSibling(element));var nextSiblings=element.nextSiblings();return Object.isNumber(expression)?nextSiblings[expression]:Selector.findElement(nextSiblings,expression,index);},select:function(){var args=$A(arguments),element=$(args.shift());return Selector.findChildElements(element,args);},adjacent:function(){var args=$A(arguments),element=$(args.shift());return Selector.findChildElements(element.parentNode,args).without(element);},identify:function(element){element=$(element);var id=element.readAttribute('id'),self=arguments.callee;if(id)return id;do{id='anonymous_element_'+self.counter++}while($(id));element.writeAttribute('id',id);return id;},readAttribute:function(element,name){element=$(element);if(Prototype.Browser.IE){var t=Element._attributeTranslations.read;if(t.values[name])return t.values[name](element,name);if(t.names[name])name=t.names[name];if(name.include(':')){return(!element.attributes||!element.attributes[name])?null:element.attributes[name].value;}}
return element.getAttribute(name);},writeAttribute:function(element,name,value){element=$(element);var attributes={},t=Element._attributeTranslations.write;if(typeof name=='object')attributes=name;else attributes[name]=Object.isUndefined(value)?true:value;for(var attr in attributes){name=t.names[attr]||attr;value=attributes[attr];if(t.values[attr])name=t.values[attr](element,value);if(value===false||value===null)
element.removeAttribute(name);else if(value===true)
element.setAttribute(name,name);else element.setAttribute(name,value);}
return element;},getHeight:function(element){return $(element).getDimensions().height;},getWidth:function(element){return $(element).getDimensions().width;},classNames:function(element){return new Element.ClassNames(element);},hasClassName:function(element,className){if(!(element=$(element)))return;var elementClassName=element.className;return(elementClassName.length>0&&(elementClassName==className||new RegExp("(^|\\s)"+className+"(\\s|$)").test(elementClassName)));},addClassName:function(element,className){if(!(element=$(element)))return;if(!element.hasClassName(className))
element.className+=(element.className?' ':'')+className;return element;},removeClassName:function(element,className){if(!(element=$(element)))return;element.className=element.className.replace(new RegExp("(^|\\s+)"+className+"(\\s+|$)"),' ').strip();return element;},toggleClassName:function(element,className){if(!(element=$(element)))return;return element[element.hasClassName(className)?'removeClassName':'addClassName'](className);},cleanWhitespace:function(element){element=$(element);var node=element.firstChild;while(node){var nextNode=node.nextSibling;if(node.nodeType==3&&!/\S/.test(node.nodeValue))
element.removeChild(node);node=nextNode;}
return element;},empty:function(element){return $(element).innerHTML.blank();},descendantOf:function(element,ancestor){element=$(element),ancestor=$(ancestor);if(element.compareDocumentPosition)
return(element.compareDocumentPosition(ancestor)&8)===8;if(ancestor.contains)
return ancestor.contains(element)&&ancestor!==element;while(element=element.parentNode)
if(element==ancestor)return true;return false;},scrollTo:function(element){element=$(element);var pos=element.cumulativeOffset();window.scrollTo(pos[0],pos[1]);return element;},getStyle:function(element,style){element=$(element);style=style=='float'?'cssFloat':style.camelize();var value=element.style[style];if(!value||value=='auto'){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null;}
if(style=='opacity')return value?parseFloat(value):1.0;return value=='auto'?null:value;},getOpacity:function(element){return $(element).getStyle('opacity');},setStyle:function(element,styles){element=$(element);var elementStyle=element.style,match;if(Object.isString(styles)){element.style.cssText+=';'+styles;return styles.include('opacity')?element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]):element;}
for(var property in styles)
if(property=='opacity')element.setOpacity(styles[property]);else
elementStyle[(property=='float'||property=='cssFloat')?(Object.isUndefined(elementStyle.styleFloat)?'cssFloat':'styleFloat'):property]=styles[property];return element;},setOpacity:function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;return element;},getDimensions:function(element){element=$(element);var display=element.getStyle('display');if(display!='none'&&display!=null)
return{width:element.offsetWidth,height:element.offsetHeight};var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility='hidden';els.position='absolute';els.display='block';var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};},makePositioned:function(element){element=$(element);var pos=Element.getStyle(element,'position');if(pos=='static'||!pos){element._madePositioned=true;element.style.position='relative';if(Prototype.Browser.Opera){element.style.top=0;element.style.left=0;}}
return element;},undoPositioned:function(element){element=$(element);if(element._madePositioned){element._madePositioned=undefined;element.style.position=element.style.top=element.style.left=element.style.bottom=element.style.right='';}
return element;},makeClipping:function(element){element=$(element);if(element._overflow)return element;element._overflow=Element.getStyle(element,'overflow')||'auto';if(element._overflow!=='hidden')
element.style.overflow='hidden';return element;},undoClipping:function(element){element=$(element);if(!element._overflow)return element;element.style.overflow=element._overflow=='auto'?'':element._overflow;element._overflow=null;return element;},cumulativeOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;}while(element);return Element._returnOffset(valueL,valueT);},positionedOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;if(element){if(element.tagName.toUpperCase()=='BODY')break;var p=Element.getStyle(element,'position');if(p!=='static')break;}}while(element);return Element._returnOffset(valueL,valueT);},absolutize:function(element){element=$(element);if(element.getStyle('position')=='absolute')return element;var offsets=element.positionedOffset();var top=offsets[1];var left=offsets[0];var width=element.clientWidth;var height=element.clientHeight;element._originalLeft=left-parseFloat(element.style.left||0);element._originalTop=top-parseFloat(element.style.top||0);element._originalWidth=element.style.width;element._originalHeight=element.style.height;element.style.position='absolute';element.style.top=top+'px';element.style.left=left+'px';element.style.width=width+'px';element.style.height=height+'px';return element;},relativize:function(element){element=$(element);if(element.getStyle('position')=='relative')return element;element.style.position='relative';var top=parseFloat(element.style.top||0)-(element._originalTop||0);var left=parseFloat(element.style.left||0)-(element._originalLeft||0);element.style.top=top+'px';element.style.left=left+'px';element.style.height=element._originalHeight;element.style.width=element._originalWidth;return element;},cumulativeScrollOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.scrollTop||0;valueL+=element.scrollLeft||0;element=element.parentNode;}while(element);return Element._returnOffset(valueL,valueT);},getOffsetParent:function(element){if(element.offsetParent)return $(element.offsetParent);if(element==document.body)return $(element);while((element=element.parentNode)&&element!=document.body)
if(Element.getStyle(element,'position')!='static')
return $(element);return $(document.body);},viewportOffset:function(forElement){var valueT=0,valueL=0;var element=forElement;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body&&Element.getStyle(element,'position')=='absolute')break;}while(element=element.offsetParent);element=forElement;do{if(!Prototype.Browser.Opera||(element.tagName&&(element.tagName.toUpperCase()=='BODY'))){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;}}while(element=element.parentNode);return Element._returnOffset(valueL,valueT);},clonePosition:function(element,source){var options=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});source=$(source);var p=source.viewportOffset();element=$(element);var delta=[0,0];var parent=null;if(Element.getStyle(element,'position')=='absolute'){parent=element.getOffsetParent();delta=parent.viewportOffset();}
if(parent==document.body){delta[0]-=document.body.offsetLeft;delta[1]-=document.body.offsetTop;}
if(options.setLeft)element.style.left=(p[0]-delta[0]+options.offsetLeft)+'px';if(options.setTop)element.style.top=(p[1]-delta[1]+options.offsetTop)+'px';if(options.setWidth)element.style.width=source.offsetWidth+'px';if(options.setHeight)element.style.height=source.offsetHeight+'px';return element;}};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(proceed,element,style){switch(style){case'left':case'top':case'right':case'bottom':if(proceed(element,'position')==='static')return null;case'height':case'width':if(!Element.visible(element))return null;var dim=parseInt(proceed(element,style),10);if(dim!==element['offset'+style.capitalize()])
return dim+'px';var properties;if(style==='height'){properties=['border-top-width','padding-top','padding-bottom','border-bottom-width'];}
else{properties=['border-left-width','padding-left','padding-right','border-right-width'];}
return properties.inject(dim,function(memo,property){var val=proceed(element,property);return val===null?memo:memo-parseInt(val,10);})+'px';default:return proceed(element,style);}});Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(proceed,element,attribute){if(attribute==='title')return element.title;return proceed(element,attribute);});}
else if(Prototype.Browser.IE){Element.Methods.getOffsetParent=Element.Methods.getOffsetParent.wrap(function(proceed,element){element=$(element);try{element.offsetParent}
catch(e){return $(document.body)}
var position=element.getStyle('position');if(position!=='static')return proceed(element);element.setStyle({position:'relative'});var value=proceed(element);element.setStyle({position:position});return value;});$w('positionedOffset viewportOffset').each(function(method){Element.Methods[method]=Element.Methods[method].wrap(function(proceed,element){element=$(element);try{element.offsetParent}
catch(e){return Element._returnOffset(0,0)}
var position=element.getStyle('position');if(position!=='static')return proceed(element);var offsetParent=element.getOffsetParent();if(offsetParent&&offsetParent.getStyle('position')==='fixed')
offsetParent.setStyle({zoom:1});element.setStyle({position:'relative'});var value=proceed(element);element.setStyle({position:position});return value;});});Element.Methods.cumulativeOffset=Element.Methods.cumulativeOffset.wrap(function(proceed,element){try{element.offsetParent}
catch(e){return Element._returnOffset(0,0)}
return proceed(element);});Element.Methods.getStyle=function(element,style){element=$(element);style=(style=='float'||style=='cssFloat')?'styleFloat':style.camelize();var value=element.style[style];if(!value&&element.currentStyle)value=element.currentStyle[style];if(style=='opacity'){if(value=(element.getStyle('filter')||'').match(/alpha\(opacity=(.*)\)/))
if(value[1])return parseFloat(value[1])/100;return 1.0;}
if(value=='auto'){if((style=='width'||style=='height')&&(element.getStyle('display')!='none'))
return element['offset'+style.capitalize()]+'px';return null;}
return value;};Element.Methods.setOpacity=function(element,value){function stripAlpha(filter){return filter.replace(/alpha\([^\)]*\)/gi,'');}
element=$(element);var currentStyle=element.currentStyle;if((currentStyle&&!currentStyle.hasLayout)||(!currentStyle&&element.style.zoom=='normal'))
element.style.zoom=1;var filter=element.getStyle('filter'),style=element.style;if(value==1||value===''){(filter=stripAlpha(filter))?style.filter=filter:style.removeAttribute('filter');return element;}else if(value<0.00001)value=0;style.filter=stripAlpha(filter)+'alpha(opacity='+(value*100)+')';return element;};Element._attributeTranslations={read:{names:{'class':'className','for':'htmlFor'},values:{_getAttr:function(element,attribute){return element.getAttribute(attribute,2);},_getAttrNode:function(element,attribute){var node=element.getAttributeNode(attribute);return node?node.value:"";},_getEv:function(element,attribute){attribute=element.getAttribute(attribute);return attribute?attribute.toString().slice(23,-2):null;},_flag:function(element,attribute){return $(element).hasAttribute(attribute)?attribute:null;},style:function(element){return element.style.cssText.toLowerCase();},title:function(element){return element.title;}}}};Element._attributeTranslations.write={names:Object.extend({cellpadding:'cellPadding',cellspacing:'cellSpacing'},Element._attributeTranslations.read.names),values:{checked:function(element,value){element.checked=!!value;},style:function(element,value){element.style.cssText=value?value:'';}}};Element._attributeTranslations.has={};$w('colSpan rowSpan vAlign dateTime accessKey tabIndex '+'encType maxLength readOnly longDesc frameBorder').each(function(attr){Element._attributeTranslations.write.names[attr.toLowerCase()]=attr;Element._attributeTranslations.has[attr.toLowerCase()]=attr;});(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(element,value){element=$(element);element.style.opacity=(value==1)?0.999999:(value==='')?'':(value<0.00001)?0:value;return element;};}
else if(Prototype.Browser.WebKit){Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;if(value==1)
if(element.tagName.toUpperCase()=='IMG'&&element.width){element.width++;element.width--;}else try{var n=document.createTextNode(' ');element.appendChild(n);element.removeChild(n);}catch(e){}
return element;};Element.Methods.cumulativeOffset=function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body)
if(Element.getStyle(element,'position')=='absolute')break;element=element.offsetParent;}while(element);return Element._returnOffset(valueL,valueT);};}
if(Prototype.Browser.IE||Prototype.Browser.Opera){Element.Methods.update=function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();if(Object.isElement(content))return element.update().insert(content);content=Object.toHTML(content);var tagName=element.tagName.toUpperCase();if(tagName in Element._insertionTranslations.tags){$A(element.childNodes).each(function(node){element.removeChild(node)});Element._getContentFromAnonymousElement(tagName,content.stripScripts()).each(function(node){element.appendChild(node)});}
else element.innerHTML=content.stripScripts();content.evalScripts.bind(content).defer();return element;};}
if('outerHTML'in document.createElement('div')){Element.Methods.replace=function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();if(Object.isElement(content)){element.parentNode.replaceChild(content,element);return element;}
content=Object.toHTML(content);var parent=element.parentNode,tagName=parent.tagName.toUpperCase();if(Element._insertionTranslations.tags[tagName]){var nextSibling=element.next();var fragments=Element._getContentFromAnonymousElement(tagName,content.stripScripts());parent.removeChild(element);if(nextSibling)
fragments.each(function(node){parent.insertBefore(node,nextSibling)});else
fragments.each(function(node){parent.appendChild(node)});}
else element.outerHTML=content.stripScripts();content.evalScripts.bind(content).defer();return element;};}
Element._returnOffset=function(l,t){var result=[l,t];result.left=l;result.top=t;return result;};Element._getContentFromAnonymousElement=function(tagName,html){var div=new Element('div'),t=Element._insertionTranslations.tags[tagName];if(t){div.innerHTML=t[0]+html+t[1];t[2].times(function(){div=div.firstChild});}else div.innerHTML=html;return $A(div.childNodes);};Element._insertionTranslations={before:function(element,node){element.parentNode.insertBefore(node,element);},top:function(element,node){element.insertBefore(node,element.firstChild);},bottom:function(element,node){element.appendChild(node);},after:function(element,node){element.parentNode.insertBefore(node,element.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(element,attribute){attribute=Element._attributeTranslations.has[attribute]||attribute;var node=$(element).getAttributeNode(attribute);return!!(node&&node.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 Methods={},ByTag=Element.Methods.ByTag;var extend=Object.extend(function(element){if(!element||element._extendedByPrototype||element.nodeType!=1||element==window)return element;var methods=Object.clone(Methods),tagName=element.tagName.toUpperCase(),property,value;if(ByTag[tagName])Object.extend(methods,ByTag[tagName]);for(property in methods){value=methods[property];if(Object.isFunction(value)&&!(property in element))
element[property]=value.methodize();}
element._extendedByPrototype=Prototype.emptyFunction;return element;},{refresh:function(){if(!Prototype.BrowserFeatures.ElementExtensions){Object.extend(Methods,Element.Methods);Object.extend(Methods,Element.Methods.Simulated);}}});extend.refresh();return extend;})();Element.hasAttribute=function(element,attribute){if(element.hasAttribute)return element.hasAttribute(attribute);return Element.Methods.Simulated.hasAttribute(element,attribute);};Element.addMethods=function(methods){var F=Prototype.BrowserFeatures,T=Element.Methods.ByTag;if(!methods){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 tagName=methods;methods=arguments[1];}
if(!tagName)Object.extend(Element.Methods,methods||{});else{if(Object.isArray(tagName))tagName.each(extend);else extend(tagName);}
function extend(tagName){tagName=tagName.toUpperCase();if(!Element.Methods.ByTag[tagName])
Element.Methods.ByTag[tagName]={};Object.extend(Element.Methods.ByTag[tagName],methods);}
function copy(methods,destination,onlyIfAbsent){onlyIfAbsent=onlyIfAbsent||false;for(var property in methods){var value=methods[property];if(!Object.isFunction(value))continue;if(!onlyIfAbsent||!(property in destination))
destination[property]=value.methodize();}}
function findDOMClass(tagName){var klass;var trans={"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(trans[tagName])klass='HTML'+trans[tagName]+'Element';if(window[klass])return window[klass];klass='HTML'+tagName+'Element';if(window[klass])return window[klass];klass='HTML'+tagName.capitalize()+'Element';if(window[klass])return window[klass];window[klass]={};window[klass].prototype=document.createElement(tagName)['__proto__'];return window[klass];}
if(F.ElementExtensions){copy(Element.Methods,HTMLElement.prototype);copy(Element.Methods.Simulated,HTMLElement.prototype,true);}
if(F.SpecificElementExtensions){for(var tag in Element.Methods.ByTag){var klass=findDOMClass(tag);if(Object.isUndefined(klass))continue;copy(T[tag],klass.prototype);}}
Object.extend(Element,Element.Methods);delete Element.ByTag;if(Element.extend.refresh)Element.extend.refresh();Element.cache={};};document.viewport={getDimensions:function(){var dimensions={},B=Prototype.Browser;$w('width height').each(function(d){var D=d.capitalize();if(B.WebKit&&!document.evaluate){dimensions[d]=self['inner'+D];}else if(B.Opera&&parseFloat(window.opera.version())<9.5){dimensions[d]=document.body['client'+D]}else{dimensions[d]=document.documentElement['client'+D];}});return dimensions;},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(expression){this.expression=expression.strip();if(this.shouldUseSelectorsAPI()){this.mode='selectorsAPI';}else if(this.shouldUseXPath()){this.mode='xpath';this.compileXPathMatcher();}else{this.mode="normal";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(e))
return false;return true;},shouldUseSelectorsAPI:function(){if(!Prototype.BrowserFeatures.SelectorsAPI)return false;if(!Selector._div)Selector._div=new Element('div');try{Selector._div.querySelector(this.expression);}catch(e){return false;}
return true;},compileMatcher:function(){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(root){root=root||document;var e=this.expression,results;switch(this.mode){case'selectorsAPI':if(root!==document){var oldId=root.id,id=$(root).identify();e="#"+id+" "+e;}
results=$A(root.querySelectorAll(e)).map(Element.extend);root.id=oldId;return results;case'xpath':return document._getElementsByXPath(this.xpath,root);default:return this.matcher(root);}},match:function(element){this.tokens=[];var e=this.expression,ps=Selector.patterns,as=Selector.assertions;var le,p,m;while(e&&le!==e&&(/\S/).test(e)){le=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(element);}}}}
var match=true,name,matches;for(var i=0,token;token=this.tokens[i];i++){name=token[0],matches=token[1];if(!Selector.assertions[name](element,matches)){match=false;break;}}
return match;},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)]",'checked':"[@checked]",'disabled':"[(@disabled) and (@type!='hidden')]",'enabled':"[not(@disabled) and (@type!='hidden')]",'not':function(m){var e=m[6],p=Selector.patterns,x=Selector.xpath,le,v;var exclusion=[];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);exclusion.push("("+v.substring(1,v.length-1)+")");e=e.replace(m[0],'');break;}}}
return"[not("+exclusion.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(fragment,m){var mm,formula=m[6],predicate;if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';if(mm=formula.match(/^(\d+)$/))
return'['+fragment+"= "+mm[1]+']';if(mm=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(mm[1]=="-")mm[1]=-1;var a=mm[1]?Number(mm[1]):1;var b=mm[2]?Number(mm[2]):0;predicate="[((#{fragment} - #{b}) mod #{a} = 0) and "+"((#{fragment} - #{b}) div #{a} >= 0)]";return new Template(predicate).evaluate({fragment:fragment,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]+:)?[\w]+)\]/,attr:/\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/},assertions:{tagName:function(element,matches){return matches[1].toUpperCase()==element.tagName.toUpperCase();},className:function(element,matches){return Element.hasClassName(element,matches[1]);},id:function(element,matches){return element.id===matches[1];},attrPresence:function(element,matches){return Element.hasAttribute(element,matches[1]);},attr:function(element,matches){var nodeValue=Element.readAttribute(element,matches[1]);return nodeValue&&Selector.operators[matches[2]](nodeValue,matches[5]||matches[6]);}},handlers:{concat:function(a,b){for(var i=0,node;node=b[i];i++)
a.push(node);return a;},mark:function(nodes){var _true=Prototype.emptyFunction;for(var i=0,node;node=nodes[i];i++)
node._countedByPrototype=_true;return nodes;},unmark:function(nodes){for(var i=0,node;node=nodes[i];i++)
node._countedByPrototype=undefined;return nodes;},index:function(parentNode,reverse,ofType){parentNode._countedByPrototype=Prototype.emptyFunction;if(reverse){for(var nodes=parentNode.childNodes,i=nodes.length-1,j=1;i>=0;i--){var node=nodes[i];if(node.nodeType==1&&(!ofType||node._countedByPrototype))node.nodeIndex=j++;}}else{for(var i=0,j=1,nodes=parentNode.childNodes;node=nodes[i];i++)
if(node.nodeType==1&&(!ofType||node._countedByPrototype))node.nodeIndex=j++;}},unique:function(nodes){if(nodes.length==0)return nodes;var results=[],n;for(var i=0,l=nodes.length;i<l;i++)
if(!(n=nodes[i])._countedByPrototype){n._countedByPrototype=Prototype.emptyFunction;results.push(Element.extend(n));}
return Selector.handlers.unmark(results);},descendant:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
h.concat(results,node.getElementsByTagName('*'));return results;},child:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[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(nodes){for(var i=0,results=[],node;node=nodes[i];i++){var next=this.nextElementSibling(node);if(next)results.push(next);}
return results;},laterSibling:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
h.concat(results,Element.nextSiblings(node));return results;},nextElementSibling:function(node){while(node=node.nextSibling)
if(node.nodeType==1)return node;return null;},previousElementSibling:function(node){while(node=node.previousSibling)
if(node.nodeType==1)return node;return null;},tagName:function(nodes,root,tagName,combinator){var uTagName=tagName.toUpperCase();var results=[],h=Selector.handlers;if(nodes){if(combinator){if(combinator=="descendant"){for(var i=0,node;node=nodes[i];i++)
h.concat(results,node.getElementsByTagName(tagName));return results;}else nodes=this[combinator](nodes);if(tagName=="*")return nodes;}
for(var i=0,node;node=nodes[i];i++)
if(node.tagName.toUpperCase()===uTagName)results.push(node);return results;}else return root.getElementsByTagName(tagName);},id:function(nodes,root,id,combinator){var targetNode=$(id),h=Selector.handlers;if(!targetNode)return[];if(!nodes&&root==document)return[targetNode];if(nodes){if(combinator){if(combinator=='child'){for(var i=0,node;node=nodes[i];i++)
if(targetNode.parentNode==node)return[targetNode];}else if(combinator=='descendant'){for(var i=0,node;node=nodes[i];i++)
if(Element.descendantOf(targetNode,node))return[targetNode];}else if(combinator=='adjacent'){for(var i=0,node;node=nodes[i];i++)
if(Selector.handlers.previousElementSibling(targetNode)==node)
return[targetNode];}else nodes=h[combinator](nodes);}
for(var i=0,node;node=nodes[i];i++)
if(node==targetNode)return[targetNode];return[];}
return(targetNode&&Element.descendantOf(targetNode,root))?[targetNode]:[];},className:function(nodes,root,className,combinator){if(nodes&&combinator)nodes=this[combinator](nodes);return Selector.handlers.byClassName(nodes,root,className);},byClassName:function(nodes,root,className){if(!nodes)nodes=Selector.handlers.descendant([root]);var needle=' '+className+' ';for(var i=0,results=[],node,nodeClassName;node=nodes[i];i++){nodeClassName=node.className;if(nodeClassName.length==0)continue;if(nodeClassName==className||(' '+nodeClassName+' ').include(needle))
results.push(node);}
return results;},attrPresence:function(nodes,root,attr,combinator){if(!nodes)nodes=root.getElementsByTagName("*");if(nodes&&combinator)nodes=this[combinator](nodes);var results=[];for(var i=0,node;node=nodes[i];i++)
if(Element.hasAttribute(node,attr))results.push(node);return results;},attr:function(nodes,root,attr,value,operator,combinator){if(!nodes)nodes=root.getElementsByTagName("*");if(nodes&&combinator)nodes=this[combinator](nodes);var handler=Selector.operators[operator],results=[];for(var i=0,node;node=nodes[i];i++){var nodeValue=Element.readAttribute(node,attr);if(nodeValue===null)continue;if(handler(nodeValue,value))results.push(node);}
return results;},pseudo:function(nodes,name,value,root,combinator){if(nodes&&combinator)nodes=this[combinator](nodes);if(!nodes)nodes=root.getElementsByTagName("*");return Selector.pseudos[name](nodes,value,root);}},pseudos:{'first-child':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(Selector.handlers.previousElementSibling(node))continue;results.push(node);}
return results;},'last-child':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(Selector.handlers.nextElementSibling(node))continue;results.push(node);}
return results;},'only-child':function(nodes,value,root){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
if(!h.previousElementSibling(node)&&!h.nextElementSibling(node))
results.push(node);return results;},'nth-child':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root);},'nth-last-child':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,true);},'nth-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,false,true);},'nth-last-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,true,true);},'first-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,"1",root,false,true);},'last-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,"1",root,true,true);},'only-of-type':function(nodes,formula,root){var p=Selector.pseudos;return p['last-of-type'](p['first-of-type'](nodes,formula,root),formula,root);},getIndices:function(a,b,total){if(a==0)return b>0?[b]:[];return $R(1,total).inject([],function(memo,i){if(0==(i-b)%a&&(i-b)/a>=0)memo.push(i);return memo;});},nth:function(nodes,formula,root,reverse,ofType){if(nodes.length==0)return[];if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';var h=Selector.handlers,results=[],indexed=[],m;h.mark(nodes);for(var i=0,node;node=nodes[i];i++){if(!node.parentNode._countedByPrototype){h.index(node.parentNode,reverse,ofType);indexed.push(node.parentNode);}}
if(formula.match(/^\d+$/)){formula=Number(formula);for(var i=0,node;node=nodes[i];i++)
if(node.nodeIndex==formula)results.push(node);}else if(m=formula.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 indices=Selector.pseudos.getIndices(a,b,nodes.length);for(var i=0,node,l=indices.length;node=nodes[i];i++){for(var j=0;j<l;j++)
if(node.nodeIndex==indices[j])results.push(node);}}
h.unmark(nodes);h.unmark(indexed);return results;},'empty':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(node.tagName=='!'||node.firstChild)continue;results.push(node);}
return results;},'not':function(nodes,selector,root){var h=Selector.handlers,selectorType,m;var exclusions=new Selector(selector).findElements(root);h.mark(exclusions);for(var i=0,results=[],node;node=nodes[i];i++)
if(!node._countedByPrototype)results.push(node);h.unmark(exclusions);return results;},'enabled':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(!node.disabled&&(!node.type||node.type!=='hidden'))
results.push(node);return results;},'disabled':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(node.disabled)results.push(node);return results;},'checked':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(node.checked)results.push(node);return results;}},operators:{'=':function(nv,v){return nv==v;},'!=':function(nv,v){return nv!=v;},'^=':function(nv,v){return nv==v||nv&&nv.startsWith(v);},'$=':function(nv,v){return nv==v||nv&&nv.endsWith(v);},'*=':function(nv,v){return nv==v||nv&&nv.include(v);},'$=':function(nv,v){return nv.endsWith(v);},'*=':function(nv,v){return nv.include(v);},'~=':function(nv,v){return(' '+nv+' ').include(' '+v+' ');},'|=':function(nv,v){return('-'+(nv||"").toUpperCase()+'-').include('-'+(v||"").toUpperCase()+'-');}},split:function(expression){var expressions=[];expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(m){expressions.push(m[1].strip());});return expressions;},matchElements:function(elements,expression){var matches=$$(expression),h=Selector.handlers;h.mark(matches);for(var i=0,results=[],element;element=elements[i];i++)
if(element._countedByPrototype)results.push(element);h.unmark(matches);return results;},findElement:function(elements,expression,index){if(Object.isNumber(expression)){index=expression;expression=false;}
return Selector.matchElements(elements,expression||'*')[index||0];},findChildElements:function(element,expressions){expressions=Selector.split(expressions.join(','));var results=[],h=Selector.handlers;for(var i=0,l=expressions.length,selector;i<l;i++){selector=new Selector(expressions[i].strip());h.concat(results,selector.findElements(element));}
return(l>1)?h.unique(results):results;}});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(nodes){for(var i=0,node;node=nodes[i];i++)
node.removeAttribute('_countedByPrototype');return nodes;}});}
function $$(){return Selector.findChildElements(document,$A(arguments));}
var Form={reset:function(form){$(form).reset();return form;},serializeElements:function(elements,options){if(typeof options!='object')options={hash:!!options};else if(Object.isUndefined(options.hash))options.hash=true;var key,value,submitted=false,submit=options.submit;var data=elements.inject({},function(result,element){if(!element.disabled&&element.name){key=element.name;value=$(element).getValue();if(value!=null&&element.type!='file'&&(element.type!='submit'||(!submitted&&submit!==false&&(!submit||key==submit)&&(submitted=true)))){if(key in result){if(!Object.isArray(result[key]))result[key]=[result[key]];result[key].push(value);}
else result[key]=value;}}
return result;});return options.hash?data:Object.toQueryString(data);}};Form.Methods={serialize:function(form,options){return Form.serializeElements(Form.getElements(form),options);},getElements:function(form){return $A($(form).getElementsByTagName('*')).inject([],function(elements,child){if(Form.Element.Serializers[child.tagName.toLowerCase()])
elements.push(Element.extend(child));return elements;});},getInputs:function(form,typeName,name){form=$(form);var inputs=form.getElementsByTagName('input');if(!typeName&&!name)return $A(inputs).map(Element.extend);for(var i=0,matchingInputs=[],length=inputs.length;i<length;i++){var input=inputs[i];if((typeName&&input.type!=typeName)||(name&&input.name!=name))
continue;matchingInputs.push(Element.extend(input));}
return matchingInputs;},disable:function(form){form=$(form);Form.getElements(form).invoke('disable');return form;},enable:function(form){form=$(form);Form.getElements(form).invoke('enable');return form;},findFirstElement:function(form){var elements=$(form).getElements().findAll(function(element){return'hidden'!=element.type&&!element.disabled;});var firstByIndex=elements.findAll(function(element){return element.hasAttribute('tabIndex')&&element.tabIndex>=0;}).sortBy(function(element){return element.tabIndex}).first();return firstByIndex?firstByIndex:elements.find(function(element){return['input','select','textarea'].include(element.tagName.toLowerCase());});},focusFirstElement:function(form){form=$(form);form.findFirstElement().activate();return form;},request:function(form,options){form=$(form),options=Object.clone(options||{});var params=options.parameters,action=form.readAttribute('action')||'';if(action.blank())action=window.location.href;options.parameters=form.serialize(true);if(params){if(Object.isString(params))params=params.toQueryParams();Object.extend(options.parameters,params);}
if(form.hasAttribute('method')&&!options.method)
options.method=form.method;return new Ajax.Request(action,options);}};Form.Element={focus:function(element){$(element).focus();return element;},select:function(element){$(element).select();return element;}};Form.Element.Methods={serialize:function(element){element=$(element);if(!element.disabled&&element.name){var value=element.getValue();if(value!=undefined){var pair={};pair[element.name]=value;return Object.toQueryString(pair);}}
return'';},getValue:function(element){element=$(element);var method=element.tagName.toLowerCase();return Form.Element.Serializers[method](element);},setValue:function(element,value){element=$(element);var method=element.tagName.toLowerCase();Form.Element.Serializers[method](element,value);return element;},clear:function(element){$(element).value='';return element;},present:function(element){return $(element).value!='';},activate:function(element){element=$(element);try{element.focus();if(element.select&&(element.tagName.toLowerCase()!='input'||!['button','reset','submit'].include(element.type)))
element.select();}catch(e){}
return element;},disable:function(element){element=$(element);element.disabled=true;return element;},enable:function(element){element=$(element);element.disabled=false;return element;}};var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers={input:function(element,value){switch(element.type.toLowerCase()){case'checkbox':case'radio':return Form.Element.Serializers.inputSelector(element,value);default:return Form.Element.Serializers.textarea(element,value);}},inputSelector:function(element,value){if(Object.isUndefined(value))return element.checked?element.value:null;else element.checked=!!value;},textarea:function(element,value){if(Object.isUndefined(value))return element.value;else element.value=value;},select:function(element,value){if(Object.isUndefined(value))
return this[element.type=='select-one'?'selectOne':'selectMany'](element);else{var opt,currentValue,single=!Object.isArray(value);for(var i=0,length=element.length;i<length;i++){opt=element.options[i];currentValue=this.optionValue(opt);if(single){if(currentValue==value){opt.selected=true;return;}}
else opt.selected=value.include(currentValue);}}},selectOne:function(element){var index=element.selectedIndex;return index>=0?this.optionValue(element.options[index]):null;},selectMany:function(element){var values,length=element.length;if(!length)return null;for(var i=0,values=[];i<length;i++){var opt=element.options[i];if(opt.selected)values.push(this.optionValue(opt));}
return values;},optionValue:function(opt){return Element.extend(opt).hasAttribute('value')?opt.value:opt.text;}};Abstract.TimedObserver=Class.create(PeriodicalExecuter,{initialize:function($super,element,frequency,callback){$super(callback,frequency);this.element=$(element);this.lastValue=this.getValue();},execute:function(){var value=this.getValue();if(Object.isString(this.lastValue)&&Object.isString(value)?this.lastValue!=value:String(this.lastValue)!=String(value)){this.callback(this.element,value);this.lastValue=value;}}});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(element,callback){this.element=$(element);this.callback=callback;this.lastValue=this.getValue();if(this.element.tagName.toLowerCase()=='form')
this.registerFormCallbacks();else
this.registerCallback(this.element);},onElementEvent:function(){var value=this.getValue();if(this.lastValue!=value){this.callback(this.element,value);this.lastValue=value;}},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback,this);},registerCallback:function(element){if(element.type){switch(element.type.toLowerCase()){case'checkbox':case'radio':Event.observe(element,'click',this.onElementEvent.bind(this));break;default:Event.observe(element,'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(event){var element;switch(event.type){case'mouseover':element=event.fromElement;break;case'mouseout':element=event.toElement;break;default:return null;}
return Element.extend(element);}});Event.Methods=(function(){var isButton;if(Prototype.Browser.IE){var buttonMap={0:1,1:4,2:2};isButton=function(event,code){return event.button==buttonMap[code];};}else if(Prototype.Browser.WebKit){isButton=function(event,code){switch(code){case 0:return event.which==1&&!event.metaKey;case 1:return event.which==1&&event.metaKey;default:return false;}};}else{isButton=function(event,code){return event.which?(event.which===code+1):(event.button===code);};}
return{isLeftClick:function(event){return isButton(event,0)},isMiddleClick:function(event){return isButton(event,1)},isRightClick:function(event){return isButton(event,2)},element:function(event){event=Event.extend(event);var node=event.target,type=event.type,currentTarget=event.currentTarget;if(currentTarget&&currentTarget.tagName){if(type==='load'||type==='error'||(type==='click'&&currentTarget.tagName.toLowerCase()==='input'&&currentTarget.type==='radio'))
node=currentTarget;}
if(node.nodeType==Node.TEXT_NODE)node=node.parentNode;return Element.extend(node);},findElement:function(event,expression){var element=Event.element(event);if(!expression)return element;var elements=[element].concat(element.ancestors());return Selector.findElement(elements,expression,0);},pointer:function(event){var docElement=document.documentElement,body=document.body||{scrollLeft:0,scrollTop:0};return{x:event.pageX||(event.clientX+
(docElement.scrollLeft||body.scrollLeft)-
(docElement.clientLeft||0)),y:event.pageY||(event.clientY+
(docElement.scrollTop||body.scrollTop)-
(docElement.clientTop||0))};},pointerX:function(event){return Event.pointer(event).x},pointerY:function(event){return Event.pointer(event).y},stop:function(event){Event.extend(event);event.preventDefault();event.stopPropagation();event.stopped=true;}};})();Event.extend=(function(){var methods=Object.keys(Event.Methods).inject({},function(m,name){m[name]=Event.Methods[name].methodize();return m;});if(Prototype.Browser.IE){Object.extend(methods,{stopPropagation:function(){this.cancelBubble=true},preventDefault:function(){this.returnValue=false},inspect:function(){return"[object Event]"}});return function(event){if(!event)return false;if(event._extendedByPrototype)return event;event._extendedByPrototype=Prototype.emptyFunction;var pointer=Event.pointer(event);Object.extend(event,{target:event.srcElement,relatedTarget:Event.relatedTarget(event),pageX:pointer.x,pageY:pointer.y});return Object.extend(event,methods);};}else{Event.prototype=Event.prototype||document.createEvent("HTMLEvents")['__proto__'];Object.extend(Event.prototype,methods);return Prototype.K;}})();Object.extend(Event,(function(){var cache=Event.cache;function getEventID(element){if(element._prototypeEventID)return element._prototypeEventID[0];arguments.callee.id=arguments.callee.id||1;return element._prototypeEventID=[++arguments.callee.id];}
function getDOMEventName(eventName){if(eventName&&eventName.include(':'))return"dataavailable";return eventName;}
function getCacheForID(id){return cache[id]=cache[id]||{};}
function getWrappersForEventName(id,eventName){var c=getCacheForID(id);return c[eventName]=c[eventName]||[];}
function createWrapper(element,eventName,handler){var id=getEventID(element);var c=getWrappersForEventName(id,eventName);if(c.pluck("handler").include(handler))return false;var wrapper=function(event){if(!Event||!Event.extend||(event.eventName&&event.eventName!=eventName))
return false;Event.extend(event);handler.call(element,event);};wrapper.handler=handler;c.push(wrapper);return wrapper;}
function findWrapper(id,eventName,handler){var c=getWrappersForEventName(id,eventName);return c.find(function(wrapper){return wrapper.handler==handler});}
function destroyWrapper(id,eventName,handler){var c=getCacheForID(id);if(!c[eventName])return false;c[eventName]=c[eventName].without(findWrapper(id,eventName,handler));}
function destroyCache(){for(var id in cache)
for(var eventName in cache[id])
cache[id][eventName]=null;}
if(window.attachEvent){window.attachEvent("onunload",destroyCache);}
if(Prototype.Browser.WebKit){window.addEventListener('unload',Prototype.emptyFunction,false);}
return{observe:function(element,eventName,handler){element=$(element);var name=getDOMEventName(eventName);var wrapper=createWrapper(element,eventName,handler);if(!wrapper)return element;if(element.addEventListener){element.addEventListener(name,wrapper,false);}else{element.attachEvent("on"+name,wrapper);}
return element;},stopObserving:function(element,eventName,handler){element=$(element);var id=getEventID(element),name=getDOMEventName(eventName);if(!handler&&eventName){getWrappersForEventName(id,eventName).each(function(wrapper){element.stopObserving(eventName,wrapper.handler);});return element;}else if(!eventName){Object.keys(getCacheForID(id)).each(function(eventName){element.stopObserving(eventName);});return element;}
var wrapper=findWrapper(id,eventName,handler);if(!wrapper)return element;if(element.removeEventListener){element.removeEventListener(name,wrapper,false);}else{element.detachEvent("on"+name,wrapper);}
destroyWrapper(id,eventName,handler);return element;},fire:function(element,eventName,memo){element=$(element);if(element==document&&document.createEvent&&!element.dispatchEvent)
element=document.documentElement;var event;if(document.createEvent){event=document.createEvent("HTMLEvents");event.initEvent("dataavailable",true,true);}else{event=document.createEventObject();event.eventType="ondataavailable";}
event.eventName=eventName;event.memo=memo||{};if(document.createEvent){element.dispatchEvent(event);}else{element.fireEvent(event.eventType,event);}
return Event.extend(event);}};})());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 timer;function fireContentLoadedEvent(){if(document.loaded)return;if(timer)window.clearInterval(timer);document.fire("dom:loaded");document.loaded=true;}
if(document.addEventListener){if(Prototype.Browser.WebKit){timer=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(element,content){return Element.insert(element,{before:content});},Top:function(element,content){return Element.insert(element,{top:content});},Bottom:function(element,content){return Element.insert(element,{bottom:content});},After:function(element,content){return Element.insert(element,{after:content});}};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(element,x,y){if(this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element,x,y);this.xcomp=x;this.ycomp=y;this.offset=Element.cumulativeOffset(element);return(y>=this.offset[1]&&y<this.offset[1]+element.offsetHeight&&x>=this.offset[0]&&x<this.offset[0]+element.offsetWidth);},withinIncludingScrolloffsets:function(element,x,y){var offsetcache=Element.cumulativeScrollOffset(element);this.xcomp=x+offsetcache[0]-this.deltaX;this.ycomp=y+offsetcache[1]-this.deltaY;this.offset=Element.cumulativeOffset(element);return(this.ycomp>=this.offset[1]&&this.ycomp<this.offset[1]+element.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+element.offsetWidth);},overlap:function(mode,element){if(!mode)return 0;if(mode=='vertical')
return((this.offset[1]+element.offsetHeight)-this.ycomp)/element.offsetHeight;if(mode=='horizontal')
return((this.offset[0]+element.offsetWidth)-this.xcomp)/element.offsetWidth;},cumulativeOffset:Element.Methods.cumulativeOffset,positionedOffset:Element.Methods.positionedOffset,absolutize:function(element){Position.prepare();return Element.absolutize(element);},relativize:function(element){Position.prepare();return Element.relativize(element);},realOffset:Element.Methods.cumulativeScrollOffset,offsetParent:Element.Methods.getOffsetParent,page:Element.Methods.viewportOffset,clone:function(source,target,options){options=options||{};return Element.clonePosition(target,source,options);}};if(!document.getElementsByClassName)document.getElementsByClassName=function(instanceMethods){function iter(name){return name.blank()?null:"[contains(concat(' ', @class, ' '), ' "+name+" ')]";}
instanceMethods.getElementsByClassName=Prototype.BrowserFeatures.XPath?function(element,className){className=className.toString().strip();var cond=/\s/.test(className)?$w(className).map(iter).join(''):iter(className);return cond?document._getElementsByXPath('.//*'+cond,element):[];}:function(element,className){className=className.toString().strip();var elements=[],classNames=(/\s/.test(className)?$w(className):null);if(!classNames&&!className)return elements;var nodes=$(element).getElementsByTagName('*');className=' '+className+' ';for(var i=0,child,cn;child=nodes[i];i++){if(child.className&&(cn=' '+child.className+' ')&&(cn.include(className)||(classNames&&classNames.all(function(name){return!name.toString().blank()&&cn.include(' '+name+' ');}))))
elements.push(Element.extend(child));}
return elements;};return function(className,parentElement){return $(parentElement||document.body).getElementsByClassName(className);};}(Element.Methods);Element.ClassNames=Class.create();Element.ClassNames.prototype={initialize:function(element){this.element=$(element);},_each:function(iterator){this.element.className.split(/\s+/).select(function(name){return name.length>0;})._each(iterator);},set:function(className){this.element.className=className;},add:function(classNameToAdd){if(this.include(classNameToAdd))return;this.set($A(this).concat(classNameToAdd).join(' '));},remove:function(classNameToRemove){if(!this.include(classNameToRemove))return;this.set($A(this).without(classNameToRemove).join(' '));},toString:function(){return $A(this).join(' ');}};Object.extend(Element.ClassNames.prototype,Enumerable);Element.addMethods();var Scriptaculous={Version:'1.8.2',require:function(libraryName){document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');},REQUIRED_PROTOTYPE:'1.6.0.3',load:function(){function convertVersionString(versionString){var v=versionString.replace(/_.*|\./g,'');v=parseInt(v+'0'.times(4-v.length));return versionString.indexOf('_')>-1?v-1:v;}
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 js=/scriptaculous\.js(\?.*)?$/;$$('head script[src]').findAll(function(s){return s.src.match(js);}).each(function(s){var path=s.src.replace(js,''),includes=s.src.match(/\?.*load=([a-z,]*)/);(includes?includes[1]:'builder,effects,dragdrop,controls,slider').split(',').each(function(include){Scriptaculous.require(path+include+'.js')});});}};Scriptaculous.load();String.prototype.parseColor=function(){var color='#';if(this.slice(0,4)=='rgb('){var cols=this.slice(4,this.length-1).split(',');var i=0;do{color+=parseInt(cols[i]).toColorPart()}while(++i<3);}else{if(this.slice(0,1)=='#'){if(this.length==4)for(var i=1;i<4;i++)color+=(this.charAt(i)+this.charAt(i)).toLowerCase();if(this.length==7)color=this.toLowerCase();}}
return(color.length==7?color:(arguments[0]||this));};Element.collectTextNodes=function(element){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:(node.hasChildNodes()?Element.collectTextNodes(node):''));}).flatten().join('');};Element.collectTextNodesIgnoreClass=function(element,className){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:((node.hasChildNodes()&&!Element.hasClassName(node,className))?Element.collectTextNodesIgnoreClass(node,className):''));}).flatten().join('');};Element.setContentZoom=function(element,percent){element=$(element);element.setStyle({fontSize:(percent/100)+'em'});if(Prototype.Browser.WebKit)window.scrollBy(0,0);return element;};Element.getInlineOpacity=function(element){return $(element).style.opacity||'';};Element.forceRerendering=function(element){try{element=$(element);var n=document.createTextNode(' ');element.appendChild(n);element.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(pos){return(-Math.cos(pos*Math.PI)/2)+.5;},reverse:function(pos){return 1-pos;},flicker:function(pos){var pos=((-Math.cos(pos*Math.PI)/4)+.75)+Math.random()/4;return pos>1?1:pos;},wobble:function(pos){return(-Math.cos(pos*Math.PI*(9*pos))/2)+.5;},pulse:function(pos,pulses){return(-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2)+.5;},spring:function(pos){return 1-(Math.cos(pos*4.5*Math.PI)*Math.exp(-pos*6));},none:function(pos){return 0;},full:function(pos){return 1;}},DefaultOptions:{duration:1.0,fps:100,sync:false,from:0.0,to:1.0,delay:0.0,queue:'parallel'},tagifyText:function(element){var tagifyStyle='position:relative';if(Prototype.Browser.IE)tagifyStyle+=';zoom:1';element=$(element);$A(element.childNodes).each(function(child){if(child.nodeType==3){child.nodeValue.toArray().each(function(character){element.insertBefore(new Element('span',{style:tagifyStyle}).update(character==' '?String.fromCharCode(160):character),child);});Element.remove(child);}});},multiple:function(element,effect){var elements;if(((typeof element=='object')||Object.isFunction(element))&&(element.length))
elements=element;else
elements=$(element).childNodes;var options=Object.extend({speed:0.1,delay:0.0},arguments[2]||{});var masterDelay=options.delay;$A(elements).each(function(element,index){new effect(element,Object.extend(options,{delay:index*options.speed+masterDelay}));});},PAIRS:{'slide':['SlideDown','SlideUp'],'blind':['BlindDown','BlindUp'],'appear':['Appear','Fade']},toggle:function(element,effect){element=$(element);effect=(effect||'appear').toLowerCase();var options=Object.extend({queue:{position:'end',scope:(element.id||'global'),limit:1}},arguments[2]||{});Effect[element.visible()?Effect.PAIRS[effect][1]:Effect.PAIRS[effect][0]](element,options);}};Effect.DefaultOptions.transition=Effect.Transitions.sinoidal;Effect.ScopedQueue=Class.create(Enumerable,{initialize:function(){this.effects=[];this.interval=null;},_each:function(iterator){this.effects._each(iterator);},add:function(effect){var timestamp=new Date().getTime();var position=Object.isString(effect.options.queue)?effect.options.queue:effect.options.queue.position;switch(position){case'front':this.effects.findAll(function(e){return e.state=='idle'}).each(function(e){e.startOn+=effect.finishOn;e.finishOn+=effect.finishOn;});break;case'with-last':timestamp=this.effects.pluck('startOn').max()||timestamp;break;case'end':timestamp=this.effects.pluck('finishOn').max()||timestamp;break;}
effect.startOn+=timestamp;effect.finishOn+=timestamp;if(!effect.options.queue.limit||(this.effects.length<effect.options.queue.limit))
this.effects.push(effect);if(!this.interval)
this.interval=setInterval(this.loop.bind(this),15);},remove:function(effect){this.effects=this.effects.reject(function(e){return e==effect});if(this.effects.length==0){clearInterval(this.interval);this.interval=null;}},loop:function(){var timePos=new Date().getTime();for(var i=0,len=this.effects.length;i<len;i++)
this.effects[i]&&this.effects[i].loop(timePos);}});Effect.Queues={instances:$H(),get:function(queueName){if(!Object.isString(queueName))return queueName;return this.instances.get(queueName)||this.instances.set(queueName,new Effect.ScopedQueue());}};Effect.Queue=Effect.Queues.get('global');Effect.Base=Class.create({position:null,start:function(options){function codeForEvent(options,eventName){return((options[eventName+'Internal']?'this.options.'+eventName+'Internal(this);':'')+
(options[eventName]?'this.options.'+eventName+'(this);':''));}
if(options&&options.transition===false)options.transition=Effect.Transitions.linear;this.options=Object.extend(Object.extend({},Effect.DefaultOptions),options||{});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;this.render=(function(){function dispatch(effect,eventName){if(effect.options[eventName+'Internal'])
effect.options[eventName+'Internal'](effect);if(effect.options[eventName])
effect.options[eventName](effect);}
return function(pos){if(this.state==="idle"){this.state="running";dispatch(this,'beforeSetup');if(this.setup)this.setup();dispatch(this,'afterSetup');}
if(this.state==="running"){pos=(this.options.transition(pos)*this.fromToDelta)+this.options.from;this.position=pos;dispatch(this,'beforeUpdate');if(this.update)this.update(pos);dispatch(this,'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(timePos){if(timePos>=this.startOn){if(timePos>=this.finishOn){this.render(1.0);this.cancel();this.event('beforeFinish');if(this.finish)this.finish();this.event('afterFinish');return;}
var pos=(timePos-this.startOn)/this.totalTime,frame=(pos*this.totalFrames).round();if(frame>this.currentFrame){this.render(pos);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(eventName){if(this.options[eventName+'Internal'])this.options[eventName+'Internal'](this);if(this.options[eventName])this.options[eventName](this);},inspect:function(){var data=$H();for(property in this)
if(!Object.isFunction(this[property]))data.set(property,this[property]);return'#<Effect:'+data.inspect()+',options:'+$H(this.options).inspect()+'>';}});Effect.Parallel=Class.create(Effect.Base,{initialize:function(effects){this.effects=effects||[];this.start(arguments[1]);},update:function(position){this.effects.invoke('render',position);},finish:function(position){this.effects.each(function(effect){effect.render(1.0);effect.cancel();effect.event('beforeFinish');if(effect.finish)effect.finish(position);effect.event('afterFinish');});}});Effect.Tween=Class.create(Effect.Base,{initialize:function(object,from,to){object=Object.isString(object)?$(object):object;var args=$A(arguments),method=args.last(),options=args.length==5?args[3]:null;this.method=Object.isFunction(method)?method.bind(object):Object.isFunction(object[method])?object[method].bind(object):function(value){object[method]=value};this.start(Object.extend({from:from,to:to},options||{}));},update:function(position){this.method(position);}});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(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});var options=Object.extend({from:this.element.getOpacity()||0.0,to:1.0},arguments[1]||{});this.start(options);},update:function(position){this.element.setOpacity(position);}});Effect.Move=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({x:0,y:0,mode:'relative'},arguments[1]||{});this.start(options);},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(position){this.element.setStyle({left:(this.options.x*position+this.originalLeft).round()+'px',top:(this.options.y*position+this.originalTop).round()+'px'});}});Effect.MoveBy=function(element,toTop,toLeft){return new Effect.Move(element,Object.extend({x:toLeft,y:toTop},arguments[3]||{}));};Effect.Scale=Class.create(Effect.Base,{initialize:function(element,percent){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({scaleX:true,scaleY:true,scaleContent:true,scaleFromCenter:false,scaleMode:'box',scaleFrom:100.0,scaleTo:percent},arguments[2]||{});this.start(options);},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 fontSize=this.element.getStyle('font-size')||'100%';['em','px','%','pt'].each(function(fontSizeType){if(fontSize.indexOf(fontSizeType)>0){this.fontSize=parseFloat(fontSize);this.fontSizeType=fontSizeType;}}.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(position){var currentScale=(this.options.scaleFrom/100.0)+(this.factor*position);if(this.options.scaleContent&&this.fontSize)
this.element.setStyle({fontSize:this.fontSize*currentScale+this.fontSizeType});this.setDimensions(this.dims[0]*currentScale,this.dims[1]*currentScale);},finish:function(position){if(this.restoreAfterFinish)this.element.setStyle(this.originalStyle);},setDimensions:function(height,width){var d={};if(this.options.scaleX)d.width=width.round()+'px';if(this.options.scaleY)d.height=height.round()+'px';if(this.options.scaleFromCenter){var topd=(height-this.dims[0])/2;var leftd=(width-this.dims[1])/2;if(this.elementPositioning=='absolute'){if(this.options.scaleY)d.top=this.originalTop-topd+'px';if(this.options.scaleX)d.left=this.originalLeft-leftd+'px';}else{if(this.options.scaleY)d.top=-topd+'px';if(this.options.scaleX)d.left=-leftd+'px';}}
this.element.setStyle(d);}});Effect.Highlight=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({startcolor:'#ffff99'},arguments[1]||{});this.start(options);},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(position){this.element.setStyle({backgroundColor:$R(0,2).inject('#',function(m,v,i){return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart());}.bind(this))});},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}));}});Effect.ScrollTo=function(element){var options=arguments[1]||{},scrollOffsets=document.viewport.getScrollOffsets(),elementOffsets=$(element).cumulativeOffset();if(options.offset)elementOffsets[1]+=options.offset;return new Effect.Tween(null,scrollOffsets.top,elementOffsets[1],options,function(p){scrollTo(scrollOffsets.left,p.round());});};Effect.Fade=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();var options=Object.extend({from:element.getOpacity()||1.0,to:0.0,afterFinishInternal:function(effect){if(effect.options.to!=0)return;effect.element.hide().setStyle({opacity:oldOpacity});}},arguments[1]||{});return new Effect.Opacity(element,options);};Effect.Appear=function(element){element=$(element);var options=Object.extend({from:(element.getStyle('display')=='none'?0.0:element.getOpacity()||0.0),to:1.0,afterFinishInternal:function(effect){effect.element.forceRerendering();},beforeSetup:function(effect){effect.element.setOpacity(effect.options.from).show();}},arguments[1]||{});return new Effect.Opacity(element,options);};Effect.Puff=function(element){element=$(element);var oldStyle={opacity:element.getInlineOpacity(),position:element.getStyle('position'),top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};return new Effect.Parallel([new Effect.Scale(element,200,{sync:true,scaleFromCenter:true,scaleContent:true,restoreAfterFinish:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:1.0,beforeSetupInternal:function(effect){Position.absolutize(effect.effects[0].element);},afterFinishInternal:function(effect){effect.effects[0].element.hide().setStyle(oldStyle);}},arguments[1]||{}));};Effect.BlindUp=function(element){element=$(element);element.makeClipping();return new Effect.Scale(element,0,Object.extend({scaleContent:false,scaleX:false,restoreAfterFinish:true,afterFinishInternal:function(effect){effect.element.hide().undoClipping();}},arguments[1]||{}));};Effect.BlindDown=function(element){element=$(element);var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:0,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makeClipping().setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.element.undoClipping();}},arguments[1]||{}));};Effect.SwitchOff=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();return new Effect.Appear(element,Object.extend({duration:0.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(effect){new Effect.Scale(effect.element,1,{duration:0.3,scaleFromCenter:true,scaleX:false,scaleContent:false,restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned().setStyle({opacity:oldOpacity});}});}},arguments[1]||{}));};Effect.DropOut=function(element){element=$(element);var oldStyle={top:element.getStyle('top'),left:element.getStyle('left'),opacity:element.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(element,{x:0,y:100,sync:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:0.5,beforeSetup:function(effect){effect.effects[0].element.makePositioned();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);}},arguments[1]||{}));};Effect.Shake=function(element){element=$(element);var options=Object.extend({distance:20,duration:0.5},arguments[1]||{});var distance=parseFloat(options.distance);var split=parseFloat(options.duration)/10.0;var oldStyle={top:element.getStyle('top'),left:element.getStyle('left')};return new Effect.Move(element,{x:distance,y:0,duration:split,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance,y:0,duration:split,afterFinishInternal:function(effect){effect.element.undoPositioned().setStyle(oldStyle);}});}});}});}});}});}});};Effect.SlideDown=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().setStyle({height:'0px'}).show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));};Effect.SlideUp=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:'box',scaleFrom:100,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));};Effect.Squish=function(element){return new Effect.Scale(element,window.opera?1:0,{restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping();}});};Effect.Grow=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var initialMoveX,initialMoveY;var moveX,moveY;switch(options.direction){case'top-left':initialMoveX=initialMoveY=moveX=moveY=0;break;case'top-right':initialMoveX=dims.width;initialMoveY=moveY=0;moveX=-dims.width;break;case'bottom-left':initialMoveX=moveX=0;initialMoveY=dims.height;moveY=-dims.height;break;case'bottom-right':initialMoveX=dims.width;initialMoveY=dims.height;moveX=-dims.width;moveY=-dims.height;break;case'center':initialMoveX=dims.width/2;initialMoveY=dims.height/2;moveX=-dims.width/2;moveY=-dims.height/2;break;}
return new Effect.Move(element,{x:initialMoveX,y:initialMoveY,duration:0.01,beforeSetup:function(effect){effect.element.hide().makeClipping().makePositioned();},afterFinishInternal:function(effect){new Effect.Parallel([new Effect.Opacity(effect.element,{sync:true,to:1.0,from:0.0,transition:options.opacityTransition}),new Effect.Move(effect.element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition}),new Effect.Scale(effect.element,100,{scaleMode:{originalHeight:dims.height,originalWidth:dims.width},sync:true,scaleFrom:window.opera?1:0,transition:options.scaleTransition,restoreAfterFinish:true})],Object.extend({beforeSetup:function(effect){effect.effects[0].element.setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);}},options));}});};Effect.Shrink=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var moveX,moveY;switch(options.direction){case'top-left':moveX=moveY=0;break;case'top-right':moveX=dims.width;moveY=0;break;case'bottom-left':moveX=0;moveY=dims.height;break;case'bottom-right':moveX=dims.width;moveY=dims.height;break;case'center':moveX=dims.width/2;moveY=dims.height/2;break;}
return new Effect.Parallel([new Effect.Opacity(element,{sync:true,to:0.0,from:1.0,transition:options.opacityTransition}),new Effect.Scale(element,window.opera?1:0,{sync:true,transition:options.scaleTransition,restoreAfterFinish:true}),new Effect.Move(element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition})],Object.extend({beforeStartInternal:function(effect){effect.effects[0].element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle);}},options));};Effect.Pulsate=function(element){element=$(element);var options=arguments[1]||{},oldOpacity=element.getInlineOpacity(),transition=options.transition||Effect.Transitions.linear,reverser=function(pos){return 1-transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2)+.5);};return new Effect.Opacity(element,Object.extend(Object.extend({duration:2.0,from:0,afterFinishInternal:function(effect){effect.element.setStyle({opacity:oldOpacity});}},options),{transition:reverser}));};Effect.Fold=function(element){element=$(element);var oldStyle={top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};element.makeClipping();return new Effect.Scale(element,5,Object.extend({scaleContent:false,scaleX:false,afterFinishInternal:function(effect){new Effect.Scale(element,1,{scaleContent:false,scaleY:false,afterFinishInternal:function(effect){effect.element.hide().undoClipping().setStyle(oldStyle);}});}},arguments[1]||{}));};Effect.Morph=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({style:{}},arguments[1]||{});if(!Object.isString(options.style))this.style=$H(options.style);else{if(options.style.include(':'))
this.style=options.style.parseStyle();else{this.element.addClassName(options.style);this.style=$H(this.element.getStyles());this.element.removeClassName(options.style);var css=this.element.getStyles();this.style=this.style.reject(function(style){return style.value==css[style.key];});options.afterFinishInternal=function(effect){effect.element.addClassName(effect.options.style);effect.transforms.each(function(transform){effect.element.style[transform.style]='';});};}}
this.start(options);},setup:function(){function parseColor(color){if(!color||['rgba(0, 0, 0, 0)','transparent'].include(color))color='#ffffff';color=color.parseColor();return $R(0,2).map(function(i){return parseInt(color.slice(i*2+1,i*2+3),16);});}
this.transforms=this.style.map(function(pair){var property=pair[0],value=pair[1],unit=null;if(value.parseColor('#zzzzzz')!='#zzzzzz'){value=value.parseColor();unit='color';}else if(property=='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 components=value.match(/^([\+\-]?[0-9\.]+)(.*)$/);value=parseFloat(components[1]);unit=(components.length==3)?components[2]:null;}
var originalValue=this.element.getStyle(property);return{style:property.camelize(),originalValue:unit=='color'?parseColor(originalValue):parseFloat(originalValue||0),targetValue:unit=='color'?parseColor(value):value,unit:unit};}.bind(this)).reject(function(transform){return((transform.originalValue==transform.targetValue)||(transform.unit!='color'&&(isNaN(transform.originalValue)||isNaN(transform.targetValue))));});},update:function(position){var style={},transform,i=this.transforms.length;while(i--)
style[(transform=this.transforms[i]).style]=transform.unit=='color'?'#'+
(Math.round(transform.originalValue[0]+
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart()+
(Math.round(transform.originalValue[1]+
(transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart()+
(Math.round(transform.originalValue[2]+
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart():(transform.originalValue+
(transform.targetValue-transform.originalValue)*position).toFixed(3)+
(transform.unit===null?'':transform.unit);this.element.setStyle(style,true);}});Effect.Transform=Class.create({initialize:function(tracks){this.tracks=[];this.options=arguments[1]||{};this.addTracks(tracks);},addTracks:function(tracks){tracks.each(function(track){track=$H(track);var data=track.values().first();this.tracks.push($H({ids:track.keys().first(),effect:Effect.Morph,options:{style:data}}));}.bind(this));return this;},play:function(){return new Effect.Parallel(this.tracks.map(function(track){var ids=track.get('ids'),effect=track.get('effect'),options=track.get('options');var elements=[$(ids)||$$(ids)].flatten();return elements.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 style,styleRules=$H();if(Prototype.Browser.WebKit)
style=new Element('div',{style:this}).style;else{String.__parseStyleElement.innerHTML='<div style="'+this+'"></div>';style=String.__parseStyleElement.childNodes[0].style;}
Element.CSS_PROPERTIES.each(function(property){if(style[property])styleRules.set(property,style[property]);});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(element){var css=document.defaultView.getComputedStyle($(element),null);return Element.CSS_PROPERTIES.inject({},function(styles,property){styles[property]=css[property];return styles;});};}else{Element.getStyles=function(element){element=$(element);var css=element.currentStyle,styles;styles=Element.CSS_PROPERTIES.inject({},function(results,property){results[property]=css[property];return results;});if(!styles.opacity)styles.opacity=element.getOpacity();return styles;};}
Effect.Methods={morph:function(element,style){element=$(element);new Effect.Morph(element,Object.extend({style:style},arguments[2]||{}));return element;},visualEffect:function(element,effect,options){element=$(element);var s=effect.dasherize().camelize(),klass=s.charAt(0).toUpperCase()+s.substring(1);new Effect[klass](element,options);return element;},highlight:function(element,options){element=$(element);new Effect.Highlight(element,options);return element;}};$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+'pulsate shake puff squish switchOff dropOut').each(function(effect){Effect.Methods[effect]=function(element,options){element=$(element);Effect[effect.charAt(0).toUpperCase()+effect.substring(1)](element,options);return element;};});$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(function(f){Effect.Methods[f]=Element[f];});Element.addMethods(Effect.Methods);Effect.Scroll=Class.create();Object.extend(Object.extend(Effect.Scroll.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);var options=Object.extend({x:0,y:0,mode:'absolute'},arguments[1]||{});this.start(options);},setup:function(){if(this.options.continuous&&!this.element._ext){this.element.cleanWhitespace();this.element._ext=true;this.element.appendChild(this.element.firstChild);}
this.originalLeft=this.element.scrollLeft;this.originalTop=this.element.scrollTop;if(this.options.mode=='absolute'){this.options.x-=this.originalLeft;this.options.y-=this.originalTop;}else{}},update:function(position){this.element.scrollLeft=this.options.x*position+this.originalLeft;this.element.scrollTop=this.options.y*position+this.originalTop;}});if(typeof Effect=='undefined')
throw("accordion.js requires including script.aculo.us' effects.js library!");var accordion=Class.create();accordion.prototype={showAccordion:null,currentAccordion:null,duration:null,effects:[],animating:false,initialize:function(container,options){if(!$(container)){throw(container+" doesn't exist!");return false;}
this.options=Object.extend({resizeSpeed:8,classNames:{toggle:'accordion_toggle',toggleActive:'accordion_toggle_active',content:'accordion_content'},defaultSize:{height:null,width:null},direction:'vertical',onEvent:'click'},options||{});this.duration=((11-this.options.resizeSpeed)*0.15);var accordions=$$('#'+container+' .'+this.options.classNames.toggle);accordions.each(function(accordion){Event.observe(accordion,this.options.onEvent,this.activate.bind(this,accordion),false);if(this.options.onEvent=='click'){accordion.onclick=function(){return false;};}
if(this.options.direction=='horizontal'){var options={width:'0px',display:'none'};}else{var options={height:'0px',display:'none'};}
this.currentAccordion=$(accordion.next(0)).setStyle(options);}.bind(this));},activate:function(accordion){if(this.animating){return false;}
this.effects=[];this.currentAccordion=$(accordion.next(0));this.currentAccordion.setStyle({display:'block'});this.currentAccordion.previous(0).addClassName(this.options.classNames.toggleActive);if(this.options.direction=='horizontal'){this.scaling=$H({scaleX:true,scaleY:false});}else{this.scaling=$H({scaleX:false,scaleY:true});}
if(this.currentAccordion==this.showAccordion){this.deactivate();}else{this._handleAccordion();}},deactivate:function(){var options=$H({duration:this.duration,scaleContent:false,transition:Effect.Transitions.sinoidal,queue:{position:'end',scope:'accordionAnimation'},scaleMode:{originalHeight:this.options.defaultSize.height?this.options.defaultSize.height:this.currentAccordion.scrollHeight,originalWidth:this.options.defaultSize.width?this.options.defaultSize.width:this.currentAccordion.scrollWidth},afterFinish:function(){if(this.showAccordion){this.showAccordion.setStyle({height:'100%',display:'none'});this.showAccordion=null;this.animating=false;}}.bind(this)});this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);new Effect.Scale(this.showAccordion,0,options.update(this.scaling).toObject());},_handleAccordion:function(){var options=$H({sync:true,scaleFrom:0,scaleContent:false,transition:Effect.Transitions.sinoidal,scaleMode:{originalHeight:this.options.defaultSize.height?this.options.defaultSize.height:this.currentAccordion.scrollHeight,originalWidth:this.options.defaultSize.width?this.options.defaultSize.width:this.currentAccordion.scrollWidth}});options.merge(this.scaling);this.effects.push(new Effect.Scale(this.currentAccordion,100,options.update(this.scaling).toObject()));if(this.showAccordion){this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);options=$H({sync:true,scaleContent:false,transition:Effect.Transitions.sinoidal});options.merge(this.scaling);this.effects.push(new Effect.Scale(this.showAccordion,0,options.update(this.scaling).toObject()));}
new Effect.Parallel(this.effects,{duration:this.duration,queue:{position:'end',scope:'accordionAnimation'},beforeStart:function(){this.animating=true;}.bind(this),afterFinish:function(){if(this.showAccordion){this.showAccordion.setStyle({display:'none'});}
$(this.currentAccordion).setStyle({height:'100%'});this.showAccordion=this.currentAccordion;this.animating=false;}.bind(this)});}}
if(typeof Effect=='undefined')
throw("controls.js requires including script.aculo.us' effects.js library");var Autocompleter={};Autocompleter.Base=Class.create({baseInitialize:function(element,update,options){element=$(element);this.element=element;this.update=$(update);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(options);else
this.options=options||{};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(element,update){if(!update.style.position||update.style.position=='absolute'){update.style.position='absolute';Position.clone(element,update,{setHeight:false,offsetTop:element.offsetHeight});}
Effect.Appear(update,{duration:0.15});};this.options.onHide=this.options.onHide||function(element,update){new Effect.Fade(update,{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(event){if(this.active)
switch(event.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:this.selectEntry();Event.stop(event);case Event.KEY_ESC:this.hide();this.active=false;Event.stop(event);return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:this.markPrevious();this.render();Event.stop(event);return;case Event.KEY_DOWN:this.markNext();this.render();Event.stop(event);return;}
else
if(event.keyCode==Event.KEY_TAB||event.keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&event.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(event){var element=Event.findElement(event,'LI');if(this.index!=element.autocompleteIndex)
{this.index=element.autocompleteIndex;this.render();}
Event.stop(event);},onClick:function(event){var element=Event.findElement(event,'LI');this.index=element.autocompleteIndex;this.selectEntry();this.hide();},onBlur:function(event){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(index){return this.update.firstChild.childNodes[index];},getCurrentEntry:function(){return this.getEntry(this.index);},selectEntry:function(){this.active=false;this.updateElement(this.getCurrentEntry());},updateElement:function(selectedElement){if(this.options.updateElement){this.options.updateElement(selectedElement);return;}
var value='';if(this.options.select){var nodes=$(selectedElement).select('.'+this.options.select)||[];if(nodes.length>0)value=Element.collectTextNodes(nodes[0],this.options.select);}else
value=Element.collectTextNodesIgnoreClass(selectedElement,'informal');var bounds=this.getTokenBounds();if(bounds[0]!=-1){var newValue=this.element.value.substr(0,bounds[0]);var whitespace=this.element.value.substr(bounds[0]).match(/^\s+/);if(whitespace)
newValue+=whitespace[0];this.element.value=newValue+value+this.element.value.substr(bounds[1]);}else{this.element.value=value;}
this.oldElementValue=this.element.value;this.element.focus();if(this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element,selectedElement);},updateChoices:function(choices){if(!this.changed&&this.hasFocus){this.update.innerHTML=choices;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 entry=this.getEntry(i);entry.autocompleteIndex=i;this.addObservers(entry);}}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(element){Event.observe(element,"mouseover",this.onHover.bindAsEventListener(this));Event.observe(element,"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 bounds=this.getTokenBounds();return this.element.value.substring(bounds[0],bounds[1]).strip();},getTokenBounds:function(){if(null!=this.tokenBounds)return this.tokenBounds;var value=this.element.value;if(value.strip().empty())return[-1,0];var diff=arguments.callee.getFirstDifferencePos(value,this.oldElementValue);var offset=(diff==this.oldElementValue.length?1:0);var prevTokenPos=-1,nextTokenPos=value.length;var tp;for(var index=0,l=this.options.tokens.length;index<l;++index){tp=value.lastIndexOf(this.options.tokens[index],diff+offset-1);if(tp>prevTokenPos)prevTokenPos=tp;tp=value.indexOf(this.options.tokens[index],diff+offset);if(-1!=tp&&tp<nextTokenPos)nextTokenPos=tp;}
return(this.tokenBounds=[prevTokenPos+1,nextTokenPos]);}});Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos=function(newS,oldS){var boundary=Math.min(newS.length,oldS.length);for(var index=0;index<boundary;++index)
if(newS[index]!=oldS[index])
return index;return boundary;};Ajax.Autocompleter=Class.create(Autocompleter.Base,{initialize:function(element,update,url,options){this.baseInitialize(element,update,options);this.options.asynchronous=true;this.options.onComplete=this.onComplete.bind(this);this.options.defaultParams=this.options.parameters||null;this.url=url;},getUpdatedChoices:function(){this.startIndicator();var entry=encodeURIComponent(this.options.paramName)+'='+
encodeURIComponent(this.getToken());this.options.parameters=this.options.callback?this.options.callback(this.element,entry):entry;if(this.options.defaultParams)
this.options.parameters+='&'+this.options.defaultParams;new Ajax.Request(this.url,this.options);},onComplete:function(request){this.updateChoices(request.responseText);}});Autocompleter.Local=Class.create(Autocompleter.Base,{initialize:function(element,update,array,options){this.baseInitialize(element,update,options);this.options.array=array;},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this));},setOptions:function(options){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,ignoreCase:true,fullSearch:false,selector:function(instance){var ret=[];var partial=[];var entry=instance.getToken();var count=0;for(var i=0;i<instance.options.array.length&&ret.length<instance.options.choices;i++){var elem=instance.options.array[i];var foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase()):elem.indexOf(entry);while(foundPos!=-1){if(foundPos==0&&elem.length!=entry.length){ret.push("<li><strong>"+elem.substr(0,entry.length)+"</strong>"+
elem.substr(entry.length)+"</li>");break;}else if(entry.length>=instance.options.partialChars&&instance.options.partialSearch&&foundPos!=-1){if(instance.options.fullSearch||/\s/.test(elem.substr(foundPos-1,1))){partial.push("<li>"+elem.substr(0,foundPos)+"<strong>"+
elem.substr(foundPos,entry.length)+"</strong>"+elem.substr(foundPos+entry.length)+"</li>");break;}}
foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase(),foundPos+1):elem.indexOf(entry,foundPos+1);}}
if(partial.length)
ret=ret.concat(partial.slice(0,instance.options.choices-ret.length));return"<ul>"+ret.join('')+"</ul>";}},options||{});}});Field.scrollFreeActivate=function(field){setTimeout(function(){Field.activate(field);},1);};Ajax.InPlaceEditor=Class.create({initialize:function(element,url,options){this.url=url;this.element=element=$(element);this.prepareOptions();this._controls={};arguments.callee.dealWithDeprecatedOptions(options);Object.extend(this.options,options||{});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(mode,handler,extraClasses){var control=this.options[mode+'Control'];var text=this.options[mode+'Text'];if('button'==control){var btn=document.createElement('input');btn.type='submit';btn.value=text;btn.className='editor_'+mode+'_button';if('cancel'==mode)
btn.onclick=this._boundCancelHandler;this._form.appendChild(btn);this._controls[mode]=btn;}else if('link'==control){var link=document.createElement('a');link.appendChild(document.createTextNode(text));link.onclick='cancel'==mode?this._boundCancelHandler:this._boundSubmitHandler;link.className='editor_'+mode+'_link blank-a';if(extraClasses)
link.className+=' '+extraClasses;this._form.appendChild(link);this._controls[mode]=link;}},createEditField:function(){var text=(this.options.loadTextURL?this.options.loadingText:this.getText());var fld;if(1>=this.options.rows&&!/\r|\n/.test(this.getText())){fld=document.createElement('input');fld.type='text';var size=this.options.size||this.options.cols||0;if(0<size)fld.size=size;}else{fld=document.createElement('textarea');fld.rows=(1>=this.options.rows?this.options.autoRows:this.options.rows);fld.cols=this.options.cols||40;}
fld.name=this.options.paramName;fld.value=text;fld.className='editor_field';if(this.options.submitOnBlur)
fld.onblur=this._boundSubmitHandler;this._controls.editor=fld;if(this.options.loadTextURL)
this.loadExternalText();this._form.appendChild(this._controls.editor);},createForm:function(){var ipe=this;function addText(mode,condition){var text=ipe.options['text'+mode+'Controls'];if(!text||condition===false)return;ipe._form.appendChild(document.createTextNode(text));};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('div'));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.unescapeHTML();},handleAJAXFailure:function(transport){this.triggerCallback('onFailure',transport);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 form=this._form;var value=$F(this._controls.editor);this.prepareSubmission();var params=this.options.callback(form,value)||'';if(Object.isString(params))
params=params.toQueryParams();params.editorId=this.element.id;if(this.options.htmlResponse){var options=Object.extend({evalScripts:true},this.options.ajaxOptions);Object.extend(options,{parameters:params,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Updater({success:this.element},this.url,options);}else{var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:params,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Request(this.url,options);}
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 options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){this._form.removeClassName(this.options.loadingClassName);var text=transport.responseText;if(this.options.stripLoadedTextTags)
text=text.stripTags();this._controls.editor.value=text;this._controls.editor.disabled=false;this.postProcessEditField();}.bind(this),onFailure:this._boundFailureHandler});new Ajax.Request(this.options.loadTextURL,options);},postProcessEditField:function(){var fpc=this.options.fieldPostCreation;if(fpc)
$(this._controls.editor)['focus'==fpc?'focus':'activate']();},prepareOptions:function(){this.options=Object.clone(Ajax.InPlaceEditor.DefaultOptions);Object.extend(this.options,Ajax.InPlaceEditor.DefaultCallbacks);[this._extraDefaultOptions].flatten().compact().each(function(defs){Object.extend(this.options,defs);}.bind(this));},prepareSubmission:function(){this._saving=true;this.removeForm();this.leaveHover();this.showSaving();},registerListeners:function(){this._listeners={};var listener;$H(Ajax.InPlaceEditor.Listeners).each(function(pair){listener=this[pair.value].bind(this);this._listeners[pair.key]=listener;if(!this.options.externalControlOnly)
this.element.observe(pair.key,listener);if(this.options.externalControl)
this.options.externalControl.observe(pair.key,listener);}.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(cbName,arg){if('function'==typeof this.options[cbName]){this.options[cbName](this,arg);}},unregisterListeners:function(){$H(this._listeners).each(function(pair){if(!this.options.externalControlOnly)
this.element.stopObserving(pair.key,pair.value);if(this.options.externalControl)
this.options.externalControl.stopObserving(pair.key,pair.value);}.bind(this));},wrapUp:function(transport){this.leaveEditMode();this._boundComplete(transport,this.element);}});Object.extend(Ajax.InPlaceEditor.prototype,{dispose:Ajax.InPlaceEditor.prototype.destroy});Ajax.InPlaceCollectionEditor=Class.create(Ajax.InPlaceEditor,{initialize:function($super,element,url,options){this._extraDefaultOptions=Ajax.InPlaceCollectionEditor.DefaultOptions;$super(element,url,options);},createEditField:function(){var list=document.createElement('select');list.name=this.options.paramName;list.size=1;this._controls.editor=list;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 options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){var js=transport.responseText.strip();if(!/^\[.*\]$/.test(js))
throw('Server returned an invalid collection representation.');this._collection=eval(js);this.checkForExternalText();}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadCollectionURL,options);},showLoadingText:function(text){this._controls.editor.disabled=true;var tempOption=this._controls.editor.firstChild;if(!tempOption){tempOption=document.createElement('option');tempOption.value='';this._controls.editor.appendChild(tempOption);tempOption.selected=true;}
tempOption.update((text||'').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 options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){this._text=transport.responseText.strip();this.buildOptionList();}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadTextURL,options);},buildOptionList:function(){this._form.removeClassName(this.options.loadingClassName);this._collection=this._collection.map(function(entry){return 2===entry.length?entry:[entry,entry].flatten();});var marker=('value'in this.options)?this.options.value:this._text;var textFound=this._collection.any(function(entry){return entry[0]==marker;}.bind(this));this._controls.editor.update('');var option;this._collection.each(function(entry,index){option=document.createElement('option');option.value=entry[0];option.selected=textFound?entry[0]==marker:0==index;option.appendChild(document.createTextNode(entry[1]));this._controls.editor.appendChild(option);}.bind(this));this._controls.editor.disabled=false;Field.scrollFreeActivate(this._controls.editor);}});Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions=function(options){if(!options)return;function fallback(name,expr){if(name in options||expr===undefined)return;options[name]=expr;};fallback('cancelControl',(options.cancelLink?'link':(options.cancelButton?'button':options.cancelLink==options.cancelButton==false?false:undefined)));fallback('okControl',(options.okLink?'link':(options.okButton?'button':options.okLink==options.okButton==false?false:undefined)));fallback('highlightColor',options.highlightcolor);fallback('highlightEndColor',options.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(form){return Form.serialize(form);},onComplete:function(transport,element){new Effect.Highlight(element,{startcolor:this.options.highlightColor,keepBackgroundImage:true});},onEnterEditMode:null,onEnterHover:function(ipe){ipe.element.style.backgroundColor=ipe.options.highlightColor;if(ipe._effect)
ipe._effect.cancel();},onFailure:function(transport,ipe){alert('Error communication with the server: '+transport.responseText.stripTags());},onFormCustomization:null,onLeaveEditMode:null,onLeaveHover:function(ipe){ipe._effect=new Effect.Highlight(ipe.element,{startcolor:ipe.options.highlightColor,endcolor:ipe.options.highlightEndColor,restorecolor:ipe._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(element,delay,callback){this.delay=delay||0.5;this.element=$(element);this.callback=callback;this.timer=null;this.lastValue=$F(this.element);Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));},delayedListener:function(event){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));}});(function(){var methods={defaultValueActsAsHint:function(element){element=$(element);element._default=element.value;return element.observe('focus',function(){if(element._default!=element.value)return;element.removeClassName('hint').value='';}).observe('blur',function(){if(element.value.strip()!='')return;element.addClassName('hint').value=element._default;}).addClassName('hint');},setValue:function(element,new_value){element.removeClassName('hint').value=new_value;},setHint:function(element,new_hint){element._default=new_hint;element.addClassName('hint').value=element._default;},emptyValue:function(element,new_value){return element.hasClassName('hint')||element.value.empty();}};$w('input textarea').each(function(tag){Element.addMethods(tag,methods)});})();Ajax.InPlaceEditorWithEmptyText=Class.create(Ajax.InPlaceEditor,{initialize:function($super,element,url,options){if(options&&!options.emptyText)options.emptyText="click to edit…";if(options&&!options.emptyClassName)options.emptyClassName="inplaceeditor-empty";options.onLeaveEditMode=this.checkEmpty.bindAsEventListener(this);options.onComplete=this.checkEmpty.bindAsEventListener(this);$super(element,url,options);this.checkEmpty();},checkEmpty:function(){if(this.element.innerHTML.length==0&&this.options.emptyText){this.element.appendChild(new Element("span",{className:this.options.emptyClassName}).update(this.options.emptyText));}else{}},getText:function($super){if(empty_span=this.element.select("."+this.options.emptyClassName).first()){empty_span.remove();}
return $super();}});if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C<A.length;C=C+1){D=(""+A[C]).split(".");E=YAHOO;for(B=(D[0]=="YAHOO")?1:0;B<D.length;B=B+1){E[D[B]]=E[D[B]]||{};E=E[D[B]];}}return E;};YAHOO.log=function(D,A,C){var B=YAHOO.widget.Logger;if(B&&B.log){return B.log(D,A,C);}else{return false;}};YAHOO.register=function(A,E,D){var I=YAHOO.env.modules,B,H,G,F,C;if(!I[A]){I[A]={versions:[],builds:[]};}B=I[A];H=D.version;G=D.build;F=YAHOO.env.listeners;B.name=A;B.version=H;B.build=G;B.versions.push(H);B.builds.push(G);B.mainClass=E;for(C=0;C<F.length;C=C+1){F[C](B);}if(E){E.VERSION=H;E.BUILD=G;}else{YAHOO.log("mainClass is undefined for module "+A,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(A){return YAHOO.env.modules[A]||null;};YAHOO.env.ua=function(){var C={ie:0,opera:0,gecko:0,webkit:0,mobile:null,air:0,caja:0},B=navigator.userAgent,A;if((/KHTML/).test(B)){C.webkit=1;}A=B.match(/AppleWebKit\/([^\s]*)/);if(A&&A[1]){C.webkit=parseFloat(A[1]);if(/ Mobile\//.test(B)){C.mobile="Apple";}else{A=B.match(/NokiaN[^\/]*/);if(A){C.mobile=A[0];}}A=B.match(/AdobeAIR\/([^\s]*)/);if(A){C.air=A[0];}}if(!C.webkit){A=B.match(/Opera[\s\/]([^\s]*)/);if(A&&A[1]){C.opera=parseFloat(A[1]);A=B.match(/Opera Mini[^;]*/);if(A){C.mobile=A[0];}}else{A=B.match(/MSIE\s([^;]*)/);if(A&&A[1]){C.ie=parseFloat(A[1]);}else{A=B.match(/Gecko\/([^\s]*)/);if(A){C.gecko=1;A=B.match(/rv:([^\s\)]*)/);if(A&&A[1]){C.gecko=parseFloat(A[1]);}}}}}A=B.match(/Caja\/([^\s]*)/);if(A&&A[1]){C.caja=parseFloat(A[1]);}return C;}();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var B=YAHOO_config.listener,A=YAHOO.env.listeners,D=true,C;if(B){for(C=0;C<A.length;C=C+1){if(A[C]==B){D=false;break;}}if(D){A.push(B);}}}})();YAHOO.lang=YAHOO.lang||{};(function(){var B=YAHOO.lang,F="[object Array]",C="[object Function]",A=Object.prototype,E=["toString","valueOf"],D={isArray:function(G){return A.toString.apply(G)===F;},isBoolean:function(G){return typeof G==="boolean";},isFunction:function(G){return A.toString.apply(G)===C;},isNull:function(G){return G===null;},isNumber:function(G){return typeof G==="number"&&isFinite(G);},isObject:function(G){return(G&&(typeof G==="object"||B.isFunction(G)))||false;},isString:function(G){return typeof G==="string";},isUndefined:function(G){return typeof G==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(I,H){var G,K,J;for(G=0;G<E.length;G=G+1){K=E[G];J=H[K];if(B.isFunction(J)&&J!=A[K]){I[K]=J;}}}:function(){},extend:function(J,K,I){if(!K||!J){throw new Error("extend failed, please check that "+"all dependencies are included.");}var H=function(){},G;H.prototype=K.prototype;J.prototype=new H();J.prototype.constructor=J;J.superclass=K.prototype;if(K.prototype.constructor==A.constructor){K.prototype.constructor=K;}if(I){for(G in I){if(B.hasOwnProperty(I,G)){J.prototype[G]=I[G];}}B._IEEnumFix(J.prototype,I);}},augmentObject:function(K,J){if(!J||!K){throw new Error("Absorb failed, verify dependencies.");}var G=arguments,I,L,H=G[2];if(H&&H!==true){for(I=2;I<G.length;I=I+1){K[G[I]]=J[G[I]];}}else{for(L in J){if(H||!(L in K)){K[L]=J[L];}}B._IEEnumFix(K,J);}},augmentProto:function(J,I){if(!I||!J){throw new Error("Augment failed, verify dependencies.");}var G=[J.prototype,I.prototype],H;for(H=2;H<arguments.length;H=H+1){G.push(arguments[H]);}B.augmentObject.apply(this,G);},dump:function(G,L){var I,K,N=[],O="{...}",H="f(){...}",M=", ",J=" => ";if(!B.isObject(G)){return G+"";}else{if(G instanceof Date||("nodeType"in G&&"tagName"in G)){return G;}else{if(B.isFunction(G)){return H;}}}L=(B.isNumber(L))?L:3;if(B.isArray(G)){N.push("[");for(I=0,K=G.length;I<K;I=I+1){if(B.isObject(G[I])){N.push((L>0)?B.dump(G[I],L-1):O);}else{N.push(G[I]);}N.push(M);}if(N.length>1){N.pop();}N.push("]");}else{N.push("{");for(I in G){if(B.hasOwnProperty(G,I)){N.push(I+J);if(B.isObject(G[I])){N.push((L>0)?B.dump(G[I],L-1):O);}else{N.push(G[I]);}N.push(M);}}if(N.length>1){N.pop();}N.push("}");}return N.join("");},substitute:function(V,H,O){var L,K,J,R,S,U,Q=[],I,M="dump",P=" ",G="{",T="}",N;for(;;){L=V.lastIndexOf(G);if(L<0){break;}K=V.indexOf(T,L);if(L+1>=K){break;}I=V.substring(L+1,K);R=I;U=null;J=R.indexOf(P);if(J>-1){U=R.substring(J+1);R=R.substring(0,J);}S=H[R];if(O){S=O(R,S,U);}if(B.isObject(S)){if(B.isArray(S)){S=B.dump(S,parseInt(U,10));}else{U=U||"";N=U.indexOf(M);if(N>-1){U=U.substring(4);}if(S.toString===A.toString||N>-1){S=B.dump(S,parseInt(U,10));}else{S=S.toString();}}}else{if(!B.isString(S)&&!B.isNumber(S)){S="~-"+Q.length+"-~";Q[Q.length]=I;}}V=V.substring(0,L)+S+V.substring(K+1);}for(L=Q.length-1;L>=0;L=L-1){V=V.replace(new RegExp("~-"+L+"-~"),"{"+Q[L]+"}","g");}return V;},trim:function(G){try{return G.replace(/^\s+|\s+$/g,"");}catch(H){return G;}},merge:function(){var J={},H=arguments,G=H.length,I;for(I=0;I<G;I=I+1){B.augmentObject(J,H[I],true);}return J;},later:function(N,H,O,J,K){N=N||0;H=H||{};var I=O,M=J,L,G;if(B.isString(O)){I=H[O];}if(!I){throw new TypeError("method undefined");}if(!B.isArray(M)){M=[J];}L=function(){I.apply(H,M);};G=(K)?setInterval(L,N):setTimeout(L,N);return{interval:K,cancel:function(){if(this.interval){clearInterval(G);}else{clearTimeout(G);}}};},isValue:function(G){return(B.isObject(G)||B.isString(G)||B.isNumber(G)||B.isBoolean(G));}};B.hasOwnProperty=(A.hasOwnProperty)?function(G,H){return G&&G.hasOwnProperty(H);}:function(G,H){return!B.isUndefined(G[H])&&G.constructor.prototype[H]!==G[H];};D.augmentObject(B,D,true);YAHOO.util.Lang=B;B.augment=B.augmentProto;YAHOO.augment=B.augmentProto;YAHOO.extend=B.extend;})();YAHOO.register("yahoo",YAHOO,{version:"2.7.0",build:"1796"});YAHOO.util.Get=function(){var M={},L=0,R=0,E=false,N=YAHOO.env.ua,S=YAHOO.lang;var J=function(W,T,X){var U=X||window,Y=U.document,Z=Y.createElement(W);for(var V in T){if(T[V]&&YAHOO.lang.hasOwnProperty(T,V)){Z.setAttribute(V,T[V]);}}return Z;};var I=function(T,U,W){var V=W||"utf-8";return J("link",{"id":"yui__dyn_"+(R++),"type":"text/css","charset":V,"rel":"stylesheet","href":T},U);};var P=function(T,U,W){var V=W||"utf-8";return J("script",{"id":"yui__dyn_"+(R++),"type":"text/javascript","charset":V,"src":T},U);};var A=function(T,U){return{tId:T.tId,win:T.win,data:T.data,nodes:T.nodes,msg:U,purge:function(){D(this.tId);}};};var B=function(T,W){var U=M[W],V=(S.isString(T))?U.win.document.getElementById(T):T;if(!V){Q(W,"target node not found: "+T);}return V;};var Q=function(W,V){var T=M[W];if(T.onFailure){var U=T.scope||T.win;T.onFailure.call(U,A(T,V));}};var C=function(W){var T=M[W];T.finished=true;if(T.aborted){var V="transaction "+W+" was aborted";Q(W,V);return;}if(T.onSuccess){var U=T.scope||T.win;T.onSuccess.call(U,A(T));}};var O=function(V){var T=M[V];if(T.onTimeout){var U=T.scope||T;T.onTimeout.call(U,A(T));}};var G=function(V,Z){var U=M[V];if(U.timer){U.timer.cancel();}if(U.aborted){var X="transaction "+V+" was aborted";Q(V,X);return;}if(Z){U.url.shift();if(U.varName){U.varName.shift();}}else{U.url=(S.isString(U.url))?[U.url]:U.url;if(U.varName){U.varName=(S.isString(U.varName))?[U.varName]:U.varName;}}var c=U.win,b=c.document,a=b.getElementsByTagName("head")[0],W;if(U.url.length===0){if(U.type==="script"&&N.webkit&&N.webkit<420&&!U.finalpass&&!U.varName){var Y=P(null,U.win,U.charset);Y.innerHTML='YAHOO.util.Get._finalize("'+V+'");';U.nodes.push(Y);a.appendChild(Y);}else{C(V);}return;}var T=U.url[0];if(!T){U.url.shift();return G(V);}if(U.timeout){U.timer=S.later(U.timeout,U,O,V);}if(U.type==="script"){W=P(T,c,U.charset);}else{W=I(T,c,U.charset);}F(U.type,W,V,T,c,U.url.length);U.nodes.push(W);if(U.insertBefore){var e=B(U.insertBefore,V);if(e){e.parentNode.insertBefore(W,e);}}else{a.appendChild(W);}if((N.webkit||N.gecko)&&U.type==="css"){G(V,T);}};var K=function(){if(E){return;}E=true;for(var T in M){var U=M[T];if(U.autopurge&&U.finished){D(U.tId);delete M[T];}}E=false;};var D=function(a){var X=M[a];if(X){var Z=X.nodes,T=Z.length,Y=X.win.document,W=Y.getElementsByTagName("head")[0];if(X.insertBefore){var V=B(X.insertBefore,a);if(V){W=V.parentNode;}}for(var U=0;U<T;U=U+1){W.removeChild(Z[U]);}X.nodes=[];}};var H=function(U,T,V){var X="q"+(L++);V=V||{};if(L%YAHOO.util.Get.PURGE_THRESH===0){K();}M[X]=S.merge(V,{tId:X,type:U,url:T,finished:false,aborted:false,nodes:[]});var W=M[X];W.win=W.win||window;W.scope=W.scope||W.win;W.autopurge=("autopurge"in W)?W.autopurge:(U==="script")?true:false;S.later(0,W,G,X);return{tId:X};};var F=function(c,X,W,U,Y,Z,b){var a=b||G;if(N.ie){X.onreadystatechange=function(){var d=this.readyState;if("loaded"===d||"complete"===d){X.onreadystatechange=null;a(W,U);}};}else{if(N.webkit){if(c==="script"){if(N.webkit>=420){X.addEventListener("load",function(){a(W,U);});}else{var T=M[W];if(T.varName){var V=YAHOO.util.Get.POLL_FREQ;T.maxattempts=YAHOO.util.Get.TIMEOUT/V;T.attempts=0;T._cache=T.varName[0].split(".");T.timer=S.later(V,T,function(j){var f=this._cache,e=f.length,d=this.win,g;for(g=0;g<e;g=g+1){d=d[f[g]];if(!d){this.attempts++;if(this.attempts++>this.maxattempts){var h="Over retry limit, giving up";T.timer.cancel();Q(W,h);}else{}return;}}T.timer.cancel();a(W,U);},null,true);}else{S.later(YAHOO.util.Get.POLL_FREQ,null,a,[W,U]);}}}}else{X.onload=function(){a(W,U);};}}};return{POLL_FREQ:10,PURGE_THRESH:20,TIMEOUT:2000,_finalize:function(T){S.later(0,null,C,T);},abort:function(U){var V=(S.isString(U))?U:U.tId;var T=M[V];if(T){T.aborted=true;}},script:function(T,U){return H("script",T,U);},css:function(T,U){return H("css",T,U);}};}();YAHOO.register("get",YAHOO.util.Get,{version:"2.7.0",build:"1796"});if(!window.console||!window.console.log){console={log:function(){return false;}}}
$$('.back-link').each(function(link){link.observe('click',function(){history.back(1);});});function registerStates(){stateManager.register('app',[cookiejar.get('state')||eb.options.passage],changeState,function(values){return values.join('/');}.bind(this),'([^\/]+)');}
function changeState(values){if(!values){return;}
if(values.length==1&&(values[0].startsWith('dict')||values[0].startsWith('tags'))){values=values[0].split("/")}
console.log("Values: >> "+values);switch(values[0]){case'dict':console.log("dict state change");if(values.length==2){dictListAll(values[1]);if(pageTracker){pageTracker._trackEvent('dictionary','list',values[1]);}}else if(values.length==3){var updateDict=new Ajax.Updater('dictionary','/dictionaries/'+values[1]+'/dictionary_entries/'+values[2],{asynchronous:true,evalScripts:true,method:'get',onLoaded:function(request){eb._hideLoading();},onLoading:function(request){eb._showLoading($(panelSwapper.visible).down().id,unescape(values[2]));$('loading_message').setStyle({'fontSize':'2.5em'});},onSuccess:function(){panelSwapper.swapPanel('dictionary');}});if(pageTracker){pageTracker._trackEvent('dictionary','entry',values[1]+'/'+unescape(values[2]));}}
eb.ensureBibleLoaded();break;case'settings':console.log("settings state changed");if(current_user){var updateSett=new Ajax.Updater('settings','/users/'+current_user.id,{asynchronous:true,evalScripts:true,method:'get',onLoaded:function(request){eb._hideLoading();},onLoading:function(request){eb._showLoading(panelSwapper.visible,'Your settings');},onSuccess:function(){panelSwapper.swapPanel('settings');}});}else{eb._stateChange("#Gen 1:1");}
if(pageTracker){pageTracker._trackEvent('settings','view');}
break;case'library':if(values.length<=1){var updateLib=new Ajax.Updater('library','/browser/library/',{asynchronous:true,evalScripts:true,method:'get',onLoaded:function(request){eb._hideLoading();},onLoading:function(request){eb._showLoading(panelSwapper.visible,'eBible library');},onSuccess:function(){panelSwapper.swapPanel('library');}});if(pageTracker){pageTracker._trackEvent('library','list');}}else{var updateBook=new Ajax.Updater('book-detail','/browser/about_title/'+values[1],{asynchronous:true,evalScripts:true,method:'get',onLoaded:function(request){eb._hideLoading();},onLoading:function(request){eb._showLoading(panelSwapper.visible,values[1]);},onSuccess:function(){panelSwapper.swapPanel('book-detail');}});}
if(pageTracker){pageTracker._trackEvent('library','book',values[1]);}
break;case'tags':case'passages':tagsPassagesHandler(values);eb.ensureBibleLoaded();break;default:cookiejar.put("verse_state",values[0]);if(stateManager.initial){cookiejar.put("sources",eb.options.sources);cookiejar.put("state",values[0]);eb.scrollToRefnum(eb.firstColumn().id.gsub('_column','')+'_'+Bible.ordinal2refnum(cookiejar.get('ordinal_to_scroll')));$('verse_state').href=values[0].startsWith('%20')?"#"+values[0].sub('%20','',1):"# "+values[0];return;}
$('verse_state').href="#"+values[0];eb._stateChange(values[0]);}}
function tagsPassagesHandler(params){if(params[4]&&!Math.abs(params[4])>0){$('tag_autocomplete').setValue(params[4]=unescape(params[4]));}
if(params[0]=='passages'&&params[1]=='all'){$('tag_type_select').value='4';}else if(params[0]=='passages'&&params[1]=='mine'){$('tag_type_select').value='3';}else if(params[0]=='tags'&&params[1]=='all'){$('tag_type_select').value='2';}else if(params[0]=='tags'&&params[1]=='mine'){$('tag_type_select').value='1';}
var updateTag=new Ajax.Updater('tag_tab_body','/tagged_passages',{parameters:{type:params[0],show:params[1],order:params[2],display:params[3],tag_autocomplete:params[4],page:params[5]},asynchronous:true,evalScripts:true,method:'get',onComplete:function(request){eb._hideLoading();new Effect.Highlight('tag_passage_status',{startcolor:'#ffff99',endcolor:'#ffffff'});},onLoading:function(request){eb._showLoading('tag-tab',params[1]+" "+params[0]);}});if(pageTracker){pageTracker._trackEvent(params[0],params[1]+' - '+params[2],unescape(params[4]));}
if(sidebar.tabs){sidebar.tabs.manualActivate("tag-tab-title");}
else
{fabtab.manualActivate("tag-tab-title");}
updateTagPassageStatus();}
function dictListAll(short_name){sidebar.tabs.manualActivate('dict-tab-title');var dictName=[];var encName=[];if($('dictionary-type')){$('dictionary-type').select('option.dict-select').each(function(dict){dictName.push(dict.value);});$('dictionary-type').select('option.enc-select').each(function(dict){encName.push(dict.value);});if(dictName.include(short_name)){$('dictionary-type').selectedIndex=(dictName.indexOf(short_name)+2);}
else{$('dictionary-type').selectedIndex=(encName.indexOf(short_name)+dictName.length+3);}}
var dictResult=new Ajax.Updater('dict-results','/dictionaries/'+short_name+'/dictionary_entries',{method:'get',asynchronous:true,evalScripts:true});}
Event.observe(window,'resize',windowResized);function windowResized(){if(eb.IE6){$('dict-results').setStyle({height:($(panelSwapper.visible).getHeight()-$('dict-toolbar').getHeight()-20)+'px'});$('dict-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});if($('dict-search-results')&&$('dict-toolbar')){if(($(panelSwapper.visible).getHeight()-$('dict-toolbar').getHeight()-$$('.dict-result-paging')[0].getHeight()-$$('.dict-tab-results')[0].getHeight())>30){$('dict-search-results').setStyle({height:($(panelSwapper.visible).getHeight()-$('dict-toolbar').getHeight()-$$('.dict-result-paging')[0].getHeight()-$$('.dict-tab-results')[0].getHeight()-30)+'px'});}}
if($('welcome-content')){$('welcome-content').setStyle({height:($(panelSwapper.visible).getHeight()-$('welcome-header').getHeight()-$('welcome-footer').getHeight()-40)+'px'});$('results-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});}
if($('playlist-body')){$('playlist-body').setStyle({height:($(panelSwapper.visible).getHeight()-20-$$('.playlistheader')[0].getHeight()-$$('.playlistfooter')[0].getHeight()-40)+'px'})}
if($('tag_tab_body')&&$('result')){$$('.result-box')[0].setStyle({height:($(panelSwapper.visible).getHeight()-$('tag-tab-header').getHeight()-$('result').getHeight()-$$('.next-prev-page')[0].getHeight()-30)+'px'});if($$('.result-box')[0].getHeight()>0&&$('result').getHeight()>0){$('tag_tab_body').setStyle({height:($$('.result-box')[0].getHeight()+$('result').getHeight()-30)+'px'});}
$('tag-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});$('dict-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});$('playlist-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});$('results-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});}}
if(document.body&&document.body.offsetHeight>315){var headerHeight=90;var tableTitleHeight=35;var tableFooterHeight=73;var table=$("eb-table-box");var leftBox=$("left-box");var headerFooter=28;if(leftBox){leftBox.setStyle({height:(document.body.offsetHeight-115)+"px"});var divs=leftBox.select('div.text-box');divs.each(function(div){div.setStyle({height:leftBox.getHeight()+"px"});});$('dictionary').setStyle({height:(leftBox.getHeight()-5)+"px"});$('settings').setStyle({height:(leftBox.getHeight()+15)+"px"});$('library').setStyle({height:(leftBox.getHeight()+15)+"px"});$('book-detail').setStyle({height:(leftBox.getHeight()-5)+"px"});if($('welcome-text')){$('welcome-text').setStyle({height:(mainHeight+tableFooterHeight-5)+"px"});}
if($('results-tab').down('.result-box')){$('results-tab').down('.result-box').setStyle({height:($('results-tab').getHeight()-85)+'px'});}
if($('welcome-content')){$('welcome-content').setStyle({height:($('results-tab').getHeight()-85)+'px'});}
if($('tag_tab_body')){$('tag_tab_body').setStyle({height:($('tag-tab').getHeight()-$('tag-tab-header').getHeight()-5)+"px"});}
if($('tag-tab').down('#result')){if($('tag_tab_body').getHeight()>0){new_height=$('tag_tab_body').getHeight()-68;$$('.result-box').first().setStyle({height:new_height+"px"});}}
if(eb.IE6&&$('tag_tab_body')&&$('tag-tab')){if($('popular_tag_list')&&$('tag-tab-header')){$('popular_tag_list').style.height=($(panelSwapper.visible).getHeight()-$('tag-tab-header').getHeight()-58)+'px';$('tag_tab_body').style.height=($('popular_tag_list').getHeight()+36)+'px';$('dict-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});$('playlist-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});$('results-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});}
else if($$('.tag_cloud')[0]&&$('tag-tab-header')){$$('.tag_cloud')[0].style.height=($(panelSwapper.visible).getHeight()-$('tag-tab-header').getHeight()-58)+'px';$('tag_tab_body').style.height=($$('.tag_cloud')[0].getHeight()+36)+'px';$('dict-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});$('playlist-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});$('results-tab').setStyle({height:($(panelSwapper.visible).getHeight()-20)+'px'});}
if($('tag_tab_body')&&$('tag-tab')){$('tag-tab').style.height=($(panelSwapper.visible).getHeight()-20)+'px';}}
if($('dict-results')){$('dict-results').setStyle({height:$('dict-tab').getHeight()-95+'px'});}
if($('dict-search-results')&&$('dict-results').getHeight()>0){$('dict-search-results').setStyle({height:$('dict-results').getHeight()-50+'px'});}
if($('playlist-body')){$('playlist-body').setStyle({height:($('playlist-tab').getHeight()-40)+'px'});}}
if(table){var mainHeight=document.body.offsetHeight-headerHeight-tableTitleHeight;table.setStyle({height:(mainHeight)+"px"});if($('eb-playlistbar')&&$('eb-playlistbar').visible()){$('eb-playlistbar').setStyle({bottom:'0px'});$('eb-table-footer').setStyle({bottom:'73px',marginBottom:'-3px'});table.setStyle({height:(mainHeight-17)+"px"});}else{table.setStyle({height:(mainHeight-17)+"px"});$('eb-table-footer').setStyle({bottom:'0px'});}
if($('eb-parallel-control').visible()){$('eb-parallel-control').setStyle({left:($('toolbar_select_bibles_open').cumulativeOffset().first()-$('eb-parallel-control').getWidth()-$('eb-bible').cumulativeOffset().first()+$('toolbar_select_bibles_open').getWidth())+'px'});}}
if(eb){eb._adjustColumns();}
if(eb){eb.alignRows();}
if(eb&eb.playlist.carousel){eb.playlist.carousel.visibleSlides=$$('.playlist-middle-part')[0].getWidth()/$$('li.item')[0].getWidth()}
if($('eb-playlistbar')&&$('eb-playlistbar').visible()){if($('playlist-table').getWidth()>0){var width=($$('.item-tab').length>0)?((parseInt($$('.item-tab').length)*parseInt($('playlist-table').getWidth())))+"px":"inherit";$('slide-table').setStyle({width:width});$$('.item-tab').each(function(ele){ele.setStyle({width:parseInt($('playlist-table').getWidth()-5)+"px",height:parseInt($('playlist-table').getHeight()-20)+"px"});});}
if($('eb-playlist-itemcontent').visible()&&$$('li.highlight')[0]){eb.playlist.contentCarousel.moveTo($($$("li.highlight")[0].down('a').rel));}
if($$('li.item').length>0){eb.playlist.sVisible=parseInt($$('.playlist-middle-part')[0].getWidth()/$$('li.item')[0].getWidth());}}}
if($('eb-playlist-itemcontent').visible()){$('calendar-planner-view').setStyle({top:($('item-titlebar').cumulativeOffset()[1]+$('item-titlebar').getHeight()+1)+"px"});}else if(!$('eb-playlist-itemcontent').visible()||!$('eb-playlist-itemcontent')){$('calendar-planner-view').hide();}
if($('RB_overlay')){$('RB_overlay').setStyle({height:'100em'});}}
function showRedBox(params){if(params=='signin'){var updateLogin=new Ajax.Updater('hidden_content_login','/signin',{asynchronous:true,evalScripts:true,method:'get',onComplete:function(request){RedBox.addHiddenContent('hidden_content_login');},onLoading:function(request){RedBox.loading();}});}
else{var updateSignup=new Ajax.Updater('hidden_content_signup','/signup',{asynchronous:true,evalScripts:true,method:'get',onComplete:function(request){RedBox.addHiddenContent('hidden_content_signup');},onLoading:function(request){RedBox.loading();}});}
if($('eb-action-bar')){$('eb-action-bar').hide();}}
function showSignInForm(){if($('RB_window'))
RedBox.close();RedBox.showInline('signin_form');RedBox.activateRBWindow();$$('.close').each(function(ele){ele.observe('click',function(){RedBox.close();});});$('email').defaultValueActsAsHint();$('password').defaultValueActsAsHint();}
function showLoader(element,message){if(message==undefined){message="loading";}
$(element).insert("<div id ='loading_"+element+"' style='display:none' class='loader'><div id='loading_message'>"+message+"</div></div>");var p=$(element).cumulativeOffset();$('loading_'+element).setStyle({left:p[0]+'px'});$('loading_'+element).setStyle({top:p[1]+'px'});$('loading_'+element).setStyle({width:$(element).getWidth()+'px'});$('loading_'+element).setStyle({height:$(element).getHeight()+'px'});$('loading_'+element).show();return true;}
function hideLoader(){$$('.loader').invoke('remove');}
function isIE6(){if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){var ieversion=new Number(RegExp.$1)
if(parseInt(ieversion)<7){return true;}
else{return false;}}}
function validateEmailIds(ids,sep_char){var emails=ids.split(sep_char);var invalid=true;emails.each(function(email){if(!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.match(email)){invalid=false;}});return invalid;}
if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");var Droppables={drops:[],remove:function(element){this.drops=this.drops.reject(function(d){return d.element==$(element)});},add:function(element){element=$(element);var options=Object.extend({greedy:true,hoverclass:null,tree:false},arguments[1]||{});if(options.containment){options._containers=[];var containment=options.containment;if(Object.isArray(containment)){containment.each(function(c){options._containers.push($(c))});}else{options._containers.push($(containment));}}
if(options.accept)options.accept=[options.accept].flatten();Element.makePositioned(element);options.element=element;this.drops.push(options);},findDeepestChild:function(drops){deepest=drops[0];for(i=1;i<drops.length;++i)
if(Element.isParent(drops[i].element,deepest.element))
deepest=drops[i];return deepest;},isContained:function(element,drop){var containmentNode;if(drop.tree){containmentNode=element.treeNode;}else{containmentNode=element.parentNode;}
return drop._containers.detect(function(c){return containmentNode==c});},isAffected:function(point,element,drop){return((drop.element!=element)&&((!drop._containers)||this.isContained(element,drop))&&((!drop.accept)||(Element.classNames(element).detect(function(v){return drop.accept.include(v)})))&&Position.within(drop.element,point[0],point[1]));},deactivate:function(drop){if(drop.hoverclass)
Element.removeClassName(drop.element,drop.hoverclass);this.last_active=null;},activate:function(drop){if(drop.hoverclass)
Element.addClassName(drop.element,drop.hoverclass);this.last_active=drop;},show:function(point,element){if(!this.drops.length)return;var drop,affected=[];this.drops.each(function(drop){if(Droppables.isAffected(point,element,drop))
affected.push(drop);});if(affected.length>0)
drop=Droppables.findDeepestChild(affected);if(this.last_active&&this.last_active!=drop)this.deactivate(this.last_active);if(drop){Position.within(drop.element,point[0],point[1]);if(drop.onHover)
drop.onHover(element,drop.element,Position.overlap(drop.overlap,drop.element));if(drop!=this.last_active)Droppables.activate(drop);}},fire:function(event,element){if(!this.last_active)return;Position.prepare();if(this.isAffected([Event.pointerX(event),Event.pointerY(event)],element,this.last_active))
if(this.last_active.onDrop){this.last_active.onDrop(element,this.last_active.element,event);return true;}},reset:function(){if(this.last_active)
this.deactivate(this.last_active);}};var Draggables={drags:[],observers:[],register:function(draggable){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(draggable);},unregister:function(draggable){this.drags=this.drags.reject(function(d){return d==draggable});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(draggable){if(draggable.options.delay){this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=draggable;}.bind(this),draggable.options.delay);}else{window.focus();this.activeDraggable=draggable;}},deactivate:function(){this.activeDraggable=null;},updateDrag:function(event){if(!this.activeDraggable)return;var pointer=[Event.pointerX(event),Event.pointerY(event)];if(this._lastPointer&&(this._lastPointer.inspect()==pointer.inspect()))return;this._lastPointer=pointer;this.activeDraggable.updateDrag(event,pointer);},endDrag:function(event){if(this._timeout){clearTimeout(this._timeout);this._timeout=null;}
if(!this.activeDraggable)return;this._lastPointer=null;this.activeDraggable.endDrag(event);this.activeDraggable=null;},keyPress:function(event){if(this.activeDraggable)
this.activeDraggable.keyPress(event);},addObserver:function(observer){this.observers.push(observer);this._cacheObserverCallbacks();},removeObserver:function(element){this.observers=this.observers.reject(function(o){return o.element==element});this._cacheObserverCallbacks();},notify:function(eventName,draggable,event){if(this[eventName+'Count']>0)
this.observers.each(function(o){if(o[eventName])o[eventName](eventName,draggable,event);});if(draggable.options[eventName])draggable.options[eventName](draggable,event);},_cacheObserverCallbacks:function(){['onStart','onEnd','onDrag'].each(function(eventName){Draggables[eventName+'Count']=Draggables.observers.select(function(o){return o[eventName];}).length;});}};var Draggable=Class.create({initialize:function(element){var defaults={handle:false,reverteffect:function(element,top_offset,left_offset){var dur=Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:dur,queue:{scope:'_draggable',position:'end'}});},endeffect:function(element){var toOpacity=Object.isNumber(element._opacity)?element._opacity:1.0;new Effect.Opacity(element,{duration:0.2,from:0.7,to:toOpacity,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[element]=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(defaults,{starteffect:function(element){element._opacity=Element.getOpacity(element);Draggable._dragging[element]=true;new Effect.Opacity(element,{duration:0.2,from:element._opacity,to:0.7});}});var options=Object.extend(defaults,arguments[1]||{});this.element=$(element);if(options.handle&&Object.isString(options.handle))
this.handle=this.element.down('.'+options.handle,0);if(!this.handle)this.handle=$(options.handle);if(!this.handle)this.handle=this.element;if(options.scroll&&!options.scroll.scrollTo&&!options.scroll.outerHTML){options.scroll=$(options.scroll);this._isScrollChild=Element.childOf(this.element,options.scroll);}
Element.makePositioned(this.element);this.options=options;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(event){if(!Object.isUndefined(Draggable._dragging[this.element])&&Draggable._dragging[this.element])return;if(Event.isLeftClick(event)){var src=Event.element(event);if((tag_name=src.tagName.toUpperCase())&&(tag_name=='INPUT'||tag_name=='SELECT'||tag_name=='OPTION'||tag_name=='BUTTON'||tag_name=='TEXTAREA'))return;var pointer=[Event.pointerX(event),Event.pointerY(event)];var pos=Position.cumulativeOffset(this.element);if(this.element.hasClassName("verseNum")){pos=this.element.viewportOffset($('bible-table-columns'));}
this.offset=[0,1].map(function(i){return(pointer[i]-pos[i])});Draggables.activate(this);Event.stop(event);}},startDrag:function(event){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 where=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=where.left;this.originalScrollTop=where.top;}else{this.originalScrollLeft=this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop;}}
Draggables.notify('onStart',this,event);if(this.options.starteffect)this.options.starteffect(this.element);},updateDrag:function(event,pointer){if(!this.dragging)this.startDrag(event);if(!this.options.quiet){Position.prepare();Droppables.show(pointer,this.element);}
Draggables.notify('onDrag',this,event);this.draw(pointer);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 speed=[0,0];if(pointer[0]<(p[0]+this.options.scrollSensitivity))speed[0]=pointer[0]-(p[0]+this.options.scrollSensitivity);if(pointer[1]<(p[1]+this.options.scrollSensitivity))speed[1]=pointer[1]-(p[1]+this.options.scrollSensitivity);if(pointer[0]>(p[2]-this.options.scrollSensitivity))speed[0]=pointer[0]-(p[2]-this.options.scrollSensitivity);if(pointer[1]>(p[3]-this.options.scrollSensitivity))speed[1]=pointer[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(speed);}
if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);},finishDrag:function(event,success){this.dragging=false;if(this.options.quiet){Position.prepare();var pointer=[Event.pointerX(event),Event.pointerY(event)];Droppables.show(pointer,this.element);}
if(this.options.ghosting){if(!this._originallyAbsolute)
Position.relativize(this.element);delete this._originallyAbsolute;}
var dropped=false;if(success){dropped=Droppables.fire(event,this.element);if(!dropped)dropped=false;}
if(this.options.onDropped){if($('playlist-items')==this.element.parentNode||$('bible-table-columns')==this.element.parentNode){this.options.onDropped(this.element);if(this._clone){this._clone.style.zIndex=0;this._clone.style.top='0px';}}else if($('side-holder')==this.element.parentNode){this._clone.remove();}else{this._clone.remove();}}
Draggables.notify('onEnd',this,event);var revert=this.options.revert;if(revert&&Object.isFunction(revert))revert=revert(this.element);var d=this.currentDelta();if(revert&&this.options.reverteffect){if(dropped==0||revert!='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(event){if(event.keyCode!=Event.KEY_ESC)return;this.finishDrag(event,false);Event.stop(event);},endDrag:function(event){if(!this.dragging)return;this.stopScrolling(event);this.finishDrag(event,true);Event.stop(event);},draw:function(point){var pos=Position.cumulativeOffset(this.element);if(this.options.ghosting){var r=Position.realOffset(this.element);}
var d=this.currentDelta();pos[0]-=d[0];pos[1]-=d[1];if(this.options.scroll&&(this.options.scroll!=window&&this._isScrollChild)){pos[0]-=this.options.scroll.scrollLeft-this.originalScrollLeft;pos[1]-=this.options.scroll.scrollTop-this.originalScrollTop;}
var p=[0,1].map(function(i){return(point[i]-pos[i]-this.offset[i])}.bind(this));if(this.element.hasClassName("verseNum")){var cs=this.element.cumulativeScrollOffset();p=[0,1].map(function(i){return(point[i]-pos[i]-this.offset[i]+cs[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 style=this.element.style;if((!this.options.constraint)||(this.options.constraint=='horizontal'))
style.left=p[0]+"px";if((!this.options.constraint)||(this.options.constraint=='vertical'))
style.top=p[1]+"px";if(style.visibility=="hidden")style.visibility="";},stopScrolling:function(event){if(this.scrollInterval){clearInterval(this.scrollInterval);this.scrollInterval=null;Draggables._lastScrollPointer=null;}},startScrolling:function(speed){if(!(speed[0]||speed[1]))return;this.scrollSpeed=[speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];this.lastScrolled=new Date();this.scrollInterval=setInterval(this.scroll.bind(this),10);},scroll:function(){var current=new Date();var delta=current-this.lastScrolled;this.lastScrolled=current;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){if(this.scrollSpeed[0]||this.scrollSpeed[1]){var d=delta/1000;this.options.scroll.scrollTo(left+d*this.scrollSpeed[0],top+d*this.scrollSpeed[1]);}}}else{this.options.scroll.scrollLeft+=this.scrollSpeed[0]*delta/1000;this.options.scroll.scrollTop+=this.scrollSpeed[1]*delta/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]*delta/1000;Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*delta/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(element,observer){this.element=$(element);this.observer=observer;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(element){while(element.tagName.toUpperCase()!="BODY"){if(element.id&&Sortable.sortables[element.id]){return element;}
element=element.parentNode;}},options:function(element){element=Sortable._findRootElement($(element));if(!element)return;return Sortable.sortables[element.id];},destroy:function(element){element=$(element);var s=Sortable.sortables[element.id];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(element){element=$(element);var options=Object.extend({element:element,tag:'li',dropOnEmpty:false,tree:false,treeTag:'ul',overlap:'vertical',constraint:'vertical',containment:element,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(element);var options_for_draggable={revert:true,quiet:options.quiet,scroll:options.scroll,scrollSpeed:options.scrollSpeed,scrollSensitivity:options.scrollSensitivity,delay:options.delay,ghosting:options.ghosting,constraint:options.constraint,handle:options.handle};if(options.starteffect)
options_for_draggable.starteffect=options.starteffect;if(options.reverteffect)
options_for_draggable.reverteffect=options.reverteffect;else
if(options.ghosting)options_for_draggable.reverteffect=function(element){element.style.top=0;element.style.left=0;};if(options.endeffect)
options_for_draggable.endeffect=options.endeffect;if(options.zindex)
options_for_draggable.zindex=options.zindex;var options_for_droppable={overlap:options.overlap,containment:options.containment,tree:options.tree,hoverclass:options.hoverclass,onHover:Sortable.onHover};var options_for_tree={onHover:Sortable.onEmptyHover,overlap:options.overlap,containment:options.containment,hoverclass:options.hoverclass};Element.cleanWhitespace(element);options.draggables=[];options.droppables=[];if(options.dropOnEmpty||options.tree){Droppables.add(element,options_for_tree);options.droppables.push(element);}
(options.elements||this.findElements(element,options)||[]).each(function(e,i){var handle=options.handles?$(options.handles[i]):(options.handle?$(e).select('.'+options.handle)[0]:e);options.draggables.push(new Draggable(e,Object.extend(options_for_draggable,{handle:handle})));Droppables.add(e,options_for_droppable);if(options.tree)e.treeNode=element;options.droppables.push(e);});if(options.tree){(Sortable.findTreeElements(element,options)||[]).each(function(e){Droppables.add(e,options_for_tree);e.treeNode=element;options.droppables.push(e);});}
this.sortables[element.id]=options;Draggables.addObserver(new SortableObserver(element,options.onUpdate));},findElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.tag);},findTreeElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.treeTag);},onHover:function(element,dropon,overlap){Position.relativize(element);if(Element.isParent(dropon,element))return;if(overlap>.33&&overlap<.66&&Sortable.options(dropon).tree){return;}else if(overlap>0.5){Sortable.mark(dropon,'before');if(dropon.previousSibling!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,dropon);Sortable.options(dropon.parentNode).onChange(element);}}else{Sortable.mark(dropon,'after');var nextElement=dropon.nextSibling||null;if(nextElement!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,nextElement);Sortable.options(dropon.parentNode).onChange(element);}}
if(dropon==$$('li.droppable').first()){$$('li.droppable').first().remove();}},onEmptyHover:function(element,dropon,overlap){var oldParentNode=element.parentNode;var droponOptions=Sortable.options(dropon);if(!Element.isParent(dropon,element)){var index;var children=Sortable.findElements(dropon,{tag:droponOptions.tag,only:droponOptions.only});var child=null;if(children){var offset=Element.offsetSize(dropon,droponOptions.overlap)*(1.0-overlap);for(index=0;index<children.length;index+=1){if(offset-Element.offsetSize(children[index],droponOptions.overlap)>=0){offset-=Element.offsetSize(children[index],droponOptions.overlap);}else if(offset-(Element.offsetSize(children[index],droponOptions.overlap)/2)>=0){child=index+1<children.length?children[index+1]:null;break;}else{child=children[index];break;}}}
dropon.insertBefore(element,child);droponOptions.onChange(element);if(dropon==$$('li.droppable').first()){$$('li.droppable').first().remove();}}},unmark:function(){if(Sortable._marker)Sortable._marker.hide();},mark:function(dropon,position){var sortable=Sortable.options(dropon.parentNode);if(sortable&&!sortable.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 offsets=Position.cumulativeOffset(dropon);Sortable._marker.setStyle({border:'1px solid red',left:offsets[0]+'px',top:offsets[1]+'px'});if(position=='after')
if(sortable.overlap=='horizontal')
Sortable._marker.setStyle({left:(offsets[0]+dropon.clientWidth)+'px'});else
Sortable._marker.setStyle({top:(offsets[1]+dropon.clientHeight)+'px'});Sortable._marker.show();},_tree:function(element,options,parent){var children=Sortable.findElements(element,options)||[];for(var i=0;i<children.length;++i){var match=children[i].id.match(options.format);if(!match)continue;var child={id:encodeURIComponent(match?match[1]:null),element:element,parent:parent,children:[],position:parent.children.length,container:$(children[i]).down(options.treeTag)};if(child.container)
this._tree(child.container,options,child);parent.children.push(child);}
return parent;},tree:function(element){element=$(element);var sortableOptions=this.options(element);var options=Object.extend({tag:sortableOptions.tag,treeTag:sortableOptions.treeTag,only:sortableOptions.only,name:element.id,format:sortableOptions.format},arguments[1]||{});var root={id:null,parent:null,children:[],container:element,position:0};return Sortable._tree(element,options,root);},_constructIndex:function(node){var index='';do{if(node.id)index='['+node.position+']'+index;}while((node=node.parent)!=null);return index;},sequence:function(element){element=$(element);var options=Object.extend(this.options(element),arguments[1]||{});return $(this.findElements(element,options)||[]).map(function(item){return item.id.match(options.format)?item.id.match(options.format)[1]:'';});},setSequence:function(element,new_sequence){element=$(element);var options=Object.extend(this.options(element),arguments[2]||{});var nodeMap={};this.findElements(element,options).each(function(n){if(n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]]=[n,n.parentNode];n.parentNode.removeChild(n);});new_sequence.each(function(ident){var n=nodeMap[ident];if(n){n[1].appendChild(n[0]);delete nodeMap[ident];}});},serialize:function(element){element=$(element);var options=Object.extend(Sortable.options(element),arguments[1]||{});var name=encodeURIComponent((arguments[1]&&arguments[1].name)?arguments[1].name:element.id);if(options.tree){return Sortable.tree(element,arguments[1]).children.map(function(item){return[name+Sortable._constructIndex(item)+"[id]="+
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));}).flatten().join('&');}else{return Sortable.sequence(element,arguments[1]).map(function(item){return name+"[]="+encodeURIComponent(item);}).join('&');}}};Element.isParent=function(child,element){if(!child.parentNode||child==element)return false;if(child.parentNode==element)return true;return Element.isParent(child.parentNode,element);};Element.findChildren=function(element,only,recursive,tagName){if(!element.hasChildNodes())return null;tagName=tagName.toUpperCase();if(only)only=[only].flatten();var elements=[];$A(element.childNodes).each(function(e){if(e.tagName&&e.tagName.toUpperCase()==tagName&&(!only||(Element.classNames(e).detect(function(v){return only.include(v)}))))
elements.push(e);if(recursive){var grandchildren=Element.findChildren(e,only,recursive,tagName);if(grandchildren)elements.push(grandchildren);}});return(elements.length>0?elements.flatten():[]);};Element.offsetSize=function(element,type){return element['offset'+((type=='vertical'||type=='height')?'Height':'Width')];};var eBibleDrag=Class.create({drag_initialize:function(element){this.element=$(element);this.active=false;this.scrolling=false;this.element.setStyle({cursor:"move"});this.gestureTrack=false;this.gestureStartTime=0;this.gestureEndTime=0;this.gestureMouseStartY=0;this.gestureMouseEndY=0;this.gestureThreshold=30;this.gestureColStartY=0;this.eventMouseDown=this.startScroll.bindAsEventListener(this);this.eventMouseUp=this.endScroll.bindAsEventListener(this);this.eventMouseMove=this.scroll.bindAsEventListener(this);Event.observe(this.element,'mousedown',this.eventMouseDown);},destroy:function(){Event.stopObserving(this.element,'mousedown',this.eventMouseDown);Event.stopObserving(document,'mouseup',this.eventMouseUp);Event.stopObserving(document,'mousemove',this.eventMouseMove);},startScroll:function(event){this.startX=Event.pointerX(event);this.startY=Event.pointerY(event);scrollEvent=Event.findElement(event,"div.grid-cell");if(!Event.findElement(event,"div.grid-cell")&&Event.isLeftClick(event)&&this._enableScroll(event)){this.element.setStyle({cursor:"move"});Event.observe(document,'mouseup',this.eventMouseUp);Event.observe(document,'mousemove',this.eventMouseMove);this.date=new Date();this.gestureStartTime=this.date.getTime();this.gestureMouseStartY=Event.pointerY(event);this.gestureColStartY=this.element.scrollTop
this.active=true;Event.stop(event);}
else{}},endScroll:function(event){this.element.setStyle({cursor:"move"});this.active=false;Event.stopObserving(document,'mouseup',this.eventMouseUp);Event.stopObserving(document,'mousemove',this.eventMouseMove);Event.stop(event);if(this.gestureTrack==false){return false;}
window.setTimeout("gestureTrack = false;",500);this.gestureMouseEndY=Event.pointerY(event);this.date=new Date();this.gestureEndTime=this.date.getTime();this.diffY=this.gestureMouseEndY-this.gestureMouseStartY;this.diffTime=this.gestureEndTime-this.gestureStartTime;this.multiplier=1;if(Math.abs(this.diffY)>this.gestureThreshold){this.multiplier=Math.abs(this.diffY/(this.diffTime*1.8));}
if(this.multiplier>1){this.multiplier=1+(((1-this.multiplier)*3)*-1);}
if(this.multiplier<0.45){this.multiplier=0;}
var changeY=this.element.scrollTop-this.diffY*this.multiplier;new Effect.Scroll(this.element,{x:0,y:changeY,duration:0.7,transition:Effect.Transitions.EaseTo});},scroll:function(event){this.gestureTrack=true;if(this.active){this.element.scrollTop+=(this.startY-Event.pointerY(event));this.startX=Event.pointerX(event);this.startY=Event.pointerY(event);}
if(eb.topLeftCell()){eb.cell_in_view=eb.topLeftCell();}},_enableScroll:function(event){return true;}});var ProtoHistoryManager=Class.create({options:{observeDelay:100,stateSeparator:';',iframeSrc:'/blank.html',onStart:Prototype.emptyFunction,onRegister:Prototype.emptyFunction,onUnregister:Prototype.emptyFunction,onStart:Prototype.emptyFunction,onUpdate:Prototype.emptyFunction,onStateChange:Prototype.emptyFunction,onObserverChange:Prototype.emptyFunction},dataOptions:{skipDefaultMatch:true,defaults:[],regexpParams:'g'},initialize:function(options){if(this.modules)return this;this.setOptions(options);this.modules=$H({});this.count=history.length;this.states=[];this.states[this.count]=this.getHash();this.state=null;this.initial=true;return this;},setOptions:function(options){Object.extend(this,this.options);Object.extend(this,options);return this;},start:function(){new PeriodicalExecuter(this.observe.bind(this),this.options.observeDelay/1000);this.started=true;this.onStart.apply(this,[this.state]);return this;},register:function(key,defaults,onMatch,onGenerate,regexp,options){if(!this.modules)this.initialize();var data=Object.extend(this.dataOptions,options||{});Object.extend(data,{defaults:defaults,onMatch:onMatch,onGenerate:onGenerate,regexp:regexp});data.regexp=data.regexp||key+'-([\\w_-]*)';if(typeof data.regexp=='string')data.regexp=new RegExp(data.regexp,data.regexpParams);data.onGenerate=data.onGenerate||function(values){return key+'-'+values[0];};data.values=data.defaults.clone();this.modules.set(key,data);this.onUnregister.apply(this,[key,data]);return{setValues:function(values){return this.setValues(key,values);}.bind(this),setValue:function(index,value){return this.setValue(key,index,value);}.bind(this),generate:function(values){return this.generate(key,values);}.bind(this),unregister:function(){return this.unregister(key);}.bind(this)};},unregister:function(key){this.onRegister.apply(this,[key]);this.modules.unset(key);},setValues:function(key,values){var data=this.modules.get(key);if(!data||data.values.isSimilar(values))return this;data.values=values;this.update();return this;},setValue:function(key,index,value){var data=this.modules.get(key);if(!data||data.values[index]==value)return this;data.values[index]=value;this.update();return this;},generate:function(key,values){var data=this.modules.get(key);var current=data.values.clone();data.values=values;var state=this.generateState();data.values=current;return'#'+state;},observe:function(){if(this.timeout)return;var state=this.getState();if(this.state==state)return;if((Prototype.Browser.IE||Prototype.Browser.WebKit)&&(this.state!==null))this.setState(state,true);else this.state=state;this.modules.each(function(data){var bits=state.match(data.value.regexp);if(bits){bits.complement(data.value.defaults);if(!bits.isSimilar(data.value.defaults))data.value.values=bits;}else data.value.values=data.value.defaults.clone();data.value.onMatch(data.value.values,data.value.defaults);});this.onStateChange.apply(this,[state]);this.onObserverChange.apply(this,[state]);},generateState:function(){var state=[];this.modules.each(function(data,key){if(data.value.skipDefaultMatch&&data.value.values.isSimilar(data.value.defaults))return;state.push(data.value.onGenerate(data.value.values));});return state.join(this.options.stateSeparator);},update:function(){if(!this.started)return this;var state=this.generateState();if((!this.state&&!state)||(this.state==state))return this;this.setState(state);this.onStateChange.apply(this,[state]);this.onUpdate.apply(this,[state]);return this;},observeTimeout:function(){if(this.timeout)this.timeout=clearInterval(this.timeout);else this.timeout=this.observeTimeout.bind(this).delay(200/1000);},getHash:function(){var href=top.location.href;var pos=href.indexOf('#')+1;return(pos)?href.substr(pos):'';},getState:function(){var state=this.getHash();if(this.iframe){var doc=this.iframe.contentWindow.document;if(doc&&doc.body.id=='state'){var istate=doc.body.innerText;if(this.state==state)return istate;this.istateOld=true;}else return this.istate;}
return state;},setState:function(state,fix){state=state!=undefined?state:'';top.location.hash=state||'#';console.log("in setState: ",state);if(Prototype.Browser.IE&&(!fix||this.istateOld)){if(!this.iframe){this.iframe=new Element('iframe',{'src':this.options.iframeSrc,'styles':'display: none;','width':'1','height':'1'});document.body.appendChild(this.iframe);this.istate=this.state;}
try{var doc=this.iframe.contentWindow.document;doc.open();doc.write('<html><body id="state">'+state+'</body></html>');doc.close();this.istateOld=false;}catch(e){};}
this.state=state;},extend:Object.extend});Object.extend(Array.prototype,{isSimilar:function(array){return(this.toString()==array.toString());},complement:function(array){for(var i=0,j=this.length;i<j;i++)this[i]=(this[i]!=undefined)?this[i]:(array[i]||null);return this;}});var Fabtabs=Class.create();Fabtabs.prototype={initialize:function(element){this.element=$(element);var options=Object.extend({},arguments[1]||{});this.menu=$A(this.element.getElementsByTagName('a'));this.show(this.getInitialTab());this.menu.each(this.setupTab.bind(this));this.activeTab=this.getInitialTab();},setupTab:function(elm){Event.observe(elm,'click',this.clickActivate.bindAsEventListener(this),false)},clickActivate:function(ev){var elm=Event.findElement(ev,"a");Event.stop(ev);this._activate(elm);windowResized();},manualActivate:function(elm){this._activate($(elm).down('a'));},hide:function(elm){$(elm).up().removeClassName('active');$(this.tabID(elm)).hide();},show:function(elm){$(elm).up().addClassName('active');$(this.tabID(elm)).show();this.menu.without(elm).each(this.hide.bind(this));},tabID:function(elm){return elm.href.match(/#(\w.+)/)[1];},getInitialTab:function(){if(document.location.href.match(/#(\w.+)/)){var loc=RegExp.$1;var elm=this.menu.find(function(value){return value.href.match(/#(\w.+)/)[1]==loc;});return elm||this.menu.first();}else{return this.menu.first();}},_activate:function(elm){this.activeTab=elm;this.show(elm);this.menu.without(elm).each(this.hide.bind(this));}}
var Bible={ordinal2refnum:function(ordinal){var currentbooknum=1;var i=0;var totalbooktotal=0;var prevtotalbooktotal=0;var chaptertotal=0;if(ordinal>31102||ordinal<1){return null;}
if(ordinal>Bible.VERSES_IN_BOOK[0]){while(ordinal>totalbooktotal){prevtotalbooktotal=totalbooktotal;totalbooktotal+=Bible.VERSES_IN_BOOK[i];i+=1;}
currentbooknum=i;chaptertotal=ordinal-prevtotalbooktotal;}else{chaptertotal=ordinal;}
var currentchapternum=1;var j=0;var totalchaptertotal=0;var prevtotalchaptertotal=0;var currentverse=0;if(chaptertotal>Bible.VERSES_IN_CHAPTER[currentbooknum-1][0]){while(chaptertotal>totalchaptertotal){prevtotalchaptertotal=totalchaptertotal;totalchaptertotal+=Bible.VERSES_IN_CHAPTER[currentbooknum-1][j];j+=1;}
currentchapternum=j;currentverse=chaptertotal-prevtotalchaptertotal;}else{currentverse=chaptertotal;}
return Bible.zerofill(currentbooknum,2)+Bible.zerofill(currentchapternum,3)+Bible.zerofill(currentverse,3)},refnum2ordinal:function(refnum){var booknum=parseInt(refnum.slice(0,2),10);var chapternum=parseInt(refnum.slice(2,5),10);var versenum=parseInt(refnum.slice(5,8),10);var i=1;var booktotal=0;var chaptertotal=0;var ordinal=0;if(!(booknum>=1&&booknum<=66&&chapternum>=1&&chapternum<=Bible.CHAPTERS_IN_BOOK[booknum-1]&&versenum>=1&&versenum<=Bible.VERSES_IN_CHAPTER[booknum-1][chapternum-1]))
return null;if(booknum>1){for(i=0;i<booknum-1;i++){booktotal+=Bible.VERSES_IN_BOOK[i];}}
if(chapternum>1){for(i=0;i<chapternum-1;i++){chaptertotal+=Bible.VERSES_IN_CHAPTER[booknum-1][i];}}
return booktotal+chaptertotal+versenum;},refnum2ref:function(refnum){var booknum=parseInt(refnum.slice(0,2),10);var chapternum=parseInt(refnum.slice(2,5),10);var versenum=parseInt(refnum.slice(5,8),10);if(!(booknum>=1&&booknum<=66&&chapternum>=1&&chapternum<=Bible.CHAPTERS_IN_BOOK[booknum-1]&&versenum>=1&&versenum<=Bible.VERSES_IN_CHAPTER[booknum-1][chapternum-1]))
return null;return Bible.LONGNAMES[booknum-1]+" "+chapternum+":"+versenum;},refnum2shortref:function(refnum){if(refnum){var booknum=parseInt(refnum.slice(0,2),10);var chapternum=parseInt(refnum.slice(2,5),10);var versenum=parseInt(refnum.slice(5,8),10);if(!(booknum>=1&&booknum<=66&&chapternum>=1&&chapternum<=Bible.CHAPTERS_IN_BOOK[booknum-1]&&versenum>=1&&versenum<=Bible.VERSES_IN_CHAPTER[booknum-1][chapternum-1]))
return null;return Bible.SHORTNAMES[booknum-1]+" "+chapternum+":"+versenum;}else{return"";}},zerofill:function(num,digits){var sNum=num+"";while(sNum.length<digits)
sNum="0"+sNum;return sNum;},mergeContinuousOrdinals:function(refnums){refnums.sort();mergeOrdinals=refnums.collect(function(refnum){return[Bible.refnum2ordinal(refnum)];});for(i=0;i<mergeOrdinals.length-1;i++){for(j=i+1;j<mergeOrdinals.length;j++){if((mergeOrdinals[i].last()-mergeOrdinals[j][0]).abs()==1){mergeOrdinals[i].push(mergeOrdinals[j][0]);mergeOrdinals=mergeOrdinals.without(mergeOrdinals[j]);j--;}}}
return mergeOrdinals;},mergeContinuousVerses:function(refnums){var ordinals=Bible.mergeContinuousOrdinals(refnums);var refnum=ordinals.collect(function(ord){return ord.collect(function(ord){return Bible.ordinal2refnum(ord);});});var mergePassage=refnum.collect(function(refn){return refn.collect(function(r){return Bible.refnum2ref(r);});});for(i=0;i<mergePassage.length;i++){if(mergePassage[i].length>1){var t1=new RegExp(/\d?\s*\w+\s(\d+):\d/).exec(mergePassage[i][0])[1];var t2=new RegExp(/\d?\s*\w+\s(\d+):\d/).exec(mergePassage[i].last())[1];if(t1!=t2){var nextpassage=new RegExp(/\d?\s*\w+\s(\d+\:\d)/).exec(mergePassage[i].last());var temp=mergePassage[i][0]+'-'+nextpassage[1];}
else
var temp=mergePassage[i][0].split(':')[0]+':'+mergePassage[i][0].split(':')[1]+'-'+mergePassage[i].last().split(':')[1];mergePassage[i].clear();mergePassage[i].push(temp);}}
var mergePassageRef=[];mergePassage.each(function(ele){mergePassageRef.push(ele[0]);});return mergePassageRef;},validVerse:function(verse){var flag=true;var verse_ref=new RegExp(/(\w+[\s*\w+]*[a-zA-Z])[\s*\.]?(\d+)\s*[\:\.\,]\s*(\d+)/).exec(verse);var chapter,versenum,book_name='';if(verse_ref){var book=verse_ref[1].match(/(\d+)\s*(\D+)/)||verse_ref[1].match(/(\D+)/);var units=[];for(i=1;i<book.length;i++){units.push(book[i].capitalize());}
book_name=units.join(" ");chapter=verse_ref[2];versenum=verse_ref[3];if(Bible.LONGNAMES.include(book_name)||Bible.SHORTNAMES.include(book_name)){var book_index=Bible.LONGNAMES.include(book_name)?Bible.LONGNAMES.indexOf(book_name):Bible.SHORTNAMES.indexOf(book_name);if(chapter>Bible.CHAPTERS_IN_BOOK[book_index])
flag=false;else{if(versenum>Bible.VERSES_IN_CHAPTER[book_index][chapter-1])
flag=false;else
flag=true;}}
else
flag=false;}
else
flag=false;return flag;},LONGNAMES:['Genesis','Exodus','Leviticus','Numbers','Deuteronomy','Joshua','Judges','Ruth','1 Samuel','2 Samuel','1 Kings','2 Kings','1 Chronicles','2 Chronicles','Ezra','Nehemiah','Esther','Job','Psalms','Proverbs','Ecclesiastes','Song of Songs','Isaiah','Jeremiah','Lamentations','Ezekiel','Daniel','Hosea','Joel','Amos','Obadiah','Jonah','Micah','Nahum','Habakkuk','Zephaniah','Haggai','Zechariah','Malachi','Matthew','Mark','Luke','John','Acts','Romans','1 Corinthians','2 Corinthians','Galatians','Ephesians','Philippians','Colossians','1 Thessalonians','2 Thessalonians','1 Timothy','2 Timothy','Titus','Philemon','Hebrews','James','1 Peter','2 Peter','1 John','2 John','3 John','Jude','Revelation'],SHORTNAMES:['Gn','Ex','Lv','Nm','Dt','Jo','Jdg','Ru','1Sa','2Sa','1Ki','2Ki','1Ch','2Ch','Ezr','Neh','Est','Job','Ps','Pr','Ecc','SoS','Is','Jer','Lam','Ez','Dn','Hos','Jl','Am','Ob','Jon','Mi','Na','Hb','Zep','Hg','Zec','Mal','Mt','Mk','Lk','Jn','Ac','Rom','1Co','2Co','Ga','Eph','Phi','Col','1Th','2Th','1Ti','2Ti','Tit','Phm','Heb','Jam','1Pe','2Pe','1Jn','2Jn','3Jn','Jud','Rv'],CHAPTERS_IN_BOOK:[50,40,27,36,34,24,21,4,31,24,22,25,29,36,10,13,10,42,150,31,12,8,66,52,5,48,12,14,3,9,1,4,7,3,3,3,2,14,4,28,16,24,21,28,16,16,13,6,6,4,4,5,3,6,4,3,1,13,5,5,3,5,1,1,1,22],VERSES_IN_BOOK:[1533,1213,859,1288,959,658,618,85,810,695,816,719,942,822,280,406,167,1070,2461,915,222,117,1292,1364,154,1273,357,197,73,146,21,48,105,47,56,53,38,211,55,1071,678,1151,879,1007,433,437,257,149,155,104,95,89,47,113,83,46,25,303,108,105,61,105,13,14,25,404],FIRST_ORDINAL_OF_BOOK:[1,1534,2747,3606,4894,5853,6511,7129,7214,8024,8719,9535,10254,11196,12018,12298,12704,12871,13941,16402,17317,17539,17656,18948,20312,20466,21739,22096,22293,22366,22512,22533,22581,22686,22733,22789,22842,22880,23091,23146,24217,24895,26046,26925,27932,28365,28802,29059,29208,29363,29467,29562,29651,29698,29811,29894,29940,29965,30268,30376,30481,30542,30647,30660,30674,30699],VERSES_IN_CHAPTER:[[31,25,24,26,32,22,24,22,29,32,32,20,18,24,21,16,27,33,38,18,34,24,20,67,34,35,46,22,35,43,55,32,20,31,29,43,36,30,23,23,57,38,34,34,28,34,31,22,33,26],[22,25,22,31,23,30,25,32,35,29,10,51,22,31,27,36,16,27,25,26,36,31,33,18,40,37,21,43,46,38,18,35,23,35,35,38,29,31,43,38],[17,16,17,35,19,30,38,36,24,20,47,8,59,57,33,34,16,30,37,27,24,33,44,23,55,46,34],[54,34,51,49,31,27,89,26,23,36,35,16,33,45,41,50,13,32,22,29,35,41,30,25,18,65,23,31,40,16,54,42,56,29,34,13],[46,37,29,49,33,25,26,20,29,22,32,32,18,29,23,22,20,22,21,20,23,30,25,22,19,19,26,68,29,20,30,52,29,12],[18,24,17,24,15,27,26,35,27,43,23,24,33,15,63,10,18,28,51,9,45,34,16,33],[36,23,31,24,31,40,25,35,57,18,40,15,25,20,20,31,13,31,30,48,25],[22,23,18,22],[28,36,21,22,12,21,17,22,27,27,15,25,23,52,35,23,58,30,24,42,15,23,29,22,44,25,12,25,11,31,13],[27,32,39,12,25,23,29,18,13,19,27,31,39,33,37,23,29,33,43,26,22,51,39,25],[53,46,28,34,18,38,51,66,28,29,43,33,34,31,34,34,24,46,21,43,29,53],[18,25,27,44,27,33,20,29,37,36,21,21,25,29,38,20,41,37,37,21,26,20,37,20,30],[54,55,24,43,26,81,40,40,44,14,47,40,14,17,29,43,27,17,19,8,30,19,32,31,31,32,34,21,30],[17,18,17,22,14,42,22,18,31,19,23,16,22,15,19,14,19,34,11,37,20,12,21,27,28,23,9,27,36,27,21,33,25,33,27,23],[11,70,13,24,17,22,28,36,15,44],[11,20,32,23,19,19,73,18,38,39,36,47,31],[22,23,15,17,14,14,10,17,32,3],[22,13,26,21,27,30,21,22,35,22,20,25,28,22,35,22,16,21,29,29,34,30,17,25,6,14,23,28,25,31,40,22,33,37,16,33,24,41,30,24,34,17],[6,12,8,8,12,10,17,9,20,18,7,8,6,7,5,11,15,50,14,9,13,31,6,10,22,12,14,9,11,12,24,11,22,22,28,12,40,22,13,17,13,11,5,26,17,11,9,14,20,23,19,9,6,7,23,13,11,11,17,12,8,12,11,10,13,20,7,35,36,5,24,20,28,23,10,12,20,72,13,19,16,8,18,12,13,17,7,18,52,17,16,15,5,23,11,13,12,9,9,5,8,28,22,35,45,48,43,13,31,7,10,10,9,8,18,19,2,29,176,7,8,9,4,8,5,6,5,6,8,8,3,18,3,3,21,26,9,8,24,13,10,7,12,15,21,10,20,14,9,6],[33,22,35,27,23,35,27,36,18,32,31,28,25,35,33,33,28,24,29,30,31,29,35,34,28,28,27,28,27,33,31],[18,26,22,16,20,12,29,17,18,20,10,14],[17,17,11,16,16,13,13,14],[31,22,26,6,30,13,25,22,21,34,16,6,22,32,9,14,14,7,25,6,17,25,18,23,12,21,13,29,24,33,9,20,24,17,10,22,38,22,8,31,29,25,28,28,25,13,15,22,26,11,23,15,12,17,13,12,21,14,21,22,11,12,19,12,25,24],[19,37,25,31,31,30,34,22,26,25,23,17,27,22,21,21,27,23,15,18,14,30,40,10,38,24,22,17,32,24,40,44,26,22,19,32,21,28,18,16,18,22,13,30,5,28,7,47,39,46,64,34],[22,22,66,22,22],[28,10,27,17,17,14,27,18,11,22,25,28,23,23,8,63,24,32,14,49,32,31,49,27,17,21,36,26,21,26,18,32,33,31,15,38,28,23,29,49,26,20,27,31,25,24,23,35],[21,49,30,37,31,28,28,27,27,21,45,13],[11,23,5,19,15,11,16,14,17,15,12,14,16,9],[20,32,21],[15,16,15,13,27,14,17,14,15],[21],[17,10,10,11],[16,13,12,13,15,16,20],[15,13,19],[17,20,19],[18,15,20],[15,23],[21,13,10,14,11,15,14,23,17,12,17,14,9,21],[14,17,18,6],[25,23,17,25,48,34,29,34,38,42,30,50,58,36,39,28,27,35,30,34,46,46,39,51,46,75,66,20],[45,28,35,41,43,56,37,38,50,52,33,44,37,72,47,20],[80,52,38,44,39,49,50,56,62,42,54,59,35,35,32,31,37,43,48,47,38,71,56,53],[51,25,36,54,47,71,53,59,41,42,57,50,38,31,27,33,26,40,42,31,25],[26,47,26,37,42,15,60,40,43,48,30,25,52,28,41,40,34,28,41,38,40,30,35,27,27,32,44,31],[32,29,31,25,21,23,25,39,33,21,36,21,14,23,33,27],[31,16,23,21,13,20,40,13,27,33,34,31,13,40,58,24],[24,17,18,18,21,18,16,24,15,18,33,21,14],[24,21,29,31,26,18],[23,22,21,32,33,24],[30,30,21,23],[29,23,25,18],[10,20,13,18,28],[12,17,18],[20,15,16,16,25,21],[18,26,17,22],[16,15,15],[25],[14,18,19,16,14,20,28,13,28,39,40,29,25],[27,26,18,17,20],[25,25,22,19,14],[21,22,18],[10,29,24,21,21],[13],[14],[25],[20,29,22,11,14,17,17,13,21,11,19,17,18,20,8,21,18,24,21,15,27,21]]};var PanelSwapper=Class.create({hidden:null,visible:null,initialize:function(hidden_container,visible_container){this.hidden=hidden_container;this.visible=visible_container;},swapPanel:function(new_panel){var new_panel=$(new_panel);if(new_panel.up().visible()){return;}
$(this.visible).childElements().each(function(panel){$(this.hidden).appendChild(panel);}.bind(this));$(this.visible).appendChild(new_panel);},isPanelVisible:function(panel){return $($(panel).parentNode).visible();}});var Footnotes=Class.create({initialize:function(container){this.container=$(container);this.footnotes=new Hash();this.ebFootnoteElements=[];this.offsetfrommouse=[10,10];this.popupWidth=275;this.popupMaxHeight=500;this.currentVisiblePopup=null;this.currentimageheight=10;this.popDelay=0.1;this.delayID=null;this.mouseX=null;this.mouseY=null;this.showingFootnote=false;this.closingFootnote=true;},update:function(){this.ebFootnoteElements=this.container.select(".footnote");if(this.ebFootnoteElements.length>0){var mutipleFootnote=0;var prevElementParentNodeId;var nextElement;var nextElementParentNodeId;for(var i=0;i<this.ebFootnoteElements.length;i++){var element=this.ebFootnoteElements[i];var elementParentNodeId=element.parentNode.id;if(elementParentNodeId==0){elementParentNodeId=element.parentNode.parentNode.id;}
if(elementParentNodeId==0)
{element.parentNode
elementParentNodeId=element.up().up().down('span.verse').id;}
if(i<this.ebFootnoteElements.length-1){nextElement=this.ebFootnoteElements[i+1];nextElementParentNodeId=nextElement.parentNode.id;if(nextElementParentNodeId==0){nextElementParentNodeId=nextElement.parentNode.parentNode.id;}
if(nextElementParentNodeId==0){nextElementParentNodeId=nextElement.up().up().down('span.verse').id;}
if((elementParentNodeId==nextElementParentNodeId)||((i==0)?false:(elementParentNodeId==prevElementParentNodeId))){mutipleFootnote+=1;this.footnotes.set(elementParentNodeId+"-"+mutipleFootnote,element.innerHTML);}
else{mutipleFootnote=0;this.footnotes.set(elementParentNodeId,element.innerHTML);}}
else
{if(elementParentNodeId==prevElementParentNodeId){mutipleFootnote+=1;this.footnotes.set(elementParentNodeId+"-"+mutipleFootnote,element.innerHTML);}
else
{mutipleFootnote=0;this.footnotes.set(elementParentNodeId,element.innerHTML);}}
var newElement,anchor;newElement=this.ebFootnoteElements[i].ownerDocument.createElement('A');newElement.className="footnoteKey"
if(mutipleFootnote==0)
newElement.name=elementParentNodeId;else
newElement.name=elementParentNodeId+"-"+mutipleFootnote;newElement.innerHTML="†";newElement.setAttribute('href','javascript://');Event.observe(newElement,'mouseover',this.onShowFootnotePopup.bind(this));Event.observe(newElement,'mouseout',this.onHideFootnotePopup.bind(this));prevElementParentNodeId=elementParentNodeId;this.ebFootnoteElements[i].up().replaceChild(newElement,this.ebFootnoteElements[i]);}}},truebody:function(){return(!window.opera&&document.compatMode&&document.compatMode!="BackCompat")?document.documentElement:document.body},onShowFootnotePopup:function(e){e=e?e:e.event;this.mouseX=e.pageX?e.pageX:e.clientX+document.body.scrollLeft;this.mouseY=e.pageY?e.pageY:e.clientY+document.body.scrollTop;var toggle=Event.element(e);var footnoteKey=toggle.name;var id=footnoteKey+"-popup";this.currentVisiblePopup=id;if(!document.getElementById(id)){this.createPopup(id,footnoteKey);}
else{this.showPopup(id);}},onHideFootnotePopup:function(e){var popup=$(this.currentVisiblePopup);if(popup){popup.hide();currentVisiblePopup=null;}},createPopup:function(id,footnoteKey){var popup=document.createElement('div');popup.id=id;popup.style.position="absolute";popup.style.fontFamily='arial';popup.style.fontSize='11';popup.style.padding='0';popup.style.color='#777';popup.style.background='#FFFFFF';popup.style.filter='alpha(opacity=9S9)';popup.style.opacity='0.99';popup.style.width=this.popupWidth+'px';popup.style.maxHeight=this.popupMaxHeight+'px';$(popup).hide();document.body.appendChild(popup);this.showPopup(id);var popup_body=document.createElement('div');popup_body.id=+"-popup-body";popup_body.innerHTML=this.footnotes.get(footnoteKey);popup_body.className="versePreviewBody";popup.appendChild(popup_body);this.posPop(this.currentVisiblePopup);},showPopup:function(id){this.posPop(id);$(id).show();},posPop:function(ele){ele=$(ele);var xcoord=this.offsetfrommouse[0];var ycoord=this.offsetfrommouse[1];var docwidth=document.all?this.truebody().scrollLeft+this.truebody().clientWidth:pageXOffset+window.innerWidth-15
var docheight=document.all?Math.min(this.truebody().scrollHeight,this.truebody().clientHeight):Math.min(window.innerHeight)
if(docwidth-this.mouseX<ele.offsetWidth+30){xcoord=this.mouseX-xcoord-ele.offsetWidth-30;}else{xcoord+=this.mouseX;}
if(docheight-this.mouseY<ele.offsetHeight+30){ycoord+=document.all?this.mouseY+this.truebody().scrollTop-Math.max(0,(ele.offsetHeight+30+this.mouseY-docheight)):this.mouseY-Math.max(0,(ele.offsetHeight+30+this.mouseY-docheight-this.truebody().scrollTop));}else{ycoord+=this.mouseY;if(document.all){ycoord+=this.truebody().scrollTop}}
if(document.all){}
if(ycoord<0){ycoord=ycoord*-1;}
ele.style.left=xcoord+"px";ele.style.top=ycoord+"px";}});var CookieJar=Class.create();CookieJar.prototype={appendString:"__EB_",initialize:function(options){this.options={expires:3600,path:'',domain:'',secure:''};Object.extend(this.options,options||{});if(this.options.expires!=''){var date=new Date();date=new Date(date.getTime()+(this.options.expires*1000));this.options.expires='; expires='+date.toGMTString();}
if(this.options.path!=''){this.options.path='; path='+escape(this.options.path);}
if(this.options.domain!=''){this.options.domain='; domain='+escape(this.options.domain);}
if(this.options.secure=='secure'){this.options.secure='; secure';}else{this.options.secure='';}},put:function(name,value){name=this.appendString+name;cookie=this.options;var type=typeof value;switch(type){case'undefined':case'function':case'unknown':return false;case'boolean':case'string':case'number':value=String(value.toString());}
var cookie_str=name+"="+escape(Object.toJSON(value));try{document.cookie=cookie_str+cookie.expires+cookie.path+cookie.domain+cookie.secure;}catch(e){return false;}
return true;},remove:function(name){name=this.appendString+name;cookie=this.options;try{var date=new Date();date.setTime(date.getTime()-(3600*1000));var expires='; expires='+date.toGMTString();document.cookie=name+"="+expires+cookie.path+cookie.domain+cookie.secure;}catch(e){return false;}
return true;},get:function(name){name=this.appendString+name;var cookies=document.cookie.match(name+'=(.*?)(;|$)');if(cookies){return(unescape(cookies[1])).evalJSON();}else{return null;}},empty:function(){keys=this.getKeys();size=keys.size();for(i=0;i<size;i++){this.remove(keys[i]);}},getPack:function(){pack={};keys=this.getKeys();size=keys.size();for(i=0;i<size;i++){pack[keys[i]]=this.get(keys[i]);}
return pack;},getKeys:function(){keys=$A();keyRe=/[^=; ]+(?=\=)/g;str=document.cookie;CJRe=new RegExp("^"+this.appendString);while((match=keyRe.exec(str))!=undefined){if(CJRe.test(match[0].strip())){keys.push(match[0].strip().gsub("^"+this.appendString,""));}}
return keys;}};var eBibleGrid=Class.create(eBibleDrag,{parentElement:null,columnContainer:null,bibleTableContainer:null,bibleTable:null,ROW_LIMIT:100,hidden_sources:[],selected_rows:[],cell_in_view:null,initialize:function(element,options){try{this.parentElement=$(element);this.options=Object.extend({collapsibleColumnClass:"comm",editableColumnClass:"personal-comm"},options||{});this._buildGridTable();this.bibleTopLeft=this.bibleTable.cumulativeOffset();this.drag_initialize(this.bibleContainer);this.wheelScrolled=this._wheelScrolled.bindAsEventListener(this);Event.observe(this.bibleContainer,"mousewheel",this.wheelScrolled);Event.observe(this.bibleContainer,"DOMMouseScroll",this.wheelScrolled);this.mouseOver=this._mouseOver.bindAsEventListener(this);Event.observe(this.bibleContainer,"mouseover",this.mouseOver);}catch(err){alert(err.description)}},rowClick:function(e){var grid_cell=Event.findElement(e,'div.grid-cell span.verseNum');if(grid_cell!=undefined&&!this.widgetMode){var ordinal=Event.findElement(e,'div.grid-cell').to_ordinal();this.toggleSelectRow(ordinal);this._rowClicked();}
else
{return false;}},addColumn:function(col_id,header,body,footer,from_scratch){if(from_scratch==0){if(!body){throw new Error("Column content is blank. Please try again.");}
$("translation_"+col_id).update(header+' <img src="/images/arrow.gif" style="vertical-align:middle" width="6" height="3"/>');this.insertIntoColumn(col_id,body,"top");this.insertIntoFooter(col_id,footer);}else{this.columnContainer.insert('<td class="grid-col" id="'+col_id+'_column">'+body+'</td>');this._buildColumnHeader(col_id,header);this._buildColumnFooter(col_id,footer);this.column(col_id).observe('click',this.rowClick.bindAsEventListener(this));$(col_id+"_closer").observe('click',function(){this.removeColumn(col_id);}.bindAsEventListener(this));$$('.column-translation').each(function(c){c.stopObserving('click');});if(this.columns().length>1){$$("span.col-closer").each(function(col_closer){col_closer.show();});}}
if(!this.widgetMode&&current_user!=null){this._createDraggableColVerseNum(col_id);}
this._adjustColumns();this._adjustCommentaryBorder();this._update();if(this.options.availableComms.include(col_id))
this._displayCommentaryImage(col_id);},removeColumn:function(source){if(this.columns().length<=1)return false;if(this.columns().first().id.gsub("_column","")==source){this.cell_in_view=$(this.cell_in_view.id.gsub(this.cell_in_view.id.split('_')[1],this.firstColumn().next().id.gsub('_column','')));}
$(source+"_closer").stopObserving();this.column(source).stopObserving();$(source+'_column').remove();$(source+'_header').remove();$(source+'_footer').remove();this.alignRows();this._adjustColumns();this.scrollToCell(this.cell_in_view);this._adjustCommentaryBorder();this._update();if(this.columns().length==1){$$("span.col-closer")[0].hide();}},hideColumn:function(source){if(this.columns().length<=1)return false;$(source+"_header").addClassName("hidden");$(source+"_footer").addClassName("hidden");$(source+"_column").addClassName("hidden");$(source+"_header").removeClassName("col-header");$(source+"_footer").removeClassName("col-footer");$(source+"_column").removeClassName("grid-col");$(source+"_header").hide();$(source+"_footer").hide();$(source+"_column").hide();this._adjustColumns();this._update();},showColumn:function(source){$(source+"_header").removeClassName("hidden");$(source+"_footer").removeClassName("hidden");$(source+"_column").removeClassName("hidden");$(source+"_header").addClassName("col-header");$(source+"_footer").addClassName("col-footer");$(source+"_column").addClassName("grid-col");$(source+"_header").show();$(source+"_footer").show();$(source+"_column").show();this.alignRows();this._adjustColumns();},hiddenColumns:function(){return $('bible-table-columns').select('td.hidden');},clear:function(){this.columns().each(function(col){col.remove();});$$('.row-header').each(function(head){head.remove();});$$('.row-footer').each(function(foot){foot.remove();});},insertIntoColumn:function(source,content,position){if(!content)throw new Error("Column content is blank. Please try again.");if(!this.column(source))throw new Error("Column doesn't exist. Please try again.");if(position==undefined)position="bottom";if(position=="bottom"){this.column(source).insert({"bottom":content});}else{this.column(source).insert({"top":content});}
this._adjustColumns();this._adjustCommentaryBorder();this._update();if(this.options.availableComms.include(source)){this._displayCommentaryImage(source);}
if(!this.widgetMode&&current_user!=null){this._createDraggableColVerseNum(source);}},insertIntoFooter:function(source,content){if(!content)throw new Error("Column content is blank. Please try again.");if(!this.column(source))throw new Error("Column doesn't exist. Please try again.");$(source+"_footer").down(".content-box").update(content);},updateColumn:function(old_source,new_source,header,footer,body){if(!body){throw new Error("Column content is blank. Please try again.");}
if(old_source)
$(old_source+"_closer").stopObserving();$$('span.column-translation').each(function(translation){translation.stopObserving('click');});$("translation_"+old_source).writeAttribute('id','translation_'+new_source).update(header+' <img src="/images/arrow.gif" style="vertical-align:middle" width="6" height="3"/>');$(old_source+'_column').writeAttribute('id',new_source+'_column').update(body);$(old_source+'_header').writeAttribute('id',new_source+'_header');$(old_source+"_footer").writeAttribute('id',new_source+"_footer").down('.content-box').update(footer);$(old_source+'_panel').writeAttribute('id',new_source+'_panel');$(old_source+"_closer").writeAttribute('id',new_source+'_closer');$(new_source+"_closer").observe('click',function(){this.removeColumn(new_source);}.bindAsEventListener(this));this._adjustColumns();this._update();if(!this.widgetMode&&current_user!=null){this._createDraggableColVerseNum(new_source);}},cell:function(source,ordinal){var refnum=((ordinal+"").match(/^[0-9]{1,5}$/))?Bible.ordinal2refnum(ordinal):ordinal;return $("box_"+source+"_"+refnum);},getBibleCell:function(ordinal){var bible_cell;this.columns(true).each(function(col){if(!col.first().hasClassName(this.options.collapsibleColumnClass)){bible_cell=col.first();}}.bind(this));if(ordinal){var src=bible_cell.id.split("_")[1];bible_cell=this.cell(src,ordinal);}
return bible_cell;},getCommentaryCell:function(ordinal){var commentary_cell;this.columns(true).each(function(col){if(col.first().hasClassName(this.options.collapsibleColumnClass)){commentary_cell=col.first();}
else
commentary_cell=null;}.bind(this));if(commentary_cell&&ordinal){var src=commentary_cell.id.split("_")[1];commentary_cell=this.cell(src,ordinal);return commentary_cell;}else
return commentary_cell;},toggleSelectRow:function(ordinal,force_select){this.row(ordinal).each(function(cell){cell.toggleClassName("selected");}.bind(this));if(this.selected_rows.include(ordinal)){this.selected_rows=this.selected_rows.without(ordinal);}else{this.selected_rows.push(ordinal);}},selectRow:function(ordinal){var row=this.row(ordinal);if(row){row.each(function(cell){cell.addClassName("selected");}.bind(this));}
if(!this.selected_rows.include(ordinal)){this.selected_rows.push(ordinal);}},unselectRow:function(ordinal){var row=this.row(ordinal);if(row){this.row(ordinal).each(function(cell){cell.removeClassName("selected");}.bind(this));}
if(this.selected_rows.include(ordinal)){this.selected_rows=this.selected_rows.without(ordinal);}},selectedRows:function(){return this.selected_rows;},rows:function(){var rowElements=this.parentElement.down('table tbody tr td.grid-col').select('div.grid-cell');var numRows=rowElements?rowElements.length:0;var row=[];var rows=[];var cols=this.columns(true);for(i=0;i<numRows;i++){row=[];cols.each(function(col){row.push(col[i]);});rows.push(row);}
return rows;},columns:function(with_children){var cols=this.parentElement.select('td.grid-col');cols=cols.sortBy(function(col){return(col.down())?col.down().hasClassName(this.options.collapsibleColumnClass):false;}.bind(this));if(with_children){var colarray=[];cols.each(function(col){if(!col.childElements().length<1)
colarray.push(col.childElements());});return colarray;}
return cols;},columnHeaders:function(with_child){if(with_child){var colHeader=[];this.columnHeaders().each(function(head){if(this.column(head).down()){colHeader.push(head)}}.bind(this));return colHeader;}else{return $('eb-table-header').select('div.row-header').collect(function(headerElem){return headerElem.id.split('_')[0];});}},commentaryHeaders:function(){var headers=this.columnHeaders();var commHeaders=[];headers.each(function(head){if(this.options.availableComms.include(head))
commHeaders.push(head)}.bind(this));return commHeaders;},row:function(ordinal){var rowCells=[];this.columns().each(function(col){var src=col.id.split("_")[0];rowCells.push(this.cell(src,ordinal));}.bind(this));return rowCells.include(null)?null:rowCells;},column:function(source,with_children){return with_children?$(source+"_column").childElements():$(source+"_column");},firstColumn:function(with_children){var firstColumn=this.parentElement.down('td.grid-col');return with_children?firstColumn.childElements():firstColumn;},alignRows:function(){if(this._hasBibleColumn()&&this.columns().length>1){var rows=this.rows();rows.each(function(r){this._alignRow(r);}.bind(this));if(this._hasCollapsibleColumn())
rows.each(function(r){this._fillGapsInCollapsibleColumns(r);}.bind(this));}else{$$('.button').each(function(btn){btn.hide();});}},makeColEditable:function(source){var elements=this.column(source,true);elements.each(function(ele){this._makeCellEditable(ele);}.bind(this));},scrollPx:function(amount){new Effect.Scroll(this.bibleContainer,{x:0,y:(this.bibleContainer.scrollTop+amount),duration:0.5,transition:Effect.Transitions.EaseTo});},scrollToCell:function(elem,jump){if($(elem)){var pos=Position.page($(elem))[1]-Position.cumulativeOffset(this.bibleContainer)[1];var destinationY=this.bibleContainer.scrollTop+pos;if(jump){this.bibleContainer.scrollTop+=pos;}else{new Effect.Scroll(this.bibleContainer,{x:0,y:destinationY,duration:1,transition:Effect.Transitions.EaseTo,queue:{position:'front',scope:'scrollToScope'}});}
this.cell_in_view=$(elem);}
else{}},topLeftCell:function(){var firstColumnCells=this.firstColumn(true);Position.prepare();var topLeftCellIndex=firstColumnCells.binarySearch(null,function(cell){if(Position.withinIncludingScrolloffsets(cell,this.bibleTopLeft[0]+50,this.bibleTopLeft[1]+50)){return 0;}
else{return Position.page(cell)[1]-this.bibleTopLeft[1];}}.bind(this));return firstColumnCells[topLeftCellIndex];},_buildGridTable:function(){($('eb-table-header'))?"":this.parentElement.insert('<div class="table-content"><div class="column"><div id="eb-table-header" class="grid-header"></div><div id="eb-table-box"><table id="eb-bible-table"><tr id="bible-table-columns"></tr></table></div><div id="eb-table-footer" class="grid-footer"></div></div></div>');this.columnContainer=$('bible-table-columns');this.bibleTable=$('eb-bible-table');this.bibleContainer=$('eb-table-box');},_adjustColumns:function(){var cols=this.parentElement.select('td.grid-col');var first=cols.first();var display;if(!first)return false;if(cols.length==1){display="block";$$('br.startParagraph').invoke('show');$$('br.endParagraph').invoke('show');if(!this.widgetMode){$('eb-bible-table').setStyle({width:'35em'});}}else{display="block";$$('br.startParagraph').invoke('hide');$$('br.endParagraph').invoke('hide');var width_percentage=cols?100/cols.length:0;cols.each(function(col){col.setStyle({width:width_percentage+'%'});});$('eb-bible-table').setStyle({width:'100%'});}
$('eb-table-header').select('div.row-header').each(function(header){header.style.width=100/$('eb-table-header').select('div.row-header').length+"%";});$('eb-table-footer').select('div.row-footer').each(function(footer){footer.style.width=100/$('eb-table-footer').select('div.row-footer').length+"%";});if(!first.down())return false;if(!first.down().hasClassName("first")||!first.childElements().last().hasClassName("first")){first.childElements().each(function(row){row.addClassName("first");});}
if(first.down().getStyle("display")!=display||first.childElements().last().getStyle("display")!=display){$$('div.grid-cell.first').each(function(c){c.setStyle({'display':display});});}
this.selectedRows().each(function(row){this.selectRow(row);}.bind(this));},_update:function(){},_rowClicked:function(){},_wheelScrolled:function(e){$('eb-table-box').scrollTop-=Event.wheel(e)*30;if(this.topLeftCell()){this.cell_in_view=this.topLeftCell();}
return false;},_mouseOver:function(event){var ele=Event.findElement(event,'div');ele.setStyle({cursor:'text'});},_alignRow:function(row){var tallestCell=row[0];var tallestHeight=0;var storyHeight=0;var storyCellIndex=row.invoke('hasClassName','story').indexOf(true);var storyHeight=(storyCellIndex<0)?0:row[storyCellIndex].down("div.paragraphHeading").getHeight()+5;row.each(function(cell){if(!cell.hasClassName(this.options.collapsibleColumnClass)||(cell.hasClassName('start')&&cell.hasClassName('expanded'))){var height=0;cell.childElements().each(function(cell_element){height+=cell_element.getHeight();});if(storyCellIndex>0){height+=storyHeight;}
tallestHeight=[tallestHeight,height].max();tallestCell=(height>tallestCell.getHeight())?cell:tallestCell;}}.bind(this));row.each(function(cell){if(!cell.hasClassName(this.options.collapsibleColumnClass)||cell.hasClassName("blank-pc")){cell.setStyle({height:tallestHeight+'px'});}else if(cell.hasClassName('start')||cell.hasClassName('blank-comm')){cell.style.height=tallestHeight+'px';}
if(storyHeight!=0&&cell.hasClassName("bible")&&!cell.hasClassName("story")){cell.down("span.verse").setStyle({'display':'block'});cell.down("span.verse").setStyle({'margin':storyHeight+'px 0 0 0'});}}.bind(this));},_fillGapsInCollapsibleColumns:function(row){},_bibleLastCellResize:function(){},_removeOldRows:function(position){var rows=this.rows();if(rows.length>(this.ROW_LIMIT-1)){if(position=="top"){for(i=this.ROW_LIMIT-1;i<rows.length;i++){rows[i].invoke('remove');}}else if(position=="bottom"){for(i=(rows.length-this.ROW_LIMIT-1);i>=0;i--){rows[i].invoke('remove');}}}},_makeCellEditable:function(element){if(!element.hasClassName("inplace")){element.addClassName("inplace");new_cell=new Ajax.InPlaceEditorWithEmptyText(element.down('.editable-cell'),'/browser/updatePersonalCommentary',{rows:3});}},_makeCellCollapsible:function(cell){if(!cell.hasClassName("expanded")&&(cell.getHeight()>cell.down('.comm-entry').getHeight())){cell.down('.button').hide();}else{cell.down('.button').show();}},_expandCollapsible:function(ele){var grid_col_cell=ele.parentNode.parentNode;this.column(ele.id.split('_')[1]).stopObserving('click');grid_col_cell.setStyle({'height':ele.previous().getHeight()+'px'});var last_row=this.row(grid_col_cell.to_refnum());this._toggleCollapsibleButton(ele);this._fillGapsInCollapsibleColumns(last_row);},_shrinkCollapsible:function(ele){this._toggleCollapsibleButton(ele);var last_row=this._alignRow(eb.row(ele.parentNode.parentNode.to_refnum()));this._fillGapsInCollapsibleColumns(last_row);},_toggleCollapsibleButton:function(ele){var cell=ele.up().up();if(ele.innerHTML=='less'){ele.innerHTML='more';cell.removeClassName('expanded');ele.writeAttribute("onclick","eb._expandCollapsible($(\'"+ele.id+"\'));");}else if(ele.innerHTML=='more'){ele.innerHTML='less';cell.addClassName('expanded');ele.writeAttribute("onclick","eb._shrinkCollapsible($(\'"+ele.id+"\'));");}},_swapColumns:function(table,colIndex1,colIndex2){if(table&&table.rows&&table.insertBefore&&colIndex1!=colIndex2){for(var i=0;i<table.rows.length;i++){var row=table.rows[i];var cell1=row.cells[colIndex1];var cell2=row.cells[colIndex2];var cell1_content=cell1.innerHTML;cell1.update(cell2.innerHTML);cell2.update(cell1_content);}}},_hasBibleColumn:function(){var has_bible=false;this.columns().each(function(col){if(col.down('.grid-cell')&&!col.down('.grid-cell').hasClassName(this.options.collapsibleColumnClass))
has_bible=true;}.bind(this));return has_bible;},_hasCollapsibleColumn:function(){var has_collapsible=false;this.columns().each(function(col){if(col.down('.grid-cell')&&col.down('.grid-cell').hasClassName(this.options.collapsibleColumnClass))
has_collapsible=true;}.bind(this));return has_collapsible;},_getAllBibleCellByOrdinal:function(ordinal){var all_cell=[];this.columnHeaders().each(function(head){cell=this.cell(head,ordinal);if(cell.hasClassName("bible"))
all_cell.push(cell);}.bind(this));return all_cell;},_adjustCommentaryBorder:function(){if(this.columnHeaders().include("PC")){this.makeColEditable('PC');this.columnHeaders().each(function(col){$(col+"_column").childElements().each(function(child){child.addClassName("border");});})}
else{this.columnHeaders().each(function(col){$(col+"_column").childElements().each(function(child){child.removeClassName("border");});})}},_buildColumnHeader:function(col_id,header){$('eb-table-header').insert('<div id="'+col_id+'_header" class="row-header"><div class="left-bg">&nbsp;</div><div class="right-bg">&nbsp;</div><div class="content-box"><span id="translation_'+col_id+'"class="column-translation">'+header+' <img src="/images/arrow.gif" style="vertical-align:middle" width="6" height="3"/></span><span id="'+col_id+'_closer" class="col-closer">x</span><div id="'+col_id+'_panel" class="translation-chooser" style="display:none"></div></div></div>');},_buildColumnFooter:function(col_id,footer){$('eb-table-footer').insert('<div id="'+col_id+'_footer" class="row-footer"><div class="left-bg"></div><div class="right-bg"></div><div class="content-box">'+footer+'</div></div>');},_displayCommentaryImage:function(col_id){if($$('.dict-image')!=undefined){this.column(col_id).select('div.dict-image').each(function(imgdiv){var img=imgdiv.childElements()[0];img.setStyle({'width':'50px','height':'50px'});img.stopObserving('click');img.observe('click',function(e){img.setStyle({'width':'400px','height':'400px'});$('comm-full-image').insert("<div id='comm-full-image_"+col_id+"'class= 'comm-full-image-display'> </div>");$('comm-full-image_'+col_id).insert("<div class='comm-image-action-title'><div class='comm-image-head'>Showing full image</div><div id='comm-image-close-"+col_id+"' class='comm-image-close'>x</div></div>");$('comm-full-image_'+col_id).insert("<div id ='comm-full-image_container_"+col_id+"'</div>");$('comm-full-image_container_'+col_id).update(img);RedBox.showInline('comm-full-image_'+col_id);RedBox.activateRBWindow();$('comm-image-close-'+col_id).observe('click',function(){RedBox.close();imgdiv.insert(img.setStyle({width:'50px',height:'50px'}));$('comm-full-image_'+col_id).childElements().each(function(c){c.remove();});});});});}},_createDraggableColVerseNum:function(col_id){this.column(col_id,true).each(function(elem){var verseSpan=elem.down('.verseNum');if(verseSpan!=null){this._createDraggableSingleVerseNum(verseSpan);}}.bind(this));},_createDraggableSingleVerseNum:function(ele){if(ele.up().id!="playlist-items"){var refnum=ele.up().id.split('_')[1];var verseRef=Bible.refnum2ref(refnum);var verseNum=ele.innerHTML;var bibleRow=null;var myDrag=new Draggable(ele,{revert:true,ghosting:true,onStart:function(obj){bibleRow=obj.element.up();this._createDraggableSingleVerseNum(obj._clone);}.bind(this),onDrag:function(obj,event){var pointer=[Event.pointerX(event),Event.pointerY(event)];var so=obj.element.cumulativeScrollOffset();obj.element.style.backgroundColor="#EFEFEF";obj.element.style.border="1px solid #919191";obj.element.style.height="54px";obj.element.style.overflow="hidden";obj.element.style.verticalAlign="top";obj.element.style.float="left";obj.element.style.width="91px";obj.element.style.fontSize="1.7em";obj.element.style.textAlign="center";obj.element.style.lineHeight="50px";obj.element.style.opacity="1";if(!obj.element.down('span.ele-ref')&&bibleRow.id.split("_")[1]){obj.element.update("<span class='ele-ref'>"+Bible.refnum2shortref(bibleRow.id.split("_")[1])+"</span>");}},onEnd:function(obj,event){var pointer=[Event.pointerX(event),Event.pointerY(event)];var vp=obj.element.viewportOffset($('bible-table-columns'));var so=obj.element.cumulativeScrollOffset();if(obj.element.parentNode!=$('playlist-items')){obj.element.style.backgroundColor="#DEDEDE";obj.element.style.border="1px solid #BBBBBB";obj.element.style.cursor="pointer";obj.element.style.height="14px";obj.element.style.width="auto";obj.element.style.lineHeight="12px";obj.element.style.zIndex="1";obj.element.style.fontSize="0.6em";obj.element.style.padding="0px";}
if(eb.IE6){obj.element.style.lineHeight="14px";obj.element.style.height="16px";}
if(obj.element.parentNode!=$('playlist-items')){obj.element.down('span.ele-ref').remove();obj.element.update(parseInt(bibleRow.id.split("_")[1].slice(5,8),10));}},onDropped:function(element){this._draggableOnDropped(element,verseRef);}.bindAsEventListener(this)});ele.treeNode=$('bible-table-columns');}},_draggableOnDropped:function(element,verseRef){this.playlist._createSortablePlaylist();var currentPackId=this.playlist.currentPlaylist[0].id;var playlisttype=this.playlist.playlistType[this.playlist.currentPlaylist[0].type_index];var position=null;if($$('li.empty').length>0){$$('li.empty').first().remove();position=1;}else{position=element.up().childElements().indexOf(element)+1;}
var duplicate=false;this.playlist.currentPlaylist[1].each(function(psg){if(psg.passage!=null&&psg.passage.toString()==verseRef){duplicate=true;return;}});this.playlist._setDroppablePlaylistbarWidth();if(duplicate){if(!confirm("Verse Reference Already Exists. Do you still want to add it.")){Sortable.destroy('playlist-items');element.remove();$('playlist-items').insert('<li class="droppable"></li>');this.playlist._createSortablePlaylist();this.playlist._setDroppablePlaylistbarWidth();return false;}}
var params='playlist_item[passage]='+verseRef+'&playlist_item[position]='+position+'&playlist_item[type]='+playlisttype+'&from=verseDrag';var ajaxCreate=new Ajax.Request('/playlists/'+currentPackId+'/playlist_items',{method:'post',asynchronous:true,evalScripts:true,parameters:params,onLoading:function(){this._showLoading('eb-playlistbar','adding...');$('loading_message').setStyle({'fontSize':'1.6em'});}.bind(this),onComplete:function(transport){this.playlist._showPlaylistEditForm(verseRef,currentPackId,position,'verseDrag');this._hideLoading();}.bindAsEventListener(this)});}});Util={getWindowHeight:function(){var win_height=0;if(typeof(window.innerHeight)=='number'){win_height=window.innerHeight;}else if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)){win_height=document.documentElement.clientHeight;}else if(document.body&&(document.body.clientWidth||document.body.clientHeight)){win_height=document.body.clientHeight;}
return win_height;},toggleHighlight:function(e){var ele=Element.extend(Event.element(e));while(ele.hasClassName('verse')==false){ele=ele.parentNode;}
ele.toggleClassName('highlight');}}
bible_element_methods=({to_refnum:function(elem){refnum=new RegExp(/[A-Za-z\_]+(\d+)/).exec($(elem).id);return refnum[1];},to_ordinal:function(elem){return Bible.refnum2ordinal(elem.to_refnum());},in_column:function(elem){return new RegExp(/([A-Z]+)/).exec($(elem).id).first();},get_height:function(elem){var height=0;elem.childElements().each(function(child){height+=child.getHeight();});return height;}});$w('SPAN DIV').each(function(tag){Element.addMethods(tag,bible_element_methods)});Element.addMethods({removeAllCell:function(elem){while(elem.childNodes.length>0){elem.removeChild(elem.childNodes[0]);}}});Object.extend(Event,{wheel:function(event){var delta=0;if(!event)event=window.event;if(event.wheelDelta){delta=event.wheelDelta/120;if(window.opera)delta=-delta;}else if(event.detail){delta=-event.detail/3;}
return Math.round(delta);}});Effect.Transitions.EaseFromTo=function(pos){if((pos/=0.5)<1)return 0.5*Math.pow(pos,4);return-0.5*((pos-=2)*Math.pow(pos,3)-2);};Effect.Transitions.EaseFrom=function(pos){return Math.pow(pos,4);};Effect.Transitions.EaseTo=function(pos){return Math.pow(pos,0.25);};Effect.Scroll=Class.create();Object.extend(Object.extend(Effect.Scroll.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);var options=Object.extend({x:0,y:0,mode:'absolute'},arguments[1]||{});this.start(options);},setup:function(){if(this.options.continuous&&!this.element._ext){this.element.cleanWhitespace();this.element._ext=true;this.element.appendChild(this.element.firstChild);}
this.originalTop=this.element.scrollTop;if(this.options.mode=='absolute'){this.options.y-=this.originalTop;}else{}},update:function(position){this.element.scrollTop=this.options.y*position+this.originalTop;}});Array.prototype.binarySearch=function binarySearch(find,comparator){var low=0,high=this.length-1,i,comparison;while(low<=high){i=parseInt((low+high)/2,10);comparison=comparator(this[i],find);if(comparison<0){low=i+1;continue;};if(comparison>0){high=i-1;continue;};return i;}
return null;};var eBible=Class.create(eBibleGrid,{widgetMode:false,container:null,toolbar:null,playlistBar:null,footnotes:null,cache:null,bufferPx:1000,userAction:null,copyrights:[],selectedList:null,cachedRangeLoaded:[0,0],IE6:false,initialize:function($super,elemID,options){this.container=$(elemID);if(!$('eb-widget')){this.widgetMode=true;this._buildContainer();}else{this.bible=$('eb-bible');this.dict=$('eb-dict');this.settings=$('eb-settings');}
$super('eb-bible');this.options=Object.extend({sources:"NIV",varName:"eb",width:430,height:300,textSize:18,showTitle:true,showTools:true,domain:"http://glory.ebible.com",passage:"Gen 1:1",playlist:null,availableBibles:"esv,hcsb,italrv,kjv,msg,nasb,ncv,niv,nkjv,sparv,tniv",availableComms:"pc,bbc,hbhc,jcac,kjbc,mcgee,mhcc,nnibc,tod,tpm"},this.options||{});this.options=Object.extend(this.options,options||{});var selectionbar=($('eb-selection-bar'))?$('eb-selection-bar'):$('eb-main-box').insert('<div id="eb-selection-bar" class="selection"><div id="selectionbar-head" class="selection-bar"><div class="head">Your Selected Verses</div><div class="close" title="close">x</div></div><div><input type="text" value="" id="verse-field" /></div><div id="verse-auto"><div class="default">Enter verse/passage</div>'+'<ul class="feed"></ul></div>').down('#eb-selection-bar');if(!this.widgetMode){this.playlist=new PlaylistBar(this);this.selectedList=new selectedPassageList(this,'verse-field','verse-auto',{newValues:true,regexSearch:false});}
selectionbar.hide();$('selectionbar-head').down('.close').observe('click',function(){this.selectedList.hide();this.selectedList.clear(true);}.bind(this));this.toolbar=new eBibleToolbar(this);this.cache=new Cache(10);this.footnotes=new Footnotes('eb-table-box');this.checkScrollPosition=this._checkScrollPosition.bindAsEventListener(this);this.pollingExecuter=new PeriodicalExecuter(this.checkScrollPosition,3);this.keyPressed=this._keyPressed.bindAsEventListener(this);document.observe("keypress",this.keyPressed);if(this.widgetMode){this.options.showTools=false;this._setWidgetOptions();this.loadPassage(this.options.passage);var transactionObj=YAHOO.util.Get.script(this.options.domain+'/bibles.json?callback=eb.jsonEbibleApi',{onFailure:function(o){this.options.availableBibles="";this.options.availableComms="";},scope:this});}},jsonEbibleApi:function(transport)
{var bibles=[];transport.each(function(bible){bibles.push(bible.short_name);});this.options.availableBibles=bibles.join(",");this._buildColumnBibleChoosers();},destroy:function(){Event.stopObserving(window);Event.stopObserving(document);Event.stopObserving(this.container);Event.stopObserving(this.bibleContainer);this.pollingExecuter.stop();this.cache.clear();},loadPassage:function(ref){var range=this.rangeLoaded();this._remote("search",'eb-main-box',unescape(ref),{query:unescape(ref),sources:this.options.sources,first:range[0],last:range[1]});},loadPlaylist:function(playlist_id,list_ele){if(list_ele){list_ele.addClassName('selected-playlist');var playlist_list=$A($("user-playlist-list").getElementsByTagName("li"));playlist_list.without(list_ele).each(function(s){s.removeClassName('selected-playlist');});}},scrollToRefnum:function(refnum,jump){refnum="box_"+refnum;this.scrollToCell(refnum,jump);var elementToHighlight=$(refnum).down('span.verse')?$(refnum).down('span.verse'):$(refnum);window.setTimeout(function(){elementToHighlight.setStyle({border:'1px solid #ffff99'});},1000);new Effect.Highlight(elementToHighlight,{duration:5,queue:{position:'end',scope:'scrollToScope'}});window.setTimeout(function(){elementToHighlight.setStyle({border:'0px'});},4000);},scrollToNextStory:function(){var next=this.topLeftCell().next('div.grid-cell.story')||this.topLeftCell().next('div.grid-cell.story');this.scrollToCell(next);},scrollToPrevStory:function(){var prev=this.topLeftCell().previous('div.grid-cell.story')||this.topLeftCell().previous('div.grid-cell.story');this.scrollToCell(prev);},searchReceived:function(result){this.waitingForCallback=false;switch(result.action){case 0:this.scrollToRefnum(this.firstColumn().id.gsub('_column','')+'_'+Bible.ordinal2refnum(result.ordinal[0]));if(pageTracker)pageTracker._trackEvent('bible','scroll',unescape(result.query));break;case 1:this.jumpReceived(result.columns,result.copyrights);this.scrollToRefnum(this.columnHeaders()[0]+'_'+Bible.ordinal2refnum(result.ordinal[0]));if(pageTracker)pageTracker._trackEvent('bible','jump',unescape(result.query));break;case 4:$('results-tab').update(result.results);windowResized();if(result.highlightSearch){if(sidebar.tabs)
sidebar.tabs.manualActivate('search-tab-title');else
fabtab.manualActivate('search-tab-title');}
this._hideLoading();this.ensureBibleLoaded();if(result.query)this.cache.setItem(result.query,result.results);if(pageTracker)pageTracker._trackEvent('bible','search',unescape(result.query));return true;break;}
if(result.query){$H(result.columns).keys().each(function(src){this.cache.setItem(src+"_"+result.query,result);}.bind(this));}
this._hideLoading();},jumpReceived:function(columns,copyrights){var sources=$H(columns).keys();this.clear();sources=this._sortSources(sources);sources.each(function(src){this.addColumn(src,columns[src].name,columns[src].html,copyrights[src])}.bind(this));this.footnotes.update();this.alignRows();this._buildColumnBibleChoosers();this._updateTitle();this._hideLoading();},prependReceived:function(columns){this.waitingForCallback=false;var sources=$H(columns).keys();firstLocalOrdinal=columns[sources[0]].start_ordinal;var yStart=this.bibleTable.getHeight();if(firstLocalOrdinal){sources.each(function(src){this.insertIntoColumn(src,columns[src].html,"top");this.cache.setItem(src+"_"+firstLocalOrdinal,columns[src].html);}.bind(this));this.footnotes.update();this.alignRows();var yDiffAfterInsert=Math.abs(yStart-this.bibleTable.getHeight());this.bibleContainer.scrollTop+=yDiffAfterInsert;}},appendReceived:function(columns){this.waitingForCallback=false;var sources=$H(columns).keys();lastLocalOrdinal=columns[sources[0]].start_ordinal
var yStart=this.bibleTable.getHeight();if(lastLocalOrdinal){sources.each(function(src){this.insertIntoColumn(src,columns[src].html,"bottom");this.cache.setItem(src+"_"+lastLocalOrdinal,columns[src].html);}.bind(this));this.footnotes.update();this.alignRows();}
var yDiffAfterRemove=Math.abs(yStart-this.bibleTable.getHeight());},addColumnsReceived:function(result){this.waitingForCallback=false;var sources=$H(result.columns).keys();sources=this._sortSources(sources);if(sources.length==1){this.addColumn(sources[0],result.columns[sources[0]].name,result.columns[sources[0]].html,result.copyrights[sources[0]],result.from_scratch);}else{sources.each(function(src){this.addColumn(src,result.columns[src].name,result.columns[src].html,result.copyrights[src],result.from_scratch);}.bind(this));}
this.footnotes.update();this.alignRows();var ref_cell=this.columnHeaders()[0]+'_'+result.topleft_refnum;this.scrollToRefnum(ref_cell,true);this._buildColumnBibleChoosers();this._updateTitle();this._hideLoading();},updateColumnReceived:function(result){this.waitingForCallback=false;var source=$H(result.column).keys();this.updateColumn(result.old_source,source[0],result.column[source[0]].name,result.copyright,result.column[source[0]].html);this.footnotes.update();this.alignRows();var ref_cell=source[0]+'_'+result.topleft_refnum;this.scrollToRefnum(ref_cell,true)
this._buildColumnBibleChoosers();this._hideLoading();},createBibleTranslationOptions:function(){var html_options='<select id ="bible-translation" class="dropdown">';var first_open_src=eb.options.sources.split(",").first();var sources=this.options.availableBibles.split(",");sources.each(function(src){if(src==first_open_src)
html_options+='<option value="'+src+'" selected="selected">'+src+'</option>';else
html_options+='<option value="'+src+'">'+src+'</option>';});html_options+='</select>';return html_options;},rangeLoaded:function(){var verseElements=this.bibleTable.select("div.grid-cell.first span.verse");if(verseElements.length>0){first=verseElements.first().to_ordinal();last=verseElements.last().to_ordinal();this.cachedRangeLoaded=[first,last];}
return this.cachedRangeLoaded;},ensureBibleLoaded:function(){var range=this.rangeLoaded();if(!range[0]){this._remote("search",this.bibleContainer.id,"Gen 1:1",{query:"Gen 1:1",sources:this.options.sources,first:range[0],last:range[1]});}},_buildContainer:function(){this.container.insert('<div id="eb-widget" class="eb-content"><div class="eb-bordered-box"><div id="eb-main-box-container"><div id="eb-main-box" class="eb-main-box"></div></div></div></div>');this.bible=$('eb-main-box').insert('<div id="eb-bible" class="middle-part"></div>').down('#eb-bible');},_setWidgetOptions:function(){if(this.options.height&&this.options.width){$$('div.eb-bordered-box')[0].setStyle({width:this.options.width+'px'});$('eb-bible-table').setStyle({width:this.options.width+'px'});headerfooterheight=parseInt($('eb-table-header').getHeight())+parseInt($('eb-table-footer').getHeight())+3;if(this.options.showTitle){this.toolbar.container.show();$('eb-tools').hide();$('eb-viewing').show();newheight=parseInt(this.options.height)-parseInt($('eb-toolbar').getHeight())-headerfooterheight;$('eb-table-box').setStyle({height:newheight+'px'});}else{this.toolbar.container.hide();$('eb-tools').hide();$('eb-viewing').show();newheight=parseInt(this.options.height)-headerfooterheight;$('eb-table-box').setStyle({height:newheight+'px'});}}},_updateSources:function(){var all_sources=[];this.columns().each(function(col){all_sources.push((col.id).gsub('_column',''));}.bind(this));if(this.options.sources!=all_sources.join(',')){this.options.sources=all_sources.join(",");this.toolbar.updateParallelMenu();if(!this.widgetMode){cookiejar.put('sources',this.options.sources);}}},_update:function(){this._updateSources();$$(".verse-ref").each(function(s){s.className="verse-ref2";s.href="#"+s.readAttribute("name")+");"}.bind(this));},_rowClicked:function(){if(this.selectedRows().length>0){this.selectedList.updateSelected(this.selectedRows());}else{this.selectedList.clear();this.selectedList.hide();}},_keyPressed:function(e){if(!e)var e=window.event;var code=e.keyCode||e.charCode;var character=String.fromCharCode(code).toLowerCase();switch(code){case Event.KEY_ESC:this.selectedList.clear(true);Event.stop(e);return true;case 43:this.toolbar._resizeText(2);return true;case 45:this.toolbar._resizeText(-2);return true;}},_stateChange:function(state){if(panelSwapper&&!panelSwapper.isPanelVisible('eb-main-box')){panelSwapper.swapPanel('eb-main-box');}
var cached_results=this.cache.getItem(state);if(cached_results){this.searchReceived({'query':null,'action':4,'results':cached_results});}
else{var loading_element=(unescape(state).match(/\d/))?this.bibleContainer:$('tab-content');var range=this.rangeLoaded();this._remote("search",loading_element.id,unescape(state),{query:unescape(state),sources:eb.options.sources,first:range[0],last:range[1]});}},_buildColumnBibleChoosers:function(){var sources=this.options.sources.split(",");var bibles_in_chooser=[];var comms_in_chooser=[];this.options.availableBibles.split(',').each(function(bible){if(!sources.include(bible))
bibles_in_chooser.push(bible);});this.options.availableComms.split(',').each(function(comms){if(!sources.include(comms))
comms_in_chooser.push(comms)});sources.each(function(src){var columnChooserPanel=$(src+'_panel');var temp=[];var availableBibles=[];this.options.availableBibles.split(',').each(function(bible){availableBibles.push(bible.capitalize());});if(availableBibles.include(src.capitalize())){bibles_in_chooser.each(function(chooser){temp.push('<div id="'+chooser+'_bible" class="column-chooser">'+chooser+'</div>')});columnChooserPanel.update(temp.join(''));}else{comms_in_chooser.each(function(chooser){temp.push('<div id="'+chooser+'_bible" class="column-chooser">'+chooser+'</div>')});columnChooserPanel.update(temp.join(''));}
$('translation_'+src).stopObserving();$('translation_'+src).observe('click',function(){if(eb.widgetMode){columnChooserPanel.setStyle({left:($('translation_'+src).cumulativeOffset()[0])+'px'});}
else{columnChooserPanel.setStyle({left:($('translation_'+src).cumulativeOffset()[0]-$('left').getWidth())+'px'});}
columnChooserPanel.toggle();});var bible_chooser=$(src+'_panel').select('div.column-chooser');bible_chooser.each(function(chooser){chooser.observe('click',function(){var old_source=chooser.up('div.row-header').id.split('_')[0];var new_source=chooser.innerHTML;var range=this.rangeLoaded();var topleft_refnum=this.cell_in_view.to_refnum();var cache=this.cache.getItem(new_source+"_"+first+"_"+last);if(cache){}else{this._remote("updateColumn",chooser.up('div.row-header').id.gsub('header','column'),new_source,{old_source:old_source,new_source:new_source,topleft_refnum:topleft_refnum,first:range[0],last:range[1]});columnChooserPanel.hide();}
this.toolbar.updateParallelMenu();}.bindAsEventListener(this));}.bind(this));}.bind(this));},_remote:function(action,loadingElement,message,params){if(this.waitingForCallback){return false;}
var url=this.options.domain+'/browser/'+action;if(params=Object.toQueryString(params)){url+=(url.include('?')?'&':'?')+params;}
this._showLoading(loadingElement,message);this.waitingForCallback=true;var transactionObj=YAHOO.util.Get.script(url,{onSuccess:function(o){this.waitingForCallback=false;},onFailure:function(o){alert('Sorry, there was a problem contacting the server. Please try again or contact support@ebible.com');this.waitingForCallback=false;},scope:this});window.setTimeout(function(){if($$('.loader')){$$('.loader').invoke('remove');}
this.waitingForCallback=false;}.bind(this),5000);},_checkScrollPosition:function(e){var range=this.rangeLoaded();if(!range[0]||(panelSwapper&&!panelSwapper.isPanelVisible('eb-main-box'))||($('RB_window')&&$('RB_window').visible())){return false;}
var ordinal=null;var cached=null;if((this.bibleContainer.scrollTop+this.bibleContainer.getHeight()+this.bufferPx)>=this.bibleTable.getHeight()){ordinal=range[1]+1;if(ordinal<31102){cached=this.cache.getItem(this.options.sources.split(',').join("_")+"_"+ordinal);if(cached){this.appendReceived(null,cached);}else{this._remote("appendIntoColumns",this.bibleContainer.id,"buffering",{lastLocalOrdinal:ordinal,sources:this.options.sources.split(',').join(",")});}}}else if((this.bibleContainer.scrollTop-this.bufferPx)<=0){ordinal=range[0]-1;if(ordinal>0){console.log("buffering up");cached=this.cache.getItem(this.options.sources.split(',').join("_")+"_"+ordinal);if(cached){this._prependReceived(null,cached);}else{if(this.options.sources.split(',').length>0){this._remote("prependIntoColumns",this.bibleContainer.id,"buffering",{firstLocalOrdinal:ordinal,sources:this.options.sources.split(',').join(",")});}}}}
this._updateTitle();},_updateTitle:function(){var elem=this.topLeftCell();if(!elem){return false;}
var refnum=elem.to_refnum();var booknum=parseInt(refnum.slice(0,2),10);var chapternum=parseInt(refnum.slice(2,5),10);var story;story=(elem.hasClassName("story"))?elem:elem.previous('div.story');var title=Bible.LONGNAMES[booknum-1]+" "+chapternum;title+=story?": "+story.down("div.paragraphHeading").innerHTML:"";$('eb-viewing').update(title);},_sortSources:function(sources){return sources.sortBy(function(col){var score=this.options.availableComms.indexOf(col);return(score>0)?score:(['KJV','SpaRV','ItalRV'].include(col))?0:score}.bind(this));},_showLoading:function(loading_element,message){if(message==undefined){message="";}
var show_loading_over=loading_element.split(',');show_loading_over.each(function(element){$(element).insert("<div id ='loading_"+element+"' style='display:none' class='loader'><div id='loading_message'>"+message+"</div></div>");var p=$(element).cumulativeOffset();if(this.IE6){$('loading_'+element).style.left=element.split('_')[1]!='column'?0:($(element).cumulativeOffset()[0]-$('left').getWidth()-20)+"px";}
else{$('loading_'+element).style.left=p[0]+'px';}
$('loading_'+element).style.top=this.IE6?0:p[1]+'px';$('loading_'+element).style.width=$(element).getWidth()+'px';if($(element).id=='eb-playlistbar'){$('loading_'+element).style.width=$(element).getWidth()-5+'px';}
if(element.split('_')[1]=='column'){$('loading_'+element).style.height=(!this.widgetMode&&$('eb-playlistbar').visible())?$('eb-table-box').getHeight()-$('eb-playlistbar').getHeight()-10+'px':$('eb-table-box').getHeight()+'px';}
else{$('loading_'+element).style.height=(!this.widgetMode&&$('eb-playlistbar').visible()&&loading_element=='eb-table-box')?$(element).getHeight()-$('eb-playlistbar').getHeight()-10+'px':$(element).getHeight()+'px';}
$('loading_'+element).show();}.bind(this));return true;},_hideLoading:function(element_id){$$('.loader').invoke('remove');if(!this.widgetMode){windowResized();}}});var eBibleSideBar=Class.create();eBibleSideBar.prototype={tabs:null,initialize:function(element,options){this.options=Object.extend({varName:"sidebar",eBibleVarName:"eb",domain:"http://ebible.com"},options||{});this.container=$(element);if(this.options.build){this._buildContainer();this._buildSearchTab();this._buildDictionaryTab();this._buildTagTab();this._buildPlaylistTab();}
this.tabs=new Fabtabs('tabs');},_buildContainer:function(){this.container.insert('<ul id="tabs" class="tabs"></ul>');$('tabs').insert('<li id="search-tab-title"><a href="/ebible#results-tab"><span>Search</span></a></li>');$('tabs').insert('<li id="playlist-tab-title"><a href="/ebible#playlist-tab"><span>Playlists</span></a></li>');$('tabs').insert('<li id="tag-tab-title"><a href="/ebible#tag-tab"><span>Tags</span></a></li>');$('tabs').insert('<li id="dict-tab-title"><a href="/ebible#dict-tab"><span>Dictionaries</span></a></li>');this.container.insert('<div class="tab-container"><div id="left-box"><div class="bg"><div id="tab-content" class="content"><!-- tabs go here --></div></div></div></div><div class="btm-bg"><span>&nbsp;</span><em>&nbsp;</em></div>');},_buildSearchTab:function(){$('tab-content').insert('<div id="results-tab" class="text-box">'+'<div id="welcome-header"><h1>Hello, I am your new eBible!</h1></div>'+'<div id="welcome-content" class="content-text"><p>Take some time to explore me and see how I help you use, understand and share the Bible like never before.</p>'+'<strong>I can:</strong>'+'<ul><li><span class="bullet">&raquo; </span>always open up to where you left off</li>'+'<li><span class="bullet">&raquo; </span>show 4 parallel bibles/commentaries</li>'+'<li><span class="bullet">&raquo; </span>help you search for anything in the bible</li>'+'<li><span class="bullet">&raquo; </span>tag verses for you to find them later</li>'+'<li><span class="bullet">&raquo; </span>let you use my reference library</li>'+'<li><span class="bullet">&raquo; </span>read my dramatic bible out loud to you</li>'+'<li><span class="bullet">&raquo; </span>help you memorize scripture</li></ul>'+'<br>'+'<h1>Problems?</h1>'+'<p>God\'s Word is perfect and complete ... but unfortunately your new eBible still has some issues we are working on ... send bug reports to <a href="mailto:bugs&#64;ebible.com">bugs&#64;ebible.com</a></p>'+'<br>'+'</div><div id="welcome-footer"></div>');},_buildPlaylistTab:function(){new Insertion.After('results-tab','<div id="playlist-tab" class="text-box"></div>');},_buildDictionaryTab:function(){$('tab-content').insert('<div id="dict-tab" class="text-box" style="display: none;"><div id="dict-toolbar"></div><div id="dict-results"></div></div>');$('tab-content').insert('');var r=new Ajax.Updater("dict-toolbar","/dictionaries",{method:'get'});},_buildTagTab:function(){$('tab-content').insert('<div id="tag-tab" class="text-box" style="display: none;"></div>');$('tag-tab').insert(new Element('div',{'id':'tag-tab-header'}));$('tag-tab-header').insert(new Element('form',{'id':'form_autocomplete','name':'form_autocomplete','onsubmit':'return sendRequest()'}));$('form_autocomplete').insert(new Element('div',{'id':'tag-search'}));var temp_row=[];temp_row.push("<table border='0' cellpadding='3'><tr><td><select id='tag_type_select' class='dropdown'><option value='1'>My Tags</option><option value='2'>All Tags</option><option value='3'>My Passages</option><option value='4' selected='true'>All Passages</option></select></td>");temp_row.push("<td><input type='text' id='tag_autocomplete' value='for this tag' name='tag_autocomplete'/><div id='autocomplete_choices' class='autocomplete'></div></td>");temp_row.push("<td><span id='indicator1' style='display:none'><img src='/images/spinner.gif' alt='Working...' /></span></td></tr></table>");$('tag-search').update(temp_row.join(""));$('autocomplete_choices').setStyle({left:$('tag_autocomplete').cumulativeOffset()[0]+'px'});$('autocomplete_choices').setStyle({left:$('tag_autocomplete').cumulativeOffset()[1]+$('tag_autocomplete').getHeight()+'px'});$('tag-tab-header').insert(new Element('div',{'id':'link_container','class':'tag-toolbar'}));$('link_container').insert(new Element('div',{'id':'display-options'}).update('<span id="display_list" class="link selected">list</span> | <span id="display_cloud" class="link">cloud</span>'));$('link_container').insert(new Element('div',{'id':'order-options'}).update('<span id="order_recent" class="link">recent</span> | <span id="order_popular" class="link selected">popular</span>'));$('tag-tab-header').insert(new Element('span',{'id':'tag_passage_status'}));$('tag-tab').insert(new Element('div',{'id':'tag_tab_body'}));new Ajax.Autocompleter("tag_autocomplete","autocomplete_choices","/tagged_passages/suggestion",{method:'GET',minChars:3,indicator:'indicator1',callback:function(){return'select='+$F('tag_type_select')+'&tag_autocomplete='+$F('tag_autocomplete');}});$('tag_autocomplete').defaultValueActsAsHint();loadTaggable(false);},_loadPlaylists:function(){var url=this.options.domain+'/playlists.js?callback='+this.options.varName+'._playlistReceived';var transactionObj=YAHOO.util.Get.script(url,{onSuccess:function(o){this.waitingForCallback=false;},onFailure:function(o){alert('Sorry, there was a problem contacting the server. Please try again or contact support@ebible.com');this.waitingForCallback=false;},scope:this});},_playlistReceived:function(json){var selected_playlist_id=null;if($('user-playlist')&&$$('.selected-playlist').first()){selected_playlist_id=$$('.selected-playlist').first().id;}
$('playlist-tab').update(json[2]);if($(selected_playlist_id)){$(selected_playlist_id).addClassName("selected-playlist");$(selected_playlist_id).down('input[type=radio]').writeAttribute("checked",1);}
windowResized();}};function loadTaggable(flag){if(flag){if($('tag_type_select').value!="2"&&$('tag_type_select').value!="4"){new Ajax.Updater('tag_tab_body','/tagged_passages',{parameters:{type:getTagState("type"),show:getTagState("show"),order:getOrderParam(),display:getDisplayParam(),tag_autocomplete:$('tag_autocomplete').emptyValue()?"":$F("tag_autocomplete")},asynchronous:true,evalScripts:true,method:'get'});}}
else{$('tag_type_select').value="4";$('tag_autocomplete').value="for this tag";new Ajax.Updater('tag_tab_body','/tagged_passages',{parameters:{type:getTagState("type"),show:getTagState("show"),order:getOrderParam(),display:getDisplayParam()},asynchronous:true,evalScripts:true,method:'get',onComplete:function(request){initTagTab();}});loadLocalAutocompleter();}
if(!$('link_container').visible()){$('link_container').setStyle({'display':'block'});$('tag_passage_status').setStyle({'display':'block'});}};function initTagTab(){if($('tag_autocomplete')){$('tag_autocomplete').defaultValueActsAsHint();}
updateTagPassageStatus();$('tag_type_select').observe('change',function(){switch($F('tag_type_select')){case'1':$('tag_autocomplete').stopObserving();$('tag_autocomplete').defaultValueActsAsHint();$('tag_autocomplete').setHint("for this verse");if(!current_user){$('tag_passage_status').update("");$('link_container').hide();$('tag_passage_status').hide();}
if(current_user)
new Autocompleter.Local('tag_autocomplete','autocomplete_choices',Bible.LONGNAMES,{});break;case'2':$('tag_autocomplete').stopObserving();$('tag_autocomplete').defaultValueActsAsHint();$('tag_autocomplete').setHint("for this verse");$('link_container').show();$('tag_passage_status').show();if(current_user)
new Autocompleter.Local('tag_autocomplete','autocomplete_choices',Bible.LONGNAMES,{});break;case'3':$('tag_autocomplete').stopObserving();$('tag_autocomplete').defaultValueActsAsHint();$('tag_autocomplete').setHint("for this tag");if(!current_user){$('tag_passage_status').update("");$('link_container').hide();$('tag_passage_status').hide();}
if(current_user){new Ajax.Autocompleter("tag_autocomplete","autocomplete_choices","/tagged_passages/suggestion",{method:'GET',minChars:3,indicator:'indicator1',callback:function(){return'select='+$F('tag_type_select')+'&tag_autocomplete='+$F('tag_autocomplete');}});}
break;case'4':$('tag_autocomplete').stopObserving();$('tag_autocomplete').defaultValueActsAsHint();$('tag_autocomplete').setHint("for this tag");$('link_container').show();$('tag_passage_status').show();new Ajax.Autocompleter("tag_autocomplete","autocomplete_choices","/tagged_passages/suggestion",{method:'GET',minChars:3,indicator:'indicator1',callback:function(){return'select='+$F('tag_type_select')+'&tag_autocomplete='+$F('tag_autocomplete');}});break;}
document.location.href="#"+getTagState()+"/"+getOrderParam()+"/"+getDisplayParam();});$('display_list').observe('click',function(e){if($('display_list').hasClassName("selected")){return false;}
changeDisplayLink('display_list','display_cloud');params="";params=getTagState()+"/";params+=getOrderParam();params+="/list";if(!$('tag_autocomplete').emptyValue()){params+="/"+$F('tag_autocomplete');}
document.location.href="#"+params;});$('display_cloud').observe('click',function(e){params="";if($('display_cloud').hasClassName("selected")){return false;}
changeDisplayLink('display_list','display_cloud');params="";params=getTagState()+"/";params+=getOrderParam();params+="/cloud";if(!$('tag_autocomplete').emptyValue()){params+="/"+$F('tag_autocomplete');}
document.location.href="#"+params;});$('order_recent').observe('click',function(e){params="";if($('order_recent').hasClassName("selected")){return false;}
changeDisplayLink('order_recent','order_popular');params="";params=getTagState();params+="/recent/";params+=getDisplayParam();if(!$('tag_autocomplete').emptyValue()){params+="/"+$F('tag_autocomplete');}
document.location.href="#"+params;});$('order_popular').observe('click',function(e){if($('order_popular').hasClassName("selected")){return false;}
changeDisplayLink('order_recent','order_popular');params="";params=getTagState();params+="/popular/";params+=getDisplayParam();if(!$('tag_autocomplete').emptyValue()){params+="/"+$F('tag_autocomplete');}
document.location.href="#"+params;});}
function sendRequest(){params="";params+=getTagState()+"/"+getOrderParam()+"/"+getDisplayParam();if(!$('tag_autocomplete').emptyValue())
params+="/"+$F('tag_autocomplete');document.location.href="#"+params;return false;}
function changeDisplayLink(ele1,ele2){$(ele1).toggleClassName('selected');$(ele2).toggleClassName('selected');}
function getTagState(value){switch($F('tag_type_select')){case'1':params="tags/mine";break;case'2':params="tags/all";break;case'3':params="passages/mine";break;case'4':params="passages/all";break;}
if(value=="type"){return params.split("/")[0];}
else if(value=="show"){return params.split("/")[1];}
else{return params;}}
function getOrderParam(){params="";if($('order_recent').hasClassName("selected")){params="recent";}else{params="popular";}
return params;}
function getDisplayParam(){params="";if($("display_cloud").hasClassName("selected")){params="cloud";}else{params="list";}
return params;}
function updateTagPassageStatus(){status="";temp=getTagState().split("/");if(!$('tag_autocomplete').emptyValue()){console.log("adding for .... to title ");status+=": <strong>"+$F('tag_autocomplete')+"</strong>";}
$('tag_passage_status').update(temp[1].capitalize()+" "+getOrderParam()+" "+temp[0]+status.gsub("\\+"," "));if($('clear_tag_autocomplete')==null&&!$('tag_autocomplete').emptyValue()){$('tag_passage_status').insert(new Element('img',{'id':'clear_tag_autocomplete','title':'clear','src':'/images/clear.gif','alt':'Clear','width':'16px','height':'16px'}));$('clear_tag_autocomplete').observe('click',function(){$('tag_autocomplete').value="";params="";params+=getTagState()+"/"+getOrderParam()+"/"+getDisplayParam();document.location.href="#"+params;$('tag_passage_status').down().remove();$('clear_tag_autocomplete').remove();$('tag_autocomplete').focus();});}}
function updateLinksAfterTagging(){if(!$('display_list').hasClassName('selected')){changeDisplayLink('display_list','display_cloud');}
if(!$('order_recent').hasClassName('selected')){changeDisplayLink('order_recent','order_popular');}}
function loadLocalAutocompleter(){$('tag_autocomplete').stopObserving();$('tag_autocomplete').defaultValueActsAsHint();$('link_container').show();$('tag_passage_status').show();new Autocompleter.Local('tag_autocomplete','autocomplete_choices',Bible.LONGNAMES,{});}
var eBibleSearchBar=Class.create();eBibleSearchBar.prototype={initialize:function(element,ebible_variable_name){this.container=$(element);this.ebible_variable_name=ebible_variable_name;this._buildContainer();this.verseChooser=new VerseChooser('versechooser',this.lookupVerse.bindAsEventListener(this));Event.observe($('vc'),"click",this.verseChooser.showChooser.bindAsEventListener(this.verseChooser));},lookupVerse:function(verse){$('query').value=verse;document.location.href="#"+verse;},_buildContainer:function(){this.container.insert('<form action="#" method="get" onsubmit="document.location.href = \'#\' + $F(\'query\'); return false;"><label>eg. Rom 8:28, love, heaven </label><table><tr><td><input type="text" id="query" value="Enter Keyword or Verse" class="text"  /></td><td><a id="query-search" class="btn"><i></i><span><span></span><i></i>Search</span></a></td><td><a id="vc" class="btn"><i></i><span><span></span><i></i>Browse</span></a></td></tr></table></form>');$('query').defaultValueActsAsHint();$('query-search').observe('click',function(event){if(!$('query').hasClassName('hint')){document.location.href="# "+$F('query');}});}};var eBibleToolbar=Class.create({ebible_widget:null,bibles:null,comms:null,MAX_SOURCES:4,bibles_commentaries:[],passage_collection:[],embed:null,initialize:function(widget,options){this.ebible_widget=widget;this.bibles=this.ebible_widget.options.availableBibles.split(',');this.comms=this.ebible_widget.options.availableComms.split(',');this.container=($('eb-toolbar'))?$('eb-toolbar'):$('eb-main-box').insert({top:'<div id="eb-toolbar" class="title"><div class="bg"><div id="eb-viewing" class="toolbar-cell"></div><div id="eb-tools" class="toolbar-cell">'+'<a id="toolbar_font_decrease" class="btnR lime"><i></i><span><span></span><i></i>-</span></a>'+'<a id="toolbar_font_increase" class="btnR lime"><i></i><span><span></span><i></i>+</span></a>'+'<a id="toolbar_memorize" class="btnR"><i></i><span><span></span><i></i>Memorize</span></a>'+'<a id="toolbar_email" class="btnR"><i></i><span><span></span><i></i>Email</span></a>'+'<a id="toolbar_link" class="btnR"><i></i><span><span></span><i></i>Link</span></a>'+'<a id="toolbar_tag" class="btnR"><i></i><span><span></span><i></i>Tag</span></a>'+'<a id="toolbar_embed" class="btnR green"><i></i><span><span></span><i></i>Embed</span></a>'+'<a id="toolbar_audio" class="btnR green"><i></i><span><span></span><i></i>Audio</span></a>'+'<a id="toolbar_select_bibles_open" class="btnR pink"><i></i><span><span></span><i></i>Bibles</span></a>'+'</div></div></div>'}).down('#eb-toolbar');this.actionbar=($('eb-action-bar'))?$('eb-action-bar'):$('eb-main-box').insert('<div id="eb-action-bar" class="action-bar"><div id="actionbar-head" class="action-bar-header"><div class ="head">Audio Player</div><div class="close">x</div><div class="close"></div></div><div id="actionbar-body" class="action-bar-body"></div></div>').down('#eb-action-bar');this.actionbar.hide();this.parallelMenu=($('eb-parallel-control'))?$('eb-parallel-control'):$('eb-main-box').insert({bottom:'<div id="eb-parallel-control" class="top-control" style="display:none;"><div id="select-bible-container"><div id="select_multiple_options" class="select_multiple_container"><div class="close" title="Close">x</div><div class="select_multiple_header">Bibles &amp; Commentaries (Select 1 to 4)</div><div id="parallel-control-table"></div><div class="select_multiple_submit"><input type="button" value="Create Study Bible" id="select_bibles_close"/> &nbsp; <input type="button" value="Cancel" id="select_bibles_cancel"/></div></div></div></div>'}).down('#eb-parallel-control');this.viewingTitle=($('eb-viewing'))?$('eb-viewing'):this.container.insert(new Element("span",{id:"eb-viewing"})).down('#eb-viewing');$('toolbar_select_bibles_open').observe('click',function(event){this.bibles=this.ebible_widget.options.availableBibles.split(',');this.comms=this.ebible_widget.options.availableComms.split(',');this.buildParallelMenu();if(!this.parallelMenu.visible()){this.parallelMenu.show();this._checkMaxSourcesSelected();}
this.ebible_widget.rangeLoaded();}.bind(this));$('actionbar-head').down(".close").observe('click',function(){this.actionbar.hide();}.bind(this));$$('.select_multiple_container')[0].down(".close").observe('click',function(){this.parallelMenu.hide();}.bind(this));$('toolbar_font_increase').observe('click',this._resizeText.bind(this,2));$('toolbar_font_decrease').observe('click',this._resizeText.bind(this,-2));$('toolbar_email').observe('click',this.emailAction.bindAsEventListener(this));$('toolbar_tag').observe('click',this.tagAction.bindAsEventListener(this));$('toolbar_link').observe('click',this.linkAction.bindAsEventListener(this));$('toolbar_memorize').observe('click',this.memorizeAction.bindAsEventListener(this));$('toolbar_embed').observe('click',this.embedAction.bindAsEventListener(this));$('toolbar_audio').observe('click',this.audioAction.bindAsEventListener(this));this.shortcut("Ctrl+Shift+M",function(){this.memorizeAction();}.bind(this),{'type':'keydown','propagate':true,'target':document});this.shortcut("Ctrl+Shift+A",function(){this.audioAction();}.bind(this),{'type':'keydown','propagate':true,'target':document});this.shortcut("Ctrl+Shift+L",function(){this.linkAction();}.bind(this),{'type':'keydown','propagate':true,'target':document});this.shortcut("Ctrl+Shift+T",function(){this.tagAction();}.bind(this),{'type':'keydown','propagate':true,'target':document});this.shortcut("Ctrl+Shift+S",function(){this.emailAction();}.bind(this),{'type':'keydown','propagate':true,'target':document});this.shortcut("Ctrl+Shift+E",function(){this.embedAction();}.bind(this),{'type':'keydown','propagate':true,'target':document})
this.shortcut("pageup",function(){this.ebible_widget.scrollToPrevStory();}.bind(this),{'type':'keydown','propagate':true,'target':document});this.shortcut("pagedown",function(){this.ebible_widget.scrollToNextStory();}.bind(this),{'type':'keydown','propagate':true,'target':document});this.shortcut("Shift+up",function(){this.ebible_widget.scrollToPrevStory();}.bind(this),{'type':'keydown','propagate':true,'target':document});this.shortcut("Shift+down",function(){this.ebible_widget.scrollToNextStory();}.bind(this),{'type':'keydown','propagate':true,'target':document});},audioAction:function(){this.user_action="play-audio";this._displayActionBar();if(pageTracker){pageTracker._trackEvent('audio','play');}},embedAction:function(){this.user_action="embed";this.embed=Object.extend({sources:this.ebible_widget.options.sources,width:430,height:300,textSize:10,showTitle:true,showTools:true,showPassage:true,passage:Bible.refnum2ref(this.ebible_widget.topLeftCell().id.split("_").last()),defaultText:this.embed?this.embed.defaultText:$F('txt-code').escapeHTML()});var fontOptions=new Array();$R(10,26).each(function(value){fontOptions.push([value,value]);});var fontSize=$('font-size');for(var i=0;i<fontOptions.length;i++){fontSize.options[i]=new Option(fontOptions[i][1],fontOptions[i][0]);}
var options=new Array();options.push(['NIV','New International Version']);options.push(['NKJV','New King James Version']);options.push(['MSG','The Message']);options.push(['NASB','New American Standard Bible']);options.push(['ESV','English Standard Version']);options.push(['HCSB','Holman Christian Standard Bible']);options.push(['NCV','New Century Version']);options.push(['KJV','King James Version']);options.push(['SpaRV','Spanish RV']);options.push(['ItalRV','Italian RV']);var tElement=$('translation');for(var i=0;i<options.length;i++){tElement.options[i]=new Option(options[i][1],options[i][0]);}
this.loadEmbedCode();RedBox.showInline('embed');RedBox.activateRBWindow();$('embed').down('#translation').value=this.embed.sources;$('embed').down('#passage').value=this.embed.passage;$('embed').down('#translation').observe('change',function(){this.embed.sources=$('embed').down('#translation').value;this.loadEmbedCode();}.bind(this));$('embed').down('#font-size').observe('change',function(){this.embed.textSize=$('embed').down('#font-size').value;this.loadEmbedCode();}.bind(this));$('embed').down('#show-title').observe('change',function(){this.embed.showTitle=$('embed').down('#show-title').checked;this.loadEmbedCode();}.bind(this));$('embed').down('#show-passage').observe('change',function(){this.embed.showPassage=$('embed').down('#show-passage').checked;this.loadEmbedCode();}.bind(this));$('embed').down('#passage').observe('keyup',function(){this.embed.passage=$('embed').down('#passage').value;this.loadEmbedCode();}.bind(this));$('embed').down('#height').observe('keyup',function(){this.embed.height=$('embed').down('#height').value;this.loadEmbedCode();}.bind(this));$('embed').down('#width').observe('keyup',function(){this.embed.width=$('embed').down('#width').value;this.loadEmbedCode();}.bind(this));$('embed').down('#txt-code').observe('focus',function(){javascript:this.select();});$('embed').down('#btn-link-cancel').observe('click',function(){RedBox.close();});$('embed').down('#close-link').observe('click',function(){RedBox.close();});},loadEmbedCode:function(){var html=[];html.push('&lt;script src="'+this.ebible_widget.options.domain+'/javascripts/prototype.js" type="text/javascript"&gt;&lt;/script&gt;');html.push('\n&lt;script src="'+this.ebible_widget.options.domain+'/javascripts/ebiblewidget.js" type="text/javascript"&gt;&lt;/script&gt;\n');html.push(this.embed.defaultText.toString());html.push('&lt;script type="text/javascript"&gt;');html.push('\neb = new eBible("ebible1", { ');html.push('\n\tvarName: "eb",');html.push('\n\tdomain: "'+this.ebible_widget.options.domain+'",');html.push('\n\tstudyBible:"'+this.embed.sources+'",');html.push('\n\tshowTitle: '+this.embed.showTitle+',');html.push('\n\tfontSize:"'+this.embed.textSize+'",');html.push('\n\twidth: '+this.embed.width+',');html.push('\n\theight: '+this.embed.height+',');html.push('\n\tpassage:"'+this.embed.passage+'"');html.push('\n});');html.push('\n&lt;/script&gt;');if(this.embed.showPassage){html.push('\n&lt;script src="'+this.ebible_widget.options.domain+'/javascripts/widgetcontrol.js" type="text/javascript"&gt;&lt;/script&gt;');}
$('embed').down('#txt-code').update(html.join(" "));},tagAction:function(){this.user_action="tag";if(this.ebible_widget.selectedList.getSelected().length<1){this._displayUserMessage(this.user_action);}
else{RedBox.showInline('tag-wrapper');RedBox.activateRBWindow();this.passage_collection=[];this.ebible_widget.selectedList.getSelected().each(function(ele){this.passage_collection.push(ele.ref);}.bind(this));new Ajax.Updater('tag-wrapper',"/tagged_passages/tag",{method:'get',parameters:"passages="+this.passage_collection,onComplete:function(){if(!current_user){$('signin_link').observe('click',function(){showSignInForm();});}
$$('.user_tags_for_passage').each(function(ele){new Ajax.Autocompleter(ele.id,"tagging_autocomplete_choices","/tagged_passages/tag_suggestion",{method:'GET',minChars:3,indicator:'indicator2',tokens:[',']});$('btn-cancel-tagging').observe('click',function(){RedBox.close();});});}});}},emailAction:function(){if(this.ebible_widget.selectedRows().length<1){this.user_action="email";this._displayUserMessage(this.user_action);}
else{RedBox.showInline('action-email-toolbar');RedBox.activateRBWindow();$('action-email-toolbar').down('.close').observe("click",function(){RedBox.close();});$('action-email-toolbar').down('#btn-email-cancel').observe('click',function(){RedBox.close();});$('action-email-toolbar').down('#sender_name').defaultValueActsAsHint();$('action-email-toolbar').down('#sender_email_address').defaultValueActsAsHint();$('action-email-toolbar').down('#receiver_email_address').defaultValueActsAsHint();var verse_to_email=[];var url_row=[];this.ebible_widget.selectedList.getSelected().each(function(list){url_row.push("<div class='url_row'>"+list.ref+"</div>");verse_to_email.push(list.ref);});var html_options="<select id ='translation' class='dropdown'>";var sources=this.ebible_widget.options.availableBibles.split(",");sources.each(function(src){if(this.bibles.include(src)){html_options+="<option value='"+src+"'>"+src+"</option>";}}.bind(this));html_options+="</select>";$('action-email-toolbar').down('#bible-translation').update(html_options);var bible_source=$('translation').value;Event.observe("translation","change",function(){bible_source=$('translation').value;});$('action-email-toolbar').down('#verse-list').update(url_row.join(""));$('action-email-toolbar').down('#btn-email').observe('click',function(){if($('action-email-toolbar').down('#sender_name').value=="Your name"){$('action-email-toolbar').down('#sender_name').setStyle({border:"1px solid red"});alert("Please provide your name");}
else if($('action-email-toolbar').down('#sender_email_address').value=="Your email"||!validateEmailIds($('action-email-toolbar').down('#sender_email_address').value,",")){$('action-email-toolbar').down('#sender_email_address').setStyle({border:"1px solid red"});alert("Please provide your valid email address");}
else if($('action-email-toolbar').down('#receiver_email_address').value=="Your friend's email (comma for multiple)"||!validateEmailIds($('action-email-toolbar').down('#receiver_email_address').value,",")){$('action-email-toolbar').down('#receiver_email_address').setStyle({border:"1px solid red"});alert("Please provide recipient's valid email address");}
else{var sender_name=$('action-email-toolbar').down('#sender_name').value;var sender_email=$('action-email-toolbar').down('#sender_email_address').value;var personal_message=$('action-email-toolbar').down('#personal-email-message').value;var recipients=($('action-email-toolbar').down('#receiver_email_address').value.split(","));var sender=sender_name+','+sender_email;Element.show($('action-email-toolbar').down('#save-verse-waiting'));var url=this.ebible_widget.options.domain+"/emailers/sendmail.json?callback="+this.ebible_widget.options.varName+".toolbar._emailsend_confirmed&data="+verse_to_email+"&sender="+sender+"&recipients="+recipients+"&bible="+bible_source+"&msg="+personal_message;var transactionObj=YAHOO.util.Get.script(url,{onSuccess:function(o){this.waitingForCallback=false;},onFailure:function(o){alert('Sorry, there was a problem contacting the server. Please try again or contact support@ebible.com');},scope:this});}}.bind(this));}},linkAction:function(){if(this.ebible_widget.selectedRows().length<1){this.user_action="link";this._displayUserMessage(this.user_action);}else{var url_row=[];this.ebible_widget.selectedList.getSelected().each(function(list){url_row.push("<div class='url_row'><input type='text' value='http://www.ebible.com/#"+list.ref+"'/></div>");});$('link-body').update(url_row.join(""));RedBox.showInline('action-link-toolbar');RedBox.activateRBWindow();$('action-link-toolbar').down('#link-body').select('.url_row input').each(function(txtbox){txtbox.observe('focus',function(){txtbox.setStyle({backgroundColor:'#f1f1f1'});javascript:this.select();});});$('action-link-toolbar').down('#link-body').select('.url_row input').each(function(txtbox){txtbox.observe('blur',function(){txtbox.setStyle({backgroundColor:'#ffffff'});});});$('btn-link-cancel').observe('click',function(){RedBox.close();});$('action-link-toolbar').down('#close-link').observe('click',function(){RedBox.close();});if(pageTracker){pageTracker._trackEvent('link','show','',url_row.length);}}},memorizeAction:function(from){if(from=='playlist'){if(this.ebible_widget.playlist.selectedRef.length<1){this.user_action="memorize";this._displayUserMessage(this.user_action);}
else{RedBox.showInline('memorize-tool');RedBox.activateRBWindow();this.memorize=new Memorize(this.ebible_widget);if(pageTracker){pageTracker._trackEvent('memorize','play');}}}
else{if(this.ebible_widget.selectedRows().length<1){this.user_action="memorize";this._displayUserMessage(this.user_action);}
else{RedBox.showInline('memorize-tool');RedBox.activateRBWindow();this.ebible_widget.playlist.memorizing=false;this.memorize=new Memorize(this.ebible_widget);if(pageTracker){pageTracker._trackEvent('memorize','play');}}}},buildParallelMenu:function(){$('select_bibles_close').stopObserving();var rows=Math.max(this.bibles.length,this.comms.length);$('eb-parallel-control').setStyle({'top':'35px','left':($('toolbar_select_bibles_open').cumulativeOffset().first()-$('eb-bible').cumulativeOffset().first())+'px'});var temp=[];var count;for(var i=0;i<rows;i++){var td="";if(this.ebible_widget.options.sources.split(",").include(this.bibles[i])){count=this.ebible_widget.columnHeaders().length;if(count==1){td='<td class="select_multiple_name">'+this.bibles[i]+'</td><td class="select_multiple_bible_checkbox"><input type="checkbox" checked ="true" disabled="true" value="'+this.bibles[i]+'"/></td>';$('select_bibles_close').stopObserving();}
else{td='<td class="select_multiple_name">'+this.bibles[i]+'</td><td class="select_multiple_bible_checkbox"><input type="checkbox" checked ="true" value="'+this.bibles[i]+'"/></td>';}}else{if(i>=this.bibles.length){td='<td colspan="2">&nbsp;</td>';}else{td='<td class="select_multiple_name">'+this.bibles[i]+'</td><td class="select_multiple_bible_checkbox"><input type="checkbox"  value="'+this.bibles[i]+'"/></td>';}}
if(this.ebible_widget.options.sources.split(",").include(this.comms[i])){count=this.ebible_widget.columnHeaders().length;if(count==1){td=td+'<td class="select_multiple_name">'+this.comms[i]+'</td><td class="select_multiple_commentary_checkbox"><input type="checkbox" checked ="true" disabled="true" value="'+this.comms[i]+'"/></td>';$('select_bibles_close').stopObserving();}
else{td=td+'<td class="select_multiple_name">'+this.comms[i]+'</td><td class="select_multiple_commentary_checkbox"><input type="checkbox" checked ="true" value="'+this.comms[i]+'"/></td>';}}
else{if(i>=this.comms.length){td=td+'<td colspan="2">&nbsp;</td>';}
else{td=td+'<td class="select_multiple_name">'+this.comms[i]+'</td><td class="select_multiple_commentary_checkbox"><input type="checkbox"  value="'+this.comms[i]+'"/></td>';}}
temp.push('<tr class="row_class">'+td+'</tr>');}
var start_table='<table id="select-bible-table" cellspacing="0" cellpadding="0" class="select_multiple_table" width="100%"><tr><th colspan="2" style="background-color:#777;color:#fff;">Bibles</th><th colspan="2" style="background-color:#777;color:#fff;">Commentaries</th>';var end_table='</tr></table>';$('parallel-control-table').update(start_table+temp.join("")+end_table);this.bibles_commentaries=$$('#eb-parallel-control input[type=checkbox]');this.bibles_commentaries.each(function(checkbox){checkbox.observe('click',function(){var flag=checkbox.checked;this._createColumnSkeleton(checkbox);if(flag){checkbox.writeAttribute('checked','true');}else{checkbox.writeAttribute('checked','false');}
this.ebible_widget._adjustColumns();this.ebible_widget.alignRows();this.ebible_widget.scrollToCell(this.ebible_widget.cell_in_view.id);this.ebible_widget._buildColumnBibleChoosers();}.bindAsEventListener(this));}.bindAsEventListener(this));$('select_bibles_cancel').observe('click',function(event){var columns=this.ebible_widget.columns();columns.each(function(col){if(col.childElements().length<1){$('select_multiple_options').select('input[value='+col.id.gsub('_column','')+']')[0].checked=false;this.ebible_widget.removeColumn(col.id.gsub('_column',''));}}.bindAsEventListener(this));this.parallelMenu.hide();this.ebible_widget.alignRows();this.ebible_widget.scrollToCell(this.ebible_widget.cell_in_view.id);}.bindAsEventListener(this));$('select_bibles_close').observe('click',function(event){var allow=this._checkNewColumns();if(allow){var new_sources=[];var loading_element=[];this.ebible_widget.columns().each(function(col){if(col.childElements().length<1){new_sources.push(col.id.gsub('_column',''));loading_element.push(col.id);}});var range=this.ebible_widget.rangeLoaded();var topleft_refnum=this.ebible_widget.cell_in_view.to_refnum();this.ebible_widget._remote("addColumns",loading_element.join(","),$('eb-viewing').innerHTML.split(':')[0],{query:this.ebible_widget.options.passage,sources:new_sources.join(","),first:range[0],last:range[1],from_scratch:0,topleft_refnum:topleft_refnum});this.parallelMenu.hide();this.ebible_widget._adjustColumns();}else{this.parallelMenu.hide();}
if(pageTracker){pageTracker._trackEvent('studybible','change',new_sources.sort().join(","));}
Event.stop(event);return false;}.bindAsEventListener(this));},enableActions:function(){$('toolbar_memorize').addClassName("blue");$('toolbar_email').addClassName("blue");$('toolbar_link').addClassName("blue");$('toolbar_tag').addClassName("blue");},disableActions:function(){$('toolbar_memorize').removeClassName("blue");$('toolbar_email').removeClassName("blue");$('toolbar_link').removeClassName("blue");$('toolbar_tag').removeClassName("blue");},updateParallelMenu:function(){this.bibles_commentaries.each(function(checkbox){checkbox.checked=(this.ebible_widget.options.sources.split(',').include(checkbox.value));}.bind(this));},_emailsend_confirmed:function(json){var message=[];message.push("<div class='note'>Thank You.</div><div class='note'>Your message has been sent to following recepients.</div>");json.each(function(receipt){message.push("<span class='email-id'>"+receipt+",</span>");});$$('.main-body')[0].update(message.join(""));if(pageTracker){pageTracker._trackEvent('email','sent','verses',json.length);}},_createColumnSkeleton:function(checkbox){this._checkMaxSourcesSelected();if(checkbox.checked){if(this.ebible_widget.columnHeaders(true).length==1){$$('#eb-parallel-control input[value='+this.ebible_widget.columnHeaders(true)[0]+']')[0].disabled=true;}
this.ebible_widget.addColumn(checkbox.value,checkbox.value,'','',1);}else{if(this.ebible_widget.columnHeaders(true).length==1){$$('#eb-parallel-control input[value='+this.ebible_widget.columnHeaders(true)[0]+']')[0].disabled=true;}
this.ebible_widget.removeColumn(checkbox.value);this.ebible_widget.alignRows();}},_checkMaxSourcesSelected:function(){var source_count=0;this.bibles_commentaries.each(function(checkbox){if(checkbox.checked){source_count+=1;}});if(source_count==1){this.bibles_commentaries.each(function(checkbox){if(checkbox.checked){checkbox.disabled=true;}});}
if((source_count>1)&&(source_count<this.MAX_SOURCES)){this.bibles_commentaries.each(function(checkbox){if(checkbox.disabled){checkbox.disabled=false;}});}
if(source_count>=this.MAX_SOURCES){this.bibles_commentaries.each(function(checkbox){if(!(checkbox.checked)){checkbox.disabled=true;}});}},_checkNewColumns:function(){var checkedTranslation=$$('#eb-parallel-control input[checked=true]').collect(function(checkbox){return checkbox.value;}).sort();var currentHeaders=this.ebible_widget.columnHeaders().sort();var flag=null;if(checkedTranslation.sort().join("")!=currentHeaders.sort().join("")){flag=true;}
else{checkedTranslation.each(function(trans){if($(trans+"_column").childElements().length<1){flag=true;throw $break;}
else{flag=false;}});}
return flag;},_displayUserMessage:function(action){var message;if(action=='link'||action=='email'||action=='tag'){message="<p class='message'>Please select a verse to "+action+" and click me.</p>";this.actionbar.childElements()[1].update(message);if(action=="link"){$('eb-action-bar').childElements()[0].childElements()[0].update("URL to Reference");}
else if(action=='email'){$('eb-action-bar').childElements()[0].childElements()[0].update("Email to Friends");}
else{$('eb-action-bar').childElements()[0].childElements()[0].update("Tag Passage/Verses");}}else if(action=="play-audio"){message="<p class='message'>Please sign in or sign up to listen.</p>";this.actionbar.childElements()[1].update(message);$('eb-action-bar').childElements()[0].childElements()[0].update("Play this chapter");}else if(action=="memorize"){message="<p class='message'>Please select a verse to "+action+" and click me.</p>";$('eb-action-bar').childElements()[0].childElements()[0].update("Memorize Bible");this.actionbar.childElements()[1].update(message);}
this.actionbar.setStyle({'opacity':'1.0'});this.actionbar.show();window.setTimeout(function(){$('eb-action-bar').fade({duration:1.0,from:1,to:0});}.bind(this),1000);},_displayActionBar:function(){if(this.user_action=="play-audio"){var chapter=$('eb-viewing').innerHTML.split(':')[0];var topLeft=this.ebible_widget.cell_in_view;if(!topLeft){$(this.actionbar.childElements()[1]).update("Sorry there was a problem. Please report this error and your browser to bugs@ebible.com");this.actionbar.setStyle({'opacity':'1.0'});this.actionbar.show();window.setTimeout(function(){$('eb-action-bar').fade({duration:2.0,from:1,to:0});},1000);return;}
if(topLeft.to_ordinal()<23146){$(this.actionbar.childElements()[1]).update("Sorry no audio file for Old Testament Books.<br />Please load New Testament books");this.actionbar.setStyle({'opacity':'1.0'});this.actionbar.show();window.setTimeout(function(){$('eb-action-bar').fade({duration:2.0,from:1,to:0});},1000);return;}
var audio_file;if(!current_user){this._displayUserMessage(this.user_action);}
else{if(this.viewingTitle.innerHTML!=""){parseInt(this.ebible_widget.cell_in_view.id.split('_')[2].substring(2,5),10);audio_file=parseInt(this.ebible_widget.cell_in_view.id.split('_')[2].substring(0,2),10).toString()+"-"+parseInt(this.ebible_widget.cell_in_view.id.split('_')[2].substring(2,5),10).toString()+".mp3";}
var current_chapter=$('eb-viewing').innerHTML.split(':')[0];var winContent="";var quality=current_user.membership_level_id>=10?"1q2w3e4r":"low";winContent+="<img src='/images/player_top_logo.jpg'/>";winContent+='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" height="24" width="250" id="audioplayer1"><param name="movie" value="/twop/player.swf?src=http://www.ebible.com" />';winContent+='<param name="audio" value="http://www.ebible.com/twop/player.swf">';winContent+='<param name="FlashVars" value="playerID=1&amp;soundFile=http://www.ebible.com/twop/'+quality+"/"+audio_file+'">';winContent+='<param name="quality" value="high">';winContent+='<param name="menu" value="false">';winContent+='<param name="wmode" value="transparent">';winContent+='<object type="application/x-shockwave-flash" data="http://www.ebible.com/twop/player.swf" width="250" height="24" id="audioplayer1">';winContent+='<param name="audio" value="http://www.ebible.com/twop/player.swf" />';winContent+='<param name="FlashVars" value="playerID=1&amp;soundFile=http://www.ebible.com/twop/'+quality+"/"+audio_file+'">';winContent+='</object>';winContent+='</object>';winContent+="<p style='text-align: center;'><a id='nkjv-audio-jump-link' class='blank-a' style='text-align : center;'>Read along with NKJV's "+current_chapter+" </a></p>";if(current_user.membership_level_id<10){winContent+="<p>Premium members get high quality audio plus other exclusive features</p>";winContent+="<a id='upgrade_now' style='padding-left: 30%;'><img src='/images/btn_upgradeNow.gif'/></a>";}
else if(current_user.membership_level_id==10){winContent+="<p style='text-align: center;'>You are already a premium member, but check out our <a href='#settings'>lifetime membership promotion!</a><p>";}
else if(current_user.membership_level_id>10){winContent+="<p style='text-align: center;'>You are already a lifetime member.<br />Please feel free to send your feedback at <a href='http://support@ebible.com'>support@ebible.com.</a> <p>";}
winContent+="<p style='text-align:center'><a href='http://www.thewordofpromise.com/'>Order The Word of Promise products here</a></p>";this.actionbar.childElements()[0].childElements()[0].update("Audio Player : "+current_chapter+" <span style='font-size:12px'>"+(quality=="1q2w3e4r"?"High":"Low")+" quality </span><span id ='audio_min' title='minimize'>--</span><span id='audio_max' style='display:none' title='maximize'>+</span>");this.actionbar.childElements()[1].update(winContent);$('audio_max').observe('click',function(){$('actionbar-body').childElements().each(function(ele){if(ele.id=='audioplayer1'){ele.setStyle({'height':'20px','width':'250px'});}
else{ele.show();}});$('actionbar-body').setStyle({'padding':'10px'});$$('.action-bar-body')[0].setStyle({'fontSize':'1.2em'});$('audio_max').hide();$('audio_min').show();});$('audio_min').observe('click',function(){$('actionbar-body').childElements().each(function(ele){if(ele.id=='audioplayer1'){ele.setStyle({'height':'0px','width':'0px'});}
else{ele.hide();}});$('actionbar-body').setStyle({'padding':'0'});$$('.action-bar-body')[0].setStyle({'fontSize':'0'});$('audio_min').hide();$('audio_max').show();});$('nkjv-audio-jump-link').observe('click',function(){if(this.ebible_widget.columnHeaders().include("NKJV")){this.ebible_widget.columnHeaders().each(function(header){if(header!="NKJV"){this.ebible_widget.removeColumn(header);this.ebible_widget._adjustColumns();this.ebible_widget.alignRows();}}.bind(this));}else{for(i=1;i<this.ebible_widget.columnHeaders().length;i++){this.ebible_widget.removeColumn(this.ebible_widget.columnHeaders()[i]);}
var chooser=$$('div.column-chooser')[0];var old_source=chooser.up('div.row-header').id.split('_')[0];var topleft_refnum=this.ebible_widget.cell_in_view.to_refnum();var range=this.ebible_widget.rangeLoaded();this.ebible_widget._remote("updateColumn",chooser.up('div.row-header').id,'NKJV',{old_source:old_source,new_source:'NKJV',topleft_refnum:topleft_refnum,first:range[0],last:range[1]});}}.bindAsEventListener(this));this.actionbar.setStyle({'opacity':'1.0'});this.actionbar.show();if($('upgrade_now')){$('upgrade_now').observe('click',function(){document.location.href="#settings";});}}}},_resizeText:function(manipulator){var contentBox=$('eb-bible-table');var size=new RegExp(/(\d+[\.]*\d+)[\s]*\w+[\W]*/).exec(contentBox.getStyle('fontSize'));textsize=(parseInt(size)+manipulator);if(textsize>=10&&textsize<=26){contentBox.setStyle({fontSize:textsize+'px'});this.ebible_widget.alignRows();}},shortcut:function(shortcut,callback,opt){var default_options={'type':'keydown','propagate':false,'target':document}
if(!opt)opt=default_options;else{for(var dfo in default_options){if(typeof opt[dfo]=='undefined')opt[dfo]=default_options[dfo];}}
var ele=opt.target
if(typeof opt.target=='string')ele=document.getElementById(opt.target);var ths=this;var func=function(e){e=e||window.event;if(e.keyCode)code=e.keyCode;else if(e.which)code=e.which;var character=String.fromCharCode(code).toLowerCase();var keys=shortcut.toLowerCase().split("+");var kp=0;var shift_nums={"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"}
var special_keys={'esc':27,'escape':27,'tab':9,'space':32,'return':13,'enter':13,'backspace':8,'scrolllock':145,'scroll_lock':145,'scroll':145,'capslock':20,'caps_lock':20,'caps':20,'numlock':144,'num_lock':144,'num':144,'pause':19,'break':19,'decrease':45,'increase':43,'home':36,'delete':46,'end':35,'pageup':33,'page_up':33,'pu':33,'pagedown':34,'page_down':34,'pd':34,'left':37,'up':38,'right':39,'down':40,'f1':112,'f2':113,'f3':114,'f4':115,'f5':116,'f6':117,'f7':118,'f8':119,'f9':120,'f10':121,'f11':122,'f12':123}
for(var i=0;k=keys[i],i<keys.length;i++){if(k=='ctrl'||k=='control'){if(e.ctrlKey)kp++;}else if(k=='shift'){if(e.shiftKey)kp++;}else if(k=='alt'){if(e.altKey)kp++;}else if(k.length>1){if(special_keys[k]==code)kp++;}else{if(character==k)kp++;else{if(shift_nums[character]&&e.shiftKey){character=shift_nums[character];if(character==k)kp++;}}}}
if(kp==keys.length){callback(e);if(!opt['propagate']){e.cancelBubble=true;e.returnValue=false;if(e.stopPropagation){e.stopPropagation();e.preventDefault();}
return false;}}}
if(ele.addEventListener)ele.addEventListener(opt['type'],func,false);else if(ele.attachEvent)ele.attachEvent('on'+opt['type'],func);else ele['on'+opt['type']]=func;}});var Screen=0;var Memorize=Class.create({testing_text:"",position:0,total_words:0,words:[],filteredWords:[],cheats:0,mistakes:0,passage_text:null,selected_verses:null,INTRO_SCREEN:0,TEST_SCREEN:1,SCORE_SCREEN:2,ebible_widget:null,memorizing_title:null,initialize:function(widget){this.ebible_widget=widget;if(eb.playlist.memorizing==false){this.selected_verses=eb.selectedList.getSelected();}else{this.selected_verses=this.ebible_widget.playlist.selectedRef;}
if(current_user!=null)
if(current_user.membership_level_id>=10){$('memorize-tool').down('#memorize-first').show();$('memorize-tool').down('#memorize-second').hide();$('memorize-tool').down('#memorize-third').hide();$('memorize-tool').down('#memorize-fourth').hide();this.displaySelectedList();}
Event.observe(parent.document,'keypress',this.keypressed.bindAsEventListener(this));},displaySelectedList:function(){$('memorize-tool').down('#mem-bible-translation').update(eb.createBibleTranslationOptions());var array_list=[];this.selected_verses.each(function(list){array_list.push("<span class='memorize-list-item'>"+list.ref+"</span>");});$('memorize-tool').down('#memorize-selected-list').update(array_list.join(""));$('memorize-tool').select('.memorize-list-item').each(function(list){list.observe('click',function(){this.getMemorizeContent(list.innerHTML);}.bindAsEventListener(this));}.bind(this));$('memorize-tool').down('.close').observe('click',function(){this.destroy();RedBox.close();}.bind(this));},passageTextReceived:function(json_text,verse_ref){if(verse_ref){this.memorizing_title=verse_ref;}
this.passage_text=json_text.toString();this.words=$w(this.passage_text);this.filteredWords=$w(this.passage_text.unescapeHTML().gsub(/[^A-Za-z\.\,\-\—]/,' '));this.total_words=this.words.size();this.introduction();},getMemorizeContent:function(text){var bible_translation=$('memorize-tool').down('#bible-translation').value;this.memorizing_title=text;var url=eb.options.domain+"/browser/getPassageText?callback="+this.ebible_widget.options.varName+".toolbar.memorize.passageTextReceived&translation="+bible_translation+"&passage="+this.memorizing_title;var transactionObj=YAHOO.util.Get.script(url,{onSuccess:function(o){this.waitingForCallback=false;},onFailure:function(o){alert('Sorry, there was a problem contacting the server. Please try again or contact support@ebible.com');},scope:this});},introduction:function(){Screen=this.INTRO_SCREEN;$('score-panel').hide();this.testing_text="";var i;for(i=0;i<this.words.length;i++){this.testing_text+="<span id='m"+i+"'>"+this.words[i]+"</span> ";}
$('memorize-tool').down('#memorize-text-area').update(this.testing_text);$('memorize-tool').down('#mistake-made').hide();var buttonbar=[];buttonbar.push("<span id='memorize-verse-start' class='btn'>START</span>");buttonbar.push("<span id='memorize-verse-tryanother' class='btn'>Try Another</span>");buttonbar.push("<span id='memorize-verse-close' class='btn'>Close</span>");$('memorize-tool').down('#button-bar').update(buttonbar.join(""));$('memorize-tool').down('#memorize-verse-tryanother').observe('click',function(){this.position=0;$('memorize-tool').down('#memorize-first').show();$('memorize-tool').down('#memorize-second').hide();$('memorize-tool').down('#memorize-third').hide();$('memorize-tool').down('#memorize-fourth').hide();this.displaySelectedList();}.bindAsEventListener(this));$('memorize-tool').down('#memorize-verse-close').observe('click',function(){this.position=0;this.cleanup();$('memorize-tool').down('#memorize-selected-list').select('.memorize-list-item').each(function(list){list.stopObserving('click');});if($$('li.selected').first()){$$('li.selected').first().removeClassName("selected");}
eb.playlist.memorizing=false;RedBox.close();}.bindAsEventListener(this));$('memorize-tool').down('#memorize-verse-start').observe('click',this.start.bind(this));$('memorize-tool').down('#memorize-first').hide();$('memorize-tool').down('#memorize-second').show();$('memorize-tool').down('#memorize-third').hide();$('memorize-tool').down('#memorize-fourth').show();$('memorize-tool').down('#memorize-title').update("Memorizing: "+this.memorizing_title);$('memorize-tool').down('#instruction').update("Take a close look");Timer.reset();},start:function(){cheats=0;mistakes=0;position=0;$('memorize-tool').down('#instruction').innerHTML="Get ready...";var i;for(i=0;i<this.words.length;i++){Effect.Shrink($('m'+i),{delay:i*0.03});}
var buttonbar=[];buttonbar.push("<div id='memorize-verse-cheat' class='btn' title='Use SPACE key'>Get Hint</div>");buttonbar.push("<div id='memorize-verse-giveup' class='btn' title='Use Q key'>Give Up</div>");buttonbar.push("<div id='memorize-timer'></div>");$('memorize-tool').down('#button-bar').update(buttonbar.join(""));$('memorize-tool').down('#memorize-verse-giveup').observe('click',this.giveup.bind(this));$('memorize-tool').down('#memorize-verse-cheat').observe('click',this.cheat.bind(this));setTimeout(function(){$('memorize-tool').down('#instruction').innerHTML="Type the FIRST LETTER of each word in the passage.";Timer.start();Screen=this.TEST_SCREEN;},1000+this.words.length*30);},cheat:function(){if(this.position<this.words.length){Element.show($('m'+this.position));new Effect.Highlight($('m'+this.position),{startcolor:'#ff9999'});}
this.position+=1;this.cheats+=1;this.mistakes+=1;if(this.position==this.total_words)
setTimeout(function(){this.complete();}.bind(this),1000);},giveup:function(){this.position=0;Timer.stop();this.introduction();},keypressed:function(e){var code;if(!e)var e=window.event;if(e.keyCode)code=e.keyCode;else if(e.which)code=e.which;var character=String.fromCharCode(code).toLowerCase();if(Screen==this.INTRO_SCREEN){return false;}else if(Screen==this.SCORE_SCREEN){}
switch(code){case Event.KEY_SPACE:this.cheat();return true;}
if(character.charAt(0)==this.filteredWords[this.position].toLowerCase().charAt(0)){Element.show($('m'+this.position));new Effect.Highlight($('m'+this.position));if(this.position==(this.total_words-1)){this.complete();}else{this.position+=1;}
return true;}else{this.mistakes+=1;$('memorize-tool').down('#mistake-made').innerHTML="<img border='0' width='30' src='/images/oops.jpg' alt='Oops'/>";$('memorize-tool').down('#mistake-made').show();setTimeout(function(){$('memorize-tool').down('#mistake-made').innerHTML=this.mistakes;}.bind(this),500);}},complete:function(){var timeScore;var mistakeScore;var cheatScore;Timer.stop();Screen=this.SCORE_SCREEN;$('memorize-tool').down('#memorize-first').hide();$('memorize-tool').down('#memorize-second').hide();$('memorize-tool').down('#memorize-third').show();var buttonbar=[];buttonbar.push("<span id='memorize-verse-tryagain' class='btn'>Try Again</span>");buttonbar.push("<span id='memorize-verse-tryanother' class='btn'>Try Another</span>");$('memorize-tool').down('#button-bar').update(buttonbar.join(""));$('memorize-tool').down('#memorize-verse-tryagain').observe('click',function(){this.position=0;$('memorize-tool').down('#memorize-first').hide();$('memorize-tool').down('#memorize-second').show();$('memorize-tool').down('#memorize-third').hide();$('memorize-tool').down('#memorize-fourth').show();this.introduction();}.bindAsEventListener(this));$('memorize-tool').down('#memorize-verse-tryanother').observe('click',function(){this.position=0;$('memorize-tool').down('#memorize-first').show();$('memorize-tool').down('#memorize-second').hide();$('memorize-tool').down('#memorize-third').hide();$('memorize-tool').down('#memorize-fourth').hide();this.displaySelectedList();}.bindAsEventListener(this));timeScore=Math.floor((1.5-(TotalSeconds/this.total_words))*10);timeScore=Math.min(timeScore,10);timeScore=Math.max(timeScore,0);mistakeScore=Math.max((Math.floor(10-this.mistakes/this.total_words*20)),0);cheatScore=Math.max((Math.floor(10-this.cheats/this.total_words*40)),0);scoreTable="<div class='memo-title'>Memorizing: "+this.memorizing_title+"</div>";scoreTable+="<div class='result-row message'>"+this.displaySuccessMessage(this.mistakes,this.total_words)+"</div>";scoreTable+="<div class='result-alt-row'><span class='col'>Time</span><span class='col'>"+((TotalMinutes>=1)?TotalMinutes+"min ":"")+TotalSeconds+" sec</span><span class='col'>"+timeScore+"/10</span></div>";scoreTable+="<div class='result-row'><span class='col'>Stumbles</span><span class='col'>"+this.mistakes+"</span><span class='col'>"+mistakeScore+"/10</span></div>";scoreTable+="<div class='result-alt-row'><span class='col'>Cheats</span><span class='col'>"+this.cheats+"</span><span class='col'>"+cheatScore+"/10</span></div>";scoreTable+="<div class='result-row'><span class='col'>Overall</span><span class='col'></span><span class='col'>"+(timeScore+mistakeScore+cheatScore)+"/30</span></div>";$('memorize-tool').down('#score-table').innerHTML=scoreTable;$('memorize-tool').down('#score-panel').show();this.mistakes=0;this.cheats=0;},cleanup:function(){Timer.stop();Event.stopObserving(document,'keypress',this.keypressed.bindAsEventListener(this));if($('memorize-tool').down('#errors-for-lightbox')){Element.hide($('errors-for-lightbox'));};RedBox.close();return false;},displaySuccessMessage:function(mistakes,totalwords){var message="";var mistakePercentage,cheatPercentage;mistakePercentage=(mistakes/totalwords);cheatPercentage=(cheats/totalwords);if(mistakePercentage>=1.0)
message="You have a poor memorization. Were you thinking the wrong verse?";else if(mistakePercentage>=0.90)
message="You have Poor Memorization.";else if(mistakePercentage>=0.75)
message="You have bad memorization."
else if(mistakePercentage>=0.50)
message="You have average Memorization.";else if(mistakePercentage>=0.25)
message="You have good memorization. You can do a lot better."
else if(mistakePercentage>0.10)
message="You are in better memorization. Keep trying to nail it."
else
message="Thats perfect. You nailed it";return message;},destroy:function(){Timer.stop();Event.stopObserving(parent.document,'keypress');}});var TotalTime;var TotalSeconds=0;var TotalMinutes=0;Timer={timerID:0,tStart:null,update:function(){TotalSeconds=parseInt(TotalSeconds)+1;if(TotalSeconds<10){}
else if(TotalSeconds>59){TotalSeconds-=60;TotalMinutes+=1;if(TotalMinutes<10)
TotalMinutes=TotalMinutes;}
if(TotalMinutes<10)
TotalTime="0"+TotalMinutes;else
TotalTime=TotalMinutes;if(TotalSeconds<10)
TotalTime+=":"+"0"+TotalSeconds;else
TotalTime+=":"+TotalSeconds;if($('memorize-tool').down('#memorize-timer')!=null)
$('memorize-tool').down('#memorize-timer').innerHTML=TotalTime;timerID=setTimeout(function(){Timer.update();},1000);},start:function(){TotalSeconds=0;TotalMinutes=0;tStart=new Date();$('memorize-tool').down('#memorize-timer').innerHTML="00:00";timerID=setTimeout(function(){Timer.update();},1000);},stop:function(){if(typeof(timerID)!="undefined"&&timerID){clearTimeout(timerID);timerID=0;}
tStart=null;},getTime:function(){return this.time;},reset:function(){tStart=null;timerID=0;}}
var VerseChooser=Class.create();VerseChooser.prototype={initialize:function(element,goFunction){this.container=$(element);this.goFunction=goFunction;},showChooser:function(e){this.vc_dom=document.createElement("div");this.book_chooser_dom=this.createBookChooser();this.vc_dom.appendChild(this.book_chooser_dom);this.dom_element=this.vc_dom;var posx=$('vc').cumulativeOffset().first();var posy=$('vc').cumulativeOffset().last();this.vc_dom.style.top=posy+'px';this.vc_dom.style.left=posx+'px';this.vc_dom.style.position='absolute';this.container.appendChild(this.dom_element);},onClick:function(e){Event.stop(e);return(false);},onBookChooserClick:function(e){e=Event.element(e);if(e.tagName&&e.tagName!="TD"){e.up('td');}
if(e&&e.id){this.chosenBook=parseInt(e.id);if(e.id==''){return;}
else
{this.chapter_chooser_dom=this.createChapterChooser();this.vc_dom.replaceChild(this.chapter_chooser_dom,this.book_chooser_dom);}}},onChapterChooserClick:function(e){e=Event.element(e);if(e.tagName!="TD"){e.up('td');}
if(e){this.chosenChapter=parseInt(e.id);this.verse_chooser_dom=this.createVerseChooser(e);this.vc_dom.replaceChild(this.verse_chooser_dom,this.chapter_chooser_dom);}},onVerseChooserClick:function(e){e=Event.element(e);if(e.tagName!="TD"){e.up('td');}
if(e){this.chosenVerse=parseInt(e.id);verseRef=Bible.SHORTNAMES[this.chosenBook]+" "+(this.chosenChapter+1)+":"+(this.chosenVerse+1);this.goFunction(verseRef);this.dom_element.parentNode.removeChild(this.dom_element);}},onCloseButtonClick:function(e){this.dom_element.parentNode.removeChild(this.dom_element);return(false);},isVisible:function(){return(this.dom_element.parentNode?true:false);},createBookChooser:function(){var title="Choose a Book";var handler;var me=this;var table_dom=this.makeBookTable();table_dom.className="verse_chooser_body";handler=function(e){return(me.onClick(e));}
Event.observe(this.vc_dom,"click",handler,false);handler=function(e){return(me.onBookChooserClick(e));}
Event.observe(table_dom,"click",handler,false);handler=function(e){return(me.onCloseButtonClick(e));}
book_chooser_dom=this.createChooser(title,table_dom,handler);return(book_chooser_dom);},createChapterChooser:function(){var title="Choose a Chapter";var handler;var me=this;var table_dom=this.makeChapterTable();table_dom.className="verse_chooser_body";table_dom.border="0";table_dom.cellSpacing="1";table_dom.cellPadding="0";handler=function(e){return(me.onClick(e));}
Event.observe(this.vc_dom,"click",handler,false);handler=function(e){return(me.onChapterChooserClick(e));}
Event.observe(table_dom,"click",handler,false);handler=function(e){return(me.onCloseButtonClick(e));}
chapter_chooser_dom=this.createChooser(title,table_dom,handler);return(chapter_chooser_dom);},createVerseChooser:function(e){var title="Choose a Verse";var handler;var me=this;var table_dom=this.makeVerseTable();table_dom.className="verse_chooser_body";table_dom.border="0";table_dom.cellSpacing="1";table_dom.cellPadding="0";handler=function(e){return(me.onClick(e));}
Event.observe(this.vc_dom,"click",handler,false);handler=function(e){return(me.onVerseChooserClick(e));}
Event.observe(table_dom,"click",handler,false);handler=function(e){return(me.onCloseButtonClick(e));}
verse_chooser_dom=this.createChooser(title,table_dom,handler);return(verse_chooser_dom);},createChooser:function(title,body_dom,handler){chooser_dom=document.createElement("div");chooser_dom.className="verse_chooser";title_dom=document.createElement("div");title_dom.className="verse_chooser_title";title_dom_text=document.createTextNode(title);close_button_dom=document.createElement("div");close_button_dom.className="verse_chooser_close_button";close_button_text=document.createTextNode("x");close_button_dom.appendChild(close_button_text);Event.observe(close_button_dom,"click",handler,false);title_dom.appendChild(close_button_dom);title_dom.appendChild(title_dom_text);chooser_dom.appendChild(title_dom);chooser_dom.appendChild(body_dom);return(chooser_dom);},makeBookTable:function(){var table_dom=document.createElement("table");var tbody_dom=document.createElement("tbody");var td_dom;var tr_dom;var hr_dom;var verse_node_dom;table_dom.width='100%';table_dom.border="0";table_dom.cellSpacing="1";table_dom.cellPadding="0";var bookInsertionCount=0;var layoutWidth=5;var clazz="nt";for(var i=0;i<Bible.SHORTNAMES.length;i++){td_dom=document.createElement("td");td_dom.id=i.toString();td_dom.align='center';td_dom.width='20%';td_dom.className=clazz;verse_node_dom=document.createTextNode(Bible.SHORTNAMES[i]);td_dom.appendChild(verse_node_dom);td_dom.title=Bible.LONGNAMES[i];if(bookInsertionCount%layoutWidth==0){tr_dom=document.createElement("tr");tbody_dom.appendChild(tr_dom);}
else if(bookInsertionCount==39){tr_dom=document.createElement("tr");tbody_dom.appendChild(tr_dom);td_divider_dom=document.createElement("td");td_divider_dom.colSpan=layoutWidth;td_divider_dom.className="bible-divider";tr_dom.appendChild(td_divider_dom);tr_dom=document.createElement("tr");tbody_dom.appendChild(tr_dom);clazz="ot"
td_dom.className=clazz
bookInsertionCount=0;}
tr_dom.appendChild(td_dom);bookInsertionCount++;}
table_dom.appendChild(tbody_dom);return(table_dom);},makeChapterTable:function(){var table_dom=document.createElement("table");var tbody_dom=document.createElement("tbody");var td_dom;var tr_dom;var verse_node_dom;table_dom.width='100%';var layoutWidth=10;for(var i=0;i<Bible.CHAPTERS_IN_BOOK[this.chosenBook];i++){td_dom=document.createElement("td");td_dom.id=i.toString();td_dom.align='center';td_dom.width='10%';td_dom.className="chapter";verse_node_dom=document.createTextNode((i+1).toString());td_dom.appendChild(verse_node_dom);if(i%layoutWidth==0){tr_dom=document.createElement("tr");tbody_dom.appendChild(tr_dom);}
tr_dom.appendChild(td_dom);}
table_dom.appendChild(tbody_dom);return(table_dom);},makeVerseTable:function(){var table_dom=document.createElement("table");var tbody_dom=document.createElement("tbody");var td_dom;var tr_dom;var verse_node_dom;table_dom.width='100%';var layoutWidth=10;for(var i=0;i<Bible.VERSES_IN_CHAPTER[this.chosenBook][this.chosenChapter];i++){td_dom=document.createElement("td");td_dom.id=i.toString();td_dom.align='center';td_dom.width='10%';td_dom.className="verse";verse_node_dom=document.createTextNode((i+1).toString());td_dom.appendChild(verse_node_dom);if(i%layoutWidth==0){tr_dom=document.createElement("tr");tbody_dom.appendChild(tr_dom);}
tr_dom.appendChild(td_dom);}
table_dom.appendChild(tbody_dom);return(table_dom);}};var CachePriority={Low:1,Normal:2,High:4}
function Cache(maxSize){this.items={};this.count=0;if(maxSize==null)
maxSize=-1;this.maxSize=maxSize;this.fillFactor=.75;this.purgeSize=Math.round(this.maxSize*this.fillFactor);this.stats={}
this.stats.hits=0;this.stats.misses=0;}
Cache.prototype.getItem=function(key){var item=this.items[key];if(item!=null){if(!this._isExpired(item)){item.lastAccessed=new Date().getTime();}else{this._removeItem(key);item=null;}}
var returnVal=null;if(item!=null){returnVal=item.value;this.stats.hits++;}else{this.stats.misses++;}
return returnVal;}
Cache.prototype.setItem=function(key,value,options){function CacheItem(k,v,o){if((k==null)||(k==''))
throw new Error("key cannot be null or empty");this.key=k;this.value=v;if(o==null)
o={};if(o.expirationAbsolute!=null)
o.expirationAbsolute=o.expirationAbsolute.getTime();if(o.priority==null)
o.priority=CachePriority.Normal;this.options=o;this.lastAccessed=new Date().getTime();}
if(this.items[key]!=null)
this._removeItem(key);this._addItem(new CacheItem(key,value,options));if((this.maxSize>0)&&(this.count>this.maxSize)){this._purge();}}
Cache.prototype.clear=function(){for(var key in this.items){this._removeItem(key);}}
Cache.prototype._purge=function(){var tmparray=new Array();for(var key in this.items){var item=this.items[key];if(this._isExpired(item)){this._removeItem(key);}else{tmparray.push(item);}}
if(tmparray.length>this.purgeSize){tmparray=tmparray.sort(function(a,b){if(a.options.priority!=b.options.priority){return b.options.priority-a.options.priority;}else{return b.lastAccessed-a.lastAccessed;}});while(tmparray.length>this.purgeSize){var ritem=tmparray.pop();this._removeItem(ritem.key);}}}
Cache.prototype._addItem=function(item){this.items[item.key]=item;this.count++;}
Cache.prototype._removeItem=function(key){var item=this.items[key];delete this.items[key];this.count--;if(item.options.callback!=null){var callback=function(){item.options.callback(item.key,item.value);}
setTimeout(callback,0);}}
Cache.prototype._isExpired=function(item){var now=new Date().getTime();var expired=false;if((item.options.expirationAbsolute)&&(item.options.expirationAbsolute<now)){expired=true;}
if((expired==false)&&(item.options.expirationSliding)){var lastAccess=item.lastAccessed+(item.options.expirationSliding*1000);if(lastAccess<now){expired=true;}}
return expired;}
Cache.prototype.toString=function(){var returnStr=this.count+" item(s) in cache: ";for(var key in this.items){var item=this.items[key];returnStr=returnStr+item.key.toString()+", ";}
return returnStr;}
var RedBox={redboxElement:null,SUFFIX:'RB',showInline:function(id)
{this.showOverlay();new Effect.Appear('RB_window',{duration:0.4,queue:'end'});this.cloneWindowContents(id);},loading:function()
{this.showOverlay();Element.show('RB_window');this.setWindowPositions();},addHiddenContent:function(id)
{this.removeChildrenFromNode($('RB_window'));this.moveChildren($(id),$('RB_window'));this.activateRBWindow();},activateRBWindow:function()
{Element.hide('RB_loading');this.setWindowPositions();},close:function()
{var root=($('RB_window').childNodes[1])
if(root&&root.innerHTML){this.del_id_suffixes($(root.id+this.SUFFIX));$('RB_window').childNodes[1].remove();}else if(this.redboxElement){this.del_id_suffixes($(this.redboxElement));}
new Effect.Fade('RB_window',{duration:0.4});new Effect.Fade('RB_overlay',{duration:0.4});this.showSelectBoxes();},showOverlay:function()
{var inside_redbox='<div id="RB_window" style="display: none;"><div id="RB_loading"></div></div><div id="RB_overlay" style="display: none;"></div>'
if($('RB_redbox'))
{Element.update('RB_redbox',"");new Insertion.Top($('RB_redbox'),inside_redbox);}
else
{new Insertion.Top(document.body,'<div id="RB_redbox" align="center">'+inside_redbox+'</div>');}
this.setOverlaySize();this.hideSelectBoxes();new Effect.Appear('RB_overlay',{duration:0.4,to:0.6,queue:'end'});},setOverlaySize:function()
{if(window.innerHeight&&window.scrollMaxY)
{yScroll=window.innerHeight+window.scrollMaxY;}
else if(document.body.scrollHeight>document.body.offsetHeight)
{yScroll=document.body.scrollHeight;}
else
{yScroll=document.body.offsetHeight;}
$("RB_overlay").style['height']=yScroll+"px";},setWindowPositions:function()
{this.setWindowPosition('RB_window');},setWindowPosition:function(window_id)
{var arrayPageSize=this.getPageSize();var arrayPageScroll=this.getPageScroll();var boxTop=arrayPageScroll[1]+(arrayPageSize[3]/10);var boxLeft=arrayPageScroll[0];},getPageScroll:function(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll)
return arrayPageScroll;},getPageSize:function(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;},removeChildrenFromNode:function(node)
{while(node.hasChildNodes())
{node.removeChild(node.firstChild);}},moveChildren:function(source,destination)
{while(source.hasChildNodes())
{destination.appendChild(source.firstChild);}},hideSelectBoxes:function()
{selects=document.getElementsByTagName("select");for(i=0;i!=selects.length;i++){selects[i].style.visibility="hidden";}},showSelectBoxes:function()
{selects=document.getElementsByTagName("select");for(i=0;i!=selects.length;i++){selects[i].style.visibility="visible";}},cloneWindowContents:function(id)
{var content=$(id).cloneNode(true);content.style['display']='block';this.add_id_suffixes($(id));var selects=$A(content.getElementsByTagName('SELECT'));selects.each(function(item){item.style.visibility="visible";}.bind(this));$('RB_window').appendChild(content);this.setWindowPositions();},add_id_suffixes:function(ele)
{if(ele){ele.id=ele.id+this.SUFFIX;this.redboxElement=ele.id;}},del_id_suffixes:function(ele)
{if(ele){ele.id=ele.id.gsub(this.SUFFIX,'');}}}
var Tooltip=Class.create();Tooltip.prototype={initialize:function(element,tool_tip){var options=Object.extend({default_css:false,margin:"0px",padding:"5px",backgroundColor:"#d6d6fc",delta_x:5,delta_y:5,zindex:100000},arguments[1]||{});this.element=$(element);this.tool_tip=$(tool_tip);this.buildHTML();this.options=options;this.tool_tip.hide();this.eventMouseOver=this.showTooltip.bindAsEventListener(this);this.eventMouseOut=this.hideTooltip.bindAsEventListener(this);this.registerEvents();},buildHTML:function(){toolTipTextContainer=new Element('div',{'class':'tooltip_content'}).update(this.tool_tip.innerHTML);this.tool_tip.update(toolTipTextContainer);},destroy:function(){Event.stopObserving(this.element,"mouseover",this.eventMouseOver);Event.stopObserving(this.element,"mouseout",this.eventMouseOut);},registerEvents:function(){Event.observe(this.element,"mouseover",this.eventMouseOver);Event.observe(this.element,"mouseout",this.eventMouseOut);},showTooltip:function(event){Event.stop(event);var mouse_x=Event.pointerX(event);var mouse_y=Event.pointerY(event);var dimensions=Element.getDimensions(this.tool_tip);var element_width=dimensions.width;var element_height=dimensions.height;mouse_x=mouse_x-320;mouse_y=mouse_y-150;if(cookiejar.get("state")=="library")
this.LibraryTooltipAdjust(mouse_x,mouse_y);else
this.SettingTooltipAdjust(mouse_x,mouse_y);},setStyles:function(x,y){Element.setStyle(this.tool_tip,{position:'absolute',top:y+"px",left:x+"px",zindex:99999999});if(this.options.default_css){Element.setStyle(this.tool_tip,{margin:this.options.margin,padding:this.options.padding,backgroundColor:this.options.backgroundColor,zindex:this.options.zindex});}},hideTooltip:function(event){var id=Element.hide.delay(0.2,this.tool_tip);Event.observe(this.tool_tip,'mouseover',function(){window.clearTimeout(id);});Event.observe(this.tool_tip,'mouseout',this.eventMouseOut);},LibraryTooltipAdjust:function(mouse_x,mouse_y){if(mouse_x+300>Element.getDimensions($("ebible-library")).width){mouse_x=mouse_x-260;mouse_y=mouse_y;}
if(mouse_y+200>Element.getDimensions($("ebible-library")).height){mouse_x=mouse_x;mouse_y=mouse_y-130;}
this.setStyles(mouse_x,mouse_y);new Element.show(this.tool_tip);},SettingTooltipAdjust:function(mouse_x,mouse_y){if(mouse_y+200>Element.getDimensions($("settings")).height){mouse_x=mouse_x;mouse_y=mouse_y-155;}
this.setStyles(mouse_x,mouse_y);new Element.show(this.tool_tip);}}
Object.extend(Event,{KEY_COMMA:188,KEY_SPACE:32});var ResizableTextbox=Class.create({initialize:function(element,options){var that=this;this.options=$H({min:5,max:500,step:7});this.options.update(options);this.el=$(element);this.width=this.el.offsetWidth;this.el.observe('keyup',function(){var newsize=that.options.get('step')*$F(this).length;if(newsize<=that.options.get('min'))newsize=that.width;if(!($F(this).length==this.retrieveData('rt-value')||newsize<=that.options.min||newsize>=that.options.max))
this.setStyle({'width':newsize});}).observe('keydown',function(){this.cacheData('rt-value',$F(this).length);});}});var TextboxList=Class.create({initialize:function(element,options){this.options=$H({resizable:{},className:'bit',separator:',',extrainputs:true,startinput:true,hideempty:true,newValues:false,newValueDelimiters:['[',']'],spaceReplace:'',fetchFile:undefined,fetchMethod:'get',results:10,maxResults:0,wordMatch:false,onEmptyInput:function(input){alert("Please Enter a verse/passages");},caseSensitive:false,regexSearch:true});this.current_input="";this.options.update(options);this.element=$(element).hide();this.bits=new Hash();this.events=new Hash();this.count=0;this.current=false;this.maininput=this.createInput({'class':'maininput'});this.holder=new Element('ul',{'id':'side-holder','class':'holder'}).insert(this.maininput);this.element.insert({'before':this.holder});this.holder.observe('click',function(event){event.stop();if(this.maininput!=this.current)this.focus(this.maininput);}.bind(this));this.makeResizable(this.maininput);this.setEvents();},setEvents:function(){document.observe(Prototype.Browser.IE?'keydown':'keypress',function(e){if(!this.current)return;if(this.current.retrieveData('type')=='box'&&e.keyCode==Event.KEY_BACKSPACE)e.stop();}.bind(this));document.observe('keyup',function(e){e.stop();if(!this.current)return;switch(e.keyCode){case Event.KEY_LEFT:return this.move('left');case Event.KEY_RIGHT:return this.move('right');case Event.KEY_DELETE:}}.bind(this)).observe('click',function(){document.fire('blur');}.bindAsEventListener(this));},update:function(){this.element.value=this.bits.values().join(this.options.get('separator'));if(!this.current_input.blank()){this.element.value+=(this.element.value.blank()?"":this.options.get('separator'))+this.current_input;}
return this;},add:function(text,html){if(this.bits.keys().length>=10){eb.unselectRow(text.ordinals);alert("Sorry, maximum passages you can select is 10");return false;}
var id=this.id_base+'-'+this.count++;var el=this.createBox($pick(html,text),{'id':id,'class':this.options.get('className'),'newValue':text.newValue?'true':'false'});new Insertion.Before(this.maininput,el);el.observe('click',function(e){e.stop();this.focus(el);var ref=this.getSelectedOne().ref.split('-')[0];document.location.href="#"+ref;}.bind(this));this.bits.set(id,{ref:text.value,ordinals:text.ordinals});this.show();this.createDraggableList();this.update();if(this.options.get('extrainputs')&&(this.options.get('startinput')||el.previous()))this.addSmallInput(el,'before');return el;},addSmallInput:function(el,where){var input=this.createInput({'class':'smallinput'});el.insert({}[where]=input);input.cacheData('small',true);this.makeResizable(input);if(this.options.get('hideempty'))input.hide();return input;},dispose:function(el){this.bits.unset(el.id);this.update();if(el.previous()&&el.previous().retrieveData('small'))el.previous().remove();if(this.current==el)this.focus(el.next());if(el.retrieveData('type')=='box')el.onBoxDispose(this);el.remove();if(this.bits.keys().length<1){this.hide();}
return this;},focus:function(el,nofocus){if(!this.current)el.fire('focus');else if(this.current==el)return this;this.blur();el.addClassName(this.options.get('className')+'-'+el.retrieveData('type')+'-focus');if(el.retrieveData('small'))el.setStyle({'display':'block'});if(el.retrieveData('type')=='input'){el.onInputFocus(this);if(!nofocus)this.callEvent(el.retrieveData('input'),'focus');}
else el.fire('onBoxFocus');this.current=el;return this;},blur:function(noblur){if(!this.current)return this;if(this.current.retrieveData('type')=='input'){var input=this.current.retrieveData('input');if(!noblur)this.callEvent(input,'blur');input.onInputBlur(this);}
else this.current.fire('onBoxBlur');if(this.current.retrieveData('small')&&!input.get('value')&&this.options.get('hideempty'))
this.current.hide();this.current.removeClassName(this.options.get('className')+'-'+this.current.retrieveData('type')+'-focus');this.current=false;return this;},createBox:function(text,options){return new Element('li',options).addClassName(this.options.get('className')+'-box').update('<div class="selected-passage">'+text.caption+"</span>").cacheData('type','box');},createInput:function(options){var li=new Element('li',{'class':this.options.get('className')+'-input'});var el=new Element('input',Object.extend(options,{'type':'text','autocomplete':'off'}));var tmp=li.cacheData('type','input').cacheData('input',el).insert(el);return tmp;},callEvent:function(el,type){this.events.set(type,el);el[type]();},isSelfEvent:function(type){return(this.events.get(type))?!!this.events.unset(type):false;},makeResizable:function(li){var el=li.retrieveData('input');el.cacheData('resizable',new ResizableTextbox(el,Object.extend(this.options.get('resizable'),{min:el.offsetWidth,max:(this.element.getWidth()?this.element.getWidth():0)})));return this;},checkInput:function(){var input=this.current.retrieveData('input');return(!input.retrieveData('lastvalue')||(input.getCaretPosition()===0&&input.retrieveData('lastcaret')===0));},move:function(direction){var el=this.current[(direction=='left'?'previous':'next')]();if(el&&(!this.current.retrieveData('input')||((this.checkInput()||direction=='right'))))this.focus(el);return this;}});Element.addMethods({getCaretPosition:function(){if(this.createTextRange){var r=document.selection.createRange().duplicate();r.moveEnd('character',this.value.length);if(r.text==='')return this.value.length;return this.value.lastIndexOf(r.text);}else return this.selectionStart;},cacheData:function(element,key,value){if(Object.isUndefined(this[$(element).identify()])||!Object.isHash(this[$(element).identify()]))
this[$(element).identify()]=$H();this[$(element).identify()].set(key,value);return element;},retrieveData:function(element,key){return this[$(element).identify()].get(key);}});function $pick(){for(var B=0,A=arguments.length;B<A;B++){if(!Object.isUndefined(arguments[B])){return arguments[B];}}
return null;}
var selectedPassageList=Class.create(TextboxList,{initialize:function($super,widget,element,autoholder,options,func){$super(element,options);this.loptions=$H({autocomplete:{'opacity':1,'maxresults':10,'minchars':1}});this.ebible_handler=widget;this.id_base=$(element).identify()+"_"+this.options.get("className");this.data=[];this.data_searchable=[];this.autoholder=$(autoholder).setOpacity(this.loptions.get('autocomplete').opacity);this.autoholder.observe('mouseover',function(){this.curOn=true;}.bind(this)).observe('mouseout',function(){this.curOn=false;}.bind(this));if(this.autoholder.select('ul').first())
this.autoresults=this.autoholder.select('ul').first();var children=null;if(this.autoresults.select('li')){children=this.autoresults.select('li');children.each(function(el){this.add({value:el.readAttribute('value'),caption:el.innerHTML});},this);}
if(!Object.isUndefined(this.options.get('fetchFile'))){new Ajax.Request(this.options.get('fetchFile'),{method:this.options.get('fetchMethod'),onSuccess:function(transport){transport.responseText.evalJSON(true).each(function(t){this.autoFeed(t)}.bind(this));}.bind(this)});}},autoShow:function(search){this.autoholder.setStyle({'display':'block'});this.autoholder.descendants().each(function(e){e.hide()});if(!search||!search.strip()||(!search.length||search.length<this.loptions.get('autocomplete').minchars)){this.resultsshown=false;}else{this.resultsshown=true;this.autoresults.setStyle({'display':'block'}).update('');if(!this.options.get('regexSearch')){var matches=new Array();if(search){if(!this.options.get('caseSensitive')){search=search.toLowerCase();}
var matches_found=0;for(var i=0,len=this.data_searchable.length;i<len;i++){if(this.data_searchable[i].indexOf(search)>=0){matches[matches_found++]=this.data[i];}}}}else{if(this.options.get('wordMatch')){var regexp=new RegExp("(^|\\s)"+search,(!this.options.get('caseSensitive')?'i':''));}else{var regexp=new RegExp(search,(!this.options.get('caseSensitive')?'i':''));var matches=this.data.filter(function(str){return str?regexp.test(str.evalJSON(true).caption):false;});}}
var count=0;matches.each(function(result,ti){count++;if(ti>=(this.options.get('maxResults')?this.options.get('maxResults'):this.loptions.get('autocomplete').maxresults))return;var that=this;var el=new Element('li');el.observe('click',function(e){e.stop();that.current_input="";that.autoAdd(this);}).observe('mouseover',function(){that.autoFocus(this);}).update(this.autoHighlight(result.evalJSON(true).caption,search));this.autoresults.insert(el);el.cacheData('result',result.evalJSON(true));if(ti==0)this.autoFocus(el);},this);}
if(count==0){this.autoHide();}else{if(count>this.options.get('results'))
this.autoresults.setStyle({'height':(this.options.get('results')*24)+'px'});else
this.autoresults.setStyle({'height':(count?(count*24):0)+'px'});}
return this;},autoHighlight:function(html,highlight){return html.gsub(new RegExp(highlight,'i'),function(match){return'<em>'+match[0]+'</em>';});},autoHide:function(){this.resultsshown=false;this.autoholder.hide();return this;},autoFocus:function(el){if(!el)return;if(this.autocurrent)this.autocurrent.removeClassName('auto-focus');this.autocurrent=el.addClassName('auto-focus');return this;},autoMove:function(direction){if(!this.resultsshown)return;this.autoFocus(this.autocurrent[(direction=='up'?'previous':'next')]());this.autoresults.scrollTop=this.autocurrent.positionedOffset()[1]-this.autocurrent.getHeight();return this;},autoFeed:function(text){var with_case=this.options.get('caseSensitive');if(this.data.indexOf(Object.toJSON(text))==-1){this.data.push(Object.toJSON(text));this.data_searchable.push(with_case?Object.toJSON(text).evalJSON(true).caption:Object.toJSON(text).evalJSON(true).caption.toLowerCase());}
return this;},autoAdd:function(el){if(this.newvalue&&this.options.get("newValues")){var input=el;}else if(!el||!el.retrieveData('result')){return;}else{delete this.data[this.data.indexOf(Object.toJSON(el.retrieveData('result')))];var input=this.lastinput||this.current.retrieveData('input');}
this.autoHide();input.clear().focus();return this;},createInput:function($super,options){var li=$super(options);var input=li.retrieveData('input');input.observe('keydown',function(e){this.dosearch=false;this.newvalue=false;switch(e.keyCode){case Event.KEY_UP:e.stop();return this.autoMove('up');case Event.KEY_DOWN:e.stop();return this.autoMove('down');case Event.KEY_RETURN:e.stop();if(!this.autocurrent||!this.resultsshown)break;this.current_input="";this.autoAdd(this.autocurrent);this.autocurrent=false;this.autoenter=true;break;case Event.KEY_ESC:this.autoHide();if(this.current&&this.current.retrieveData('input'))
this.current.retrieveData('input').clear();break;default:this.dosearch=true;}}.bind(this));input.observe('keyup',function(e){switch(e.keyCode){case Event.KEY_RETURN:if(this.options.get('newValues')){new_value_el=this.current.retrieveData('input');if(!new_value_el.value.endsWith('<')){keep_input="";new_value_el.value=new_value_el.value.strip();new_value_el.value=new_value_el.value.gsub(",","").escapeHTML().strip();if(!this.options.get("spaceReplace").blank())new_value_el.value.gsub(" ",this.options.get("spaceReplace"));var url=eb.options.domain+"/browser/passage2ordinals?callback=eb.selectedList.ordinalsReceived&passage="+new_value_el.value;var transactionObj=YAHOO.util.Get.script(url,{onSuccess:function(o){this.waitingForCallback=false;},onFailure:function(o){alert('Sorry, there was a problem contacting the server. Please try again or contact support@ebible.com');},scope:this});new_value_el.value='';}}
break;case Event.KEY_UP:case Event.KEY_DOWN:case Event.KEY_COMMA:case Event.KEY_ESC:break;default:this.update();if(this.searchTimeout)clearTimeout(this.searchTimeout);this.searchTimeout=setTimeout(function(){var sanitizer=new RegExp("[({[^$*+?\\\]})]","g");}.bind(this),250);}}.bind(this));input.observe(Prototype.Browser.IE?'keydown':'keypress',function(e){if((e.keyCode==Event.KEY_RETURN)&&this.autoenter)e.stop();this.autoenter=false;}.bind(this));return li;},createBox:function($super,text,options){var li=$super(text,options);li.observe('mouseover',function(){}).observe('mouseout',function(){});var a=new Element('div',{'class':'closebutton','title':'Close'});a.insert(" x ");a.observe('click',function(e){e.stop();if(!this.current)this.focus(this.maininput);this.bits.get(li.id).ordinals.each(function(ordinal){eb.unselectRow(ordinal);});this.dispose(li);}.bind(this));li.insert(a).cacheData('text',Object.toJSON(text));return li;},ordinalsReceived:function(result){if(result==null){$('verse-auto').update('Not valid verse');$('verse-auto').setStyle({'color':'red'});$('verse-auto').show();Effect.Fade('verse-auto',{duration:2.0});return;}
testresult=result
this.newvalue=true;this.current_input="";result.ordinals.each(function(ordinal){eb.selectRow(ordinal);});this.updateSelected(eb.selectedRows());this.update();},updateSelected:function(selected_ordinals){$$('li.bit-box').each(function(li){Event.stopObserving(li);}.bind(this));if(selected_ordinals.length<1)return;var selected_refnums=[];selected_ordinals.each(function(ordinal){selected_refnums.push(Bible.ordinal2refnum(ordinal));}.bind(this));var mergedContinuousVerses=Bible.mergeContinuousVerses(selected_refnums);var mergedContinuousOrdinals=Bible.mergeContinuousOrdinals(selected_refnums);this.clear();var i=0;while(i<mergedContinuousVerses.length){this.add({value:mergedContinuousVerses[i],caption:mergedContinuousVerses[i],ordinals:mergedContinuousOrdinals[i]});i++;}},clear:function(remove_all){eb.toolbar.disableActions();if(remove_all){this.bits.values().each(function(li){li.ordinals.each(function(ord){eb.unselectRow(ord);});});}
var count=$$('ul#side-holder li').length-1;for(i=0;i<count/2;i++)
this.dispose($$('ul#side-holder li')[0]);},getSelected:function(){return this.bits.values();},getSelectedOne:function(){return this.bits.get($$('.bit-box-focus')[0].id);},show:function(){$('eb-selection-bar').show();eb.toolbar.enableActions();},hide:function(){$('eb-selection-bar').hide();eb.toolbar.disableActions();},createDraggableList:function(){var elem=null;var dragText=null;$('side-holder').childElements().each(function(ele){new Draggable(ele,{ghosting:true,revert:true,onStart:function(obj){new Draggable(obj._clone);elem=obj.element;dragText=obj.element.down('.selected-passage').innerHTML;console.log("XTH: "+dragText);},onDropped:function(element,evt){element.stopObserving('click');var verseRef=element.down('.ele-ref').innerHTML;this.ebible_handler._draggableOnDropped(element,verseRef);}.bindAsEventListener(this),onDrag:function(obj){obj.element.removeClassName('bit');obj.element.removeClassName('bit-box');obj.element.removeClassName('bit-hover');obj.element.update('<span class="ele-ref">'+dragText+'</div>');obj.element.addClassName("drag");obj.element.style.opacity="1";},onEnd:function(obj){obj.element=elem;this.createDraggableList();if($('playlistcalendar')){var udts=[];this.ebible_handler.playlist.currentPlaylist[1].each(function(item){if(item.scheduled_for!==null){udts.push(new Date(eb.playlist._getFilteredDate(item.scheduled_for)).format("yyyy-mm-dd"));}}.bind(this));highlightScheduledDate(udts,playlistcal);}
this.updateSelected(eb.selectedRows());}.bindAsEventListener(this)});ele.treeNode=$('side-holder');}.bindAsEventListener(this));}});Element.addMethods({onBoxDispose:function(item,obj){item=item.retrieveData('text').evalJSON(true);if(!item.newValue)
obj.autoFeed(item);},onInputFocus:function(el,obj){},onInputBlur:function(el,obj){obj.lastinput=el;if(!obj.curOn){obj.blurhide=obj.autoHide.bind(obj).delay(0.1);}},filter:function(D,E){var C=[];for(var B=0,A=this.length;B<A;B++){if(D.call(E,this[B],B,this)){C.push(this[B]);}}return C;}});var ap_instances=new Array();function ap_stopAll(playerID){for(var i=0;i<ap_instances.length;i++){try{if(ap_instances[i]!=playerID)document.getElementById("audioplayer"+ap_instances[i].toString()).SetVariable("closePlayer",1);else document.getElementById("audioplayer"+ap_instances[i].toString()).SetVariable("closePlayer",0);}catch(errorObject){}}}
function ap_registerPlayers(){var objectID;var objectTags=document.getElementsByTagName("object");for(var i=0;i<objectTags.length;i++){objectID=objectTags[i].id;if(objectID.indexOf("audioplayer")==0){ap_instances[i]=objectID.substring(11,objectID.length);}}}
var ap_clearID=setInterval(ap_registerPlayers,100);Carousel=Class.create(Abstract,{initialize:function(scroller,slides,controls,options){this.scrolling=false;this.scroller=$(scroller);this.controls=controls;this.slides=slides;this.options=Object.extend({duration:0.5,auto:false,frequency:3,visibleSlides:1,controlClassName:'carousel-control',jumperClassName:'carousel-jumper',disabledClassName:'carousel-disabled',selectedClassName:'carousel-selected',circular:false,wheel:true,effect:'scroll',transition:'sinoidal'},options||{});if(this.options.effect=='fade'){this.options.circular=true;}
if(this.options.carouselFor=="playlistbar"){this.disablePrevBtn();}
if($('playlist-items').childElements().length<=this.options.visibleSlides&&this.options.carouselFor=='playlistbar'){this.disableNextBtn();this.deactivateControls();}else if($('playlist-items').childElements().length>this.options.visibleSlides&&this.options.carouselFor=='playlistbar'){this.enableNextBtn();}
this.slides.each(function(slide,index){slide._index=index;});if(this.controls){if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){this.controls.invoke('observe','mousedown',this.click.bind(this));}else{this.controls.invoke('observe','click',this.click.bind(this));}}
if(this.options.auto){this.start();}
if(this.options.initial){var initialIndex=this.slides.indexOf($(this.options.initial));if(initialIndex>(this.options.visibleSlides-1)&&this.options.visibleSlides>1){if(initialIndex>this.slides.length-(this.options.visibleSlides+1)){initialIndex=this.slides.length-this.options.visibleSlides;}}
this.moveTo(this.slides[initialIndex]);}},click:function(event){this.stop();var element=event.findElement('a');var response=null;if(!element.hasClassName(this.options.disabledClassName)){if(element.hasClassName(this.options.controlClassName)){eval("this."+element.rel+"()");}else if(element.hasClassName(this.options.jumperClassName)){if(eb.playlist.itemEditMode){response=confirm("You are currently editing a playlist item. Abandon changes?");if(response){eb.playlist._insertItemTable();this.moveTo(element.rel);eb.playlist._highlightPlaylistItem("drop_"+element.rel.split("-").last());eb.playlist._updateTotalPlaylist();}}else{this.moveTo(element.rel);}
if(this.options.selectedClassName){this.controls.invoke('removeClassName',this.options.selectedClassName);element.addClassName(this.options.selectedClassName);}}}
this.deactivateControls();if(!response){this.activateControls();}
event.stop();},moveTo:function(element){if(this.options.beforeMove&&(typeof this.options.beforeMove=='function')){this.options.beforeMove();}
this.previous=this.current?this.current:this.slides[0];this.current=$(element);var scrollerOffset=this.scroller.cumulativeOffset();var elementOffset=this.current.cumulativeOffset();if(this.scrolling){this.scrolling.cancel();}
switch(this.options.effect){case'fade':this.scrolling=new Effect.Opacity(this.scroller,{from:1.0,to:0,duration:this.options.duration,afterFinish:(function(){this.scroller.scrollLeft=elementOffset[0]-scrollerOffset[0];this.scroller.scrollTop=elementOffset[1]-scrollerOffset[1];new Effect.Opacity(this.scroller,{from:0,to:1.0,duration:this.options.duration,afterFinish:(function(){if(this.controls){this.activateControls();}
if(this.options.afterMove&&(typeof this.options.afterMove=='function')){}}).bind(this)});}).bind(this)});break;case'scroll':default:var transition;switch(this.options.transition){case'spring':transition=Effect.Transitions.spring;break;case'sinoidal':default:transition=Effect.Transitions.sinoidal;break;}
this.scrolling=new Effect.SmoothScroll(this.scroller,{duration:this.options.duration,x:(elementOffset[0]-scrollerOffset[0]),y:(elementOffset[1]-scrollerOffset[1]),transition:transition,carouselfor:this.options.carouselFor,afterFinish:(function(){if(this.controls){this.activateControls();}
if(this.options.afterMove&&(typeof this.options.afterMove=='function')){this.options.afterMove();}
this.scrolling=false;}).bind(this)});break;}
return false;},prev:function(){if(this.current){var currentIndex=this.current._index;var prevIndex=(currentIndex==0)?(this.options.circular?this.slides.length-1:0):currentIndex-1;}else{var prevIndex=(this.options.circular?this.slides.length-1:0);}
if(prevIndex==(this.slides.length-1)&&this.options.circular&&this.options.effect!='fade'){this.scroller.scrollLeft=(this.slides.length-1)*this.slides.first().getWidth();this.scroller.scrollTop=(this.slides.length-1)*this.slides.first().getHeight();prevIndex=this.slides.length-2;}
this.moveTo(this.slides[prevIndex]);if(this.options.carouselFor=="playlistbar"){if(prevIndex>0){$$('a.next')[0].setStyle({background:"transparent url(/images/btn-next.gif) no-repeat scroll 0 0"});$$('a.next')[0].removeClassName(this.options.disabledClassName);$$('a.next')[0].addClassName(this.options.controlClassName);}else{$$('a.prev')[0].setStyle({background:"transparent url(/images/btn-previous-disabled.gif) no-repeat scroll 0 0"});$$('a.prev')[0].removeClassName(this.options.controlClassName);$$('a.prev')[0].addClassName(this.options.disabledClassName);$$('a.next')[0].setStyle({background:"transparent url(/images/btn-next.gif) no-repeat scroll 0 0"});$$('a.next')[0].removeClassName(this.options.disabledClassName);$$('a.next')[0].addClassName(this.options.controlClassName);}}},next:function(){if(this.current){var currentIndex=this.current._index;var nextIndex=(this.slides.length-1==currentIndex)?(this.options.circular?0:currentIndex):currentIndex+1;}else{var nextIndex=1;}
if(nextIndex==0&&this.options.circular&&this.options.effect!='fade'){this.scroller.scrollLeft=0;this.scroller.scrollTop=0;nextIndex=1;}
if(nextIndex>this.slides.length-(this.options.visibleSlides+1)){nextIndex=this.slides.length-this.options.visibleSlides;}
this.moveTo(this.slides[nextIndex]);if(this.options.carouselFor=="playlistbar"){if(nextIndex>this.slides.length-this.options.visibleSlides-1){$$('a.next')[0].setStyle({background:"transparent url(/images/btn-next-disabled.gif) no-repeat scroll 0 0"});$$('a.next')[0].removeClassName(this.options.controlClassName);$$('a.next')[0].addClassName(this.options.disabledClassName);this.enablePrevBtn();}else{$$('a.prev')[0].setStyle({background:"transparent url(/images/btn-previous.gif) no-repeat scroll 0 0"});$$('a.prev')[0].removeClassName(this.options.disabledClassName);$$('a.prev')[0].addClassName(this.options.controlClassName);}}},first:function(){this.moveTo(this.slides[0]);},last:function(){this.moveTo(this.slides[this.slides.length-1]);},toggle:function(){if(this.previous){this.moveTo(this.slides[this.previous._index]);}else{return false;}},stop:function(){if(this.timer){clearTimeout(this.timer);}},start:function(){this.periodicallyUpdate();},pause:function(){this.stop();this.activateControls();},resume:function(event){if(event){var related=event.relatedTarget||event.toElement;if(!related||(!this.slides.include(related)&&!this.slides.any(function(slide){return related.descendantOf(slide);}))){this.start();}}else{this.start();}},periodicallyUpdate:function(){if(this.timer!=null){clearTimeout(this.timer);this.next();}
this.timer=setTimeout(this.periodicallyUpdate.bind(this),this.options.frequency*1000);},wheel:function(event){event.cancelBubble=true;event.stop();var delta=0;if(!event){event=window.event;}
if(event.wheelDelta){delta=event.wheelDelta/120;}else if(event.detail){delta=-event.detail/3;}
if(!this.scrolling){this.deactivateControls();if(delta>0){this.prev();}else{this.next();}}
return Math.round(delta);},deactivateControls:function(){this.controls.invoke('addClassName',this.options.disabledClassName);},activateControls:function(){this.controls.invoke('removeClassName',this.options.disabledClassName);},disableNextBtn:function(){$$('#playlist-carousel a.next')[0].setStyle({background:"transparent url(/images/btn-next-disabled.gif) no-repeat scroll 0 0"});$$('#playlist-carousel a.next')[0].addClassName("carousel-disabled");$$('#playlist-carousel a.next')[0].removeClassName("carousel-control");},enableNextBtn:function(){$$('#playlist-carousel a.next')[0].setStyle({background:"transparent url(/images/btn-next.gif) no-repeat scroll 0 0"});$$('#playlist-carousel a.next')[0].removeClassName("carousel-disabled");$$('#playlist-carousel a.next')[0].addClassName("carousel-control");},enablePrevBtn:function(){$$('#playlist-carousel a.prev')[0].setStyle({background:"transparent url(/images/btn-previous.gif) no-repeat scroll 0 0"});$$('#playlist-carousel a.prev')[0].addClassName("carousel-control");$$('#playlist-carousel a.prev')[0].removeClassName("carousel-disabled");},disablePrevBtn:function(){$$('#playlist-carousel a.prev')[0].setStyle({background:"transparent url(/images/btn-previous-disabled.gif) no-repeat scroll 0 0"});$$('#playlist-carousel a.prev')[0].addClassName("carousel-disabled");$$('#playlist-carousel a.prev')[0].removeClassName("carousel-control");},destroy:function(){this.controls.invoke('stopObserving','click');}});Effect.SmoothScroll=Class.create();Object.extend(Object.extend(Effect.SmoothScroll.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);var options=Object.extend({x:0,y:0,mode:'absolute'},arguments[1]||{});this.start(options);},setup:function(){if(this.options.continuous&&!this.element._ext){this.element.cleanWhitespace();this.element._ext=true;this.element.appendChild(this.element.firstChild);}
this.originalLeft=this.element.scrollLeft;this.originalTop=this.element.scrollTop;if(this.options.mode=='absolute'){this.options.x-=this.originalLeft;this.options.y-=this.originalTop;}},update:function(position){if(this.options.carouselfor=="playlistbar"){var moveLeft=0-(this.options.x*position+this.originalLeft);this.element.setStyle({left:moveLeft+"px"});}else{this.element.scrollLeft=this.options.x*position+this.originalLeft;this.element.scrollTop=this.options.y*position+this.originalTop;}}});Object.extend(Date.prototype,{monthnames:['January','February','March','April','May','June','July','August','September','October','November','December'],daynames:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],succ:function(){var sd=new Date(this.getFullYear(),this.getMonth(),this.getDate()+1);sd.setHours(this.getHours(),this.getMinutes(),this.getSeconds(),this.getMilliseconds());return sd;},firstofmonth:function(){return new Date(this.getFullYear(),this.getMonth(),1);},lastofmonth:function(){return new Date(this.getFullYear(),this.getMonth()+1,0);},formatPadding:true,format:function(f){if(!this.valueOf()){return'&nbsp;';}
var d=this;var formats={'yyyy':d.getFullYear(),'mmmm':this.monthnames[d.getMonth()],'mmm':this.monthnames[d.getMonth()].substr(0,3),'mm':this.formatPadding?((d.getMonth()).succ()).toPaddedString(2):(d.getMonth()).succ(),'dddd':this.daynames[d.getDay()],'ddd':this.daynames[d.getDay()].substr(0,3),'dd':d.getDate().toPaddedString(2),'hh':h=d.getHours()%12?h:12,'nn':d.getMinutes(),'ss':d.getSeconds(),'a/p':d.getHours()<12?'a':'p'};return f.gsub(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/i,function(match){return formats[match[0].toLowerCase()];});}});var scal={};scal=Class.create();scal.prototype={initialize:function(element,update){this.element=$(element);var type=Try.these(function(){if(!Object.isUndefined(Effect)){return'Effect';}},function(){return'Element';});this.options=Object.extend({oncalchange:Prototype.emptyFunction,daypadding:false,titleformat:'mmmm yyyy',updateformat:'yyyy-mm-dd',closebutton:'X',prevbutton:'&laquo;',nextbutton:'&raquo;',yearnext:'&raquo;&raquo;',yearprev:'&laquo;&laquo;',openeffect:type=='Effect'?Effect.Appear:Element.show,closeeffect:type=='Effect'?Effect.Fade:Element.hide,exactweeks:false,dayheadlength:2,weekdaystart:0,planner:false,tabular:false},arguments[2]||{});this.table=false;this.thead=false;this.startdate=this._setStartDate(arguments[2]);if(this.options.planner){this._setupPlanner(this.options.planner);}
if(this.options.tabular){this.table=new Element('table',{'class':'cal_table',border:0,cellspacing:0,cellpadding:0});this.thead=new Element('thead');this.table.insert(this.thead);this.element.insert(this.table);}
this.updateelement=update;this._setCurrentDate(this.startdate);this.initDate=new Date(this.currentdate);this.controls=this._buildControls();this.title.setAttribute('title',this.initDate.format(this.options.titleformat));this._updateTitles();this[this.table?'thead':'element'].insert(this.controls);this.cal_wrapper=this._buildHead();this.cells=[];this._buildCal();},_eventMouseMove:function(event){this.startX=Event.pointerX(event);this.startY=Event.pointerY(event);if(!Position.within(this.element,this.startX,this.startY)){this.element.hide();Event.stopObserving(document,'mouseover',this._eventMouseMove.bind(this));this.element.update('');}},_setStartDate:function(){var args=arguments[0];var startday=new Date();this.options.month=args&&args.month&&Object.isNumber(args.month)?args.month-1:startday.getMonth();this.options.year=args&&args.year&&Object.isNumber(args.year)?args.year:startday.getFullYear();this.options.day=args&&args.day&&Object.isNumber(args.day)?args.day:(this.options.month!=startday.getMonth())?1:startday.getDate();startday.setHours(0,0,0,0);startday.setDate(this.options.day);startday.setMonth(this.options.month);startday.setFullYear(this.options.year);return startday;},_emptyCells:function(){if(this.cells.size()>0){this.cells.invoke('stopObserving');this.cells.invoke('remove');this.cells=[];}},_buildCal:function(){this._emptyCells();if(!(Object.isUndefined(this.cal_weeks_wrapper)||this.table)){this.cal_weeks_wrapper.remove();}
this.cal_weeks_wrapper=this._buildWrapper();if(this.table){this.table.select('tbody tr.weekbox:not(.weekboxname)').invoke('remove');this.table.select('tbody.cal_wrapper').invoke('remove');this.cal_weeks_wrapper.each(function(row){this.cal_wrapper.insert(row);}.bind(this));}else{this.cal_wrapper.insert(this.cal_weeks_wrapper);}
this[this.table?'table':'element'].insert(this.cal_wrapper);},_click:function(event,cellIndex){var el=this.cells[cellIndex].select('.dayboxvalue')[0].up().down();clicked_date=this.dateRange[cellIndex].format("yyyy-mm-dd");this.element.select('.dayselected').invoke('removeClassName','dayselected');(event.target.hasClassName('daybox')?event.target:event.target.up()).addClassName('dayselected');this._setCurrentDate(this.dateRange[cellIndex]);this._updateExternal();var records=[];var index=0;eb.playlist.currentPlaylist[1].each(function(item){if(new Date(eb.playlist._getFilteredDate(item.scheduled_for)).format('yyyy-mm-dd')==clicked_date){if(index>0){records.push(item);}
index+=1;}});var first=false;if(!$(this.updateelement)&&el.hasClassName("highlightitemsdate")){eb.playlist.currentPlaylist[1].each(function(item){if(new Date(eb.playlist._getFilteredDate(item.scheduled_for)).format('yyyy-mm-dd')==clicked_date&&first==false){el=$('drop_'+item.id);first=true;}
eb.playlist._highlightPlaylistItem(el.id);});if(records.length>0){eb.playlist._adjustMultiple(records);}else{if($('additional-items').visible()){$('additional-items').hide();}}
var element=$("item-table-"+$$('li.highlight').first().id.gsub("drop_",""));eb.playlist.contentCarousel.moveTo(element);eb.playlist._updateTotalPlaylist();}},_updateExternal:function(){if(Object.isFunction(this.updateelement)){this.updateelement(this.currentdate);this.element.hide();}else{if($(this.updateelement)){var updateElement=$(this.updateelement);updateElement[updateElement.tagName=='INPUT'?'setValue':'update'](this.currentdate.format(this.options.updateformat));this.element.hide();}}},_buildHead:function(){var cal_wrapper=new Element(this.table?'tbody':'div',{'class':'cal_wrapper'});var weekbox=new Element(this.table?'tr':'div',{'class':'weekbox weekboxname'});Date.prototype.daynames.sortBy(function(s,i){i-=this.options.weekdaystart;if(i<0){i+=7;}
return i;}.bind(this)).each(function(day,i){var cell=new Element(this.table?'td':'div',{'class':'cal_day_name_'+i});cell.addClassName('daybox').addClassName('dayboxname').update(day.substr(0,this.options.dayheadlength));if(i==6){cell.addClassName('endweek');}
weekbox.insert(cell);}.bind(this));return cal_wrapper.insert(weekbox);},_buildWrapper:function(){var firstdaycal=new Date(this.firstofmonth.getFullYear(),this.firstofmonth.getMonth(),this.firstofmonth.getDate());var lastdaycal=new Date(this.lastofmonth.getFullYear(),this.lastofmonth.getMonth(),this.lastofmonth.getDate());if(this.options.weekdaystart-firstdaycal.getDay()<firstdaycal.getDate()){firstdaycal.setDate(firstdaycal.getDate()-firstdaycal.getDay()+this.options.weekdaystart);}else{firstdaycal.setDate(firstdaycal.getDate()-(firstdaycal.getDay()+7-this.options.weekdaystart));}
var dateRange=$A($R(firstdaycal,lastdaycal));var cal_weeks_wrapper=this.table?[]:new Element('div',{'class':'calweekswrapper'});var wk;var row;var lastday;this.dateRange=[];this.indicators=[];var buildWeek=function(day){row.insert(this._buildDay(wk,day));lastday=day;}.bind(this);dateRange.eachSlice(7,function(slice,i){wk=i;row=new Element(this.table?'tr':'div',{'class':'cal_week_'+wk}).addClassName('weekbox');while(slice.length<7){slice.push(slice.last().succ());}
slice.map(buildWeek);cal_weeks_wrapper[this.table?'push':'insert'](row);}.bind(this));if(!this.options.exactweeks){var toFinish=42-this.cells.size();var wkstoFinish=Math.ceil(toFinish/7);if(wkstoFinish>0){toFinish=toFinish/wkstoFinish;}
$R(1,wkstoFinish).each(function(w){wk+=1;row=new Element(this.table?'tr':'div',{'class':'cal_week_'+wk}).addClassName('weekbox');$R(1,toFinish).each(function(i){var d=lastday.succ();row.insert(this._buildDay(wk,d));cal_weeks_wrapper[this.table?'push':'insert'](row);lastday=d;}.bind(this));}.bind(this));}
return cal_weeks_wrapper;},_compareDates:function(date1,date2,type){return(this.indicators.indexOf(type)>=0)?false:Object.isUndefined(['getMonth','getDate','getFullYear'].find(function(n){return date1[n]()!=date2[n]();}));},_buildDay:function(week,day){this.dateRange.push(day);var cellid='cal_day_'+week+'_'+day.getDay();var cell=new Element(this.table?'td':'div',{'class':cellid});var celldate=new Element('div',{'class':cellid+'_date'}).addClassName('dayboxdate').update(this.options.daypadding?((day.getDate()).toPaddedString(2)):day.getDate());var cellvalue=new Element('div',{'class':cellid+'_value'}).addClassName('dayboxvalue');if(this.options.planner){this._updatePlanner(day,cellvalue);}
cell.insert(celldate).insert(cellvalue).addClassName('daybox').addClassName('daybox'+day.format('dddd').toLowerCase());if(this._compareDates(day,new Date(),'today')){cell.addClassName('today');this.indicators.push('today');}
if(day.getDay()==6){cell.addClassName('endweek');}
if(eb){if(day.format('yy-dd-mm')==new Date(eb.playlist.currentDate).format('yy-dd-mm')){cell.addClassName("dayselected");}
if(day<new Date(eb.playlist.currentDate)){cell.addClassName("previousday");}}
var cs=day.getMonth()!=this.currentdate.getMonth()?['dayoutmonth','dayinmonth']:['dayinmonth','dayoutmonth'];cell.addClassName(cs[0]);if(cell.hasClassName(cs[1])){cell.removeClassName(cs[1]);}
this.cells.push(cell);if(cell.hasClassName("dayinmonth")&&!cell.hasClassName("previousday")&&!cell.hasClassName("dayoutmonth")){return cell.observe('click',this._click.bindAsEventListener(this,this.cells.size()-1));}
else{var scheduled=false;if(eb){eb.playlist.currentPlaylist[1].each(function(pl){if(new Date(eb.playlist._getFilteredDate(pl.scheduled_for)).format('yyyy-mm-dd')==day.format('yyyy-mm-dd')){scheduled=true;}});}
if(scheduled){return cell.observe('click',this._click.bindAsEventListener(this,this.cells.size()-1));}else{return cell;}}},_updateTitles:function(){var yr=this.currentdate.getFullYear();var mnth=this.currentdate.getMonth();var titles={calprevmonth:Date.prototype.monthnames[(mnth-1)==-1?11:mnth-1],calprevyear:yr-1,calnextyear:yr+1,calnextmonth:Date.prototype.monthnames[(mnth+1)==12?0:mnth+1]};this.controls.select('.calcontrol').each(function(ctrl){var title=titles[ctrl.className.split(' ')[0]];if(!Object.isUndefined(title)){ctrl.setAttribute('title',title);}});},_buildControls:function(){var hParts=[{p:'calclose',u:this.options.closebutton,f:this.toggleCalendar.bindAsEventListener(this)},{p:'calprevmonth',u:this.options.prevbutton,f:this._switchCal.bindAsEventListener(this,'monthdown')},{p:'calprevyear',u:this.options.yearprev,f:this._switchCal.bindAsEventListener(this,'yeardown')},{p:'calnextyear',u:this.options.yearnext,f:this._switchCal.bindAsEventListener(this,'yearup')},{p:'calnextmonth',u:this.options.nextbutton,f:this._switchCal.bindAsEventListener(this,'monthup')},{p:'caltitle',u:this.currentdate.format(this.options.titleformat)}];if(this.table){hParts=[hParts[1],hParts[2],hParts[5],hParts[3],hParts[4],hParts[0]];}
var cal_header=new Element(this.table?'tr':'div',{'class':'calheader'});hParts.each(function(part){var el=new Element(this.table?'td':'div',{'class':part.p});if(part.p=='caltitle'){this.title=el;if(this.table){el.writeAttribute({colspan:2});}
el.update(part.u).observe('click',part.f);}else{if(part.p=='calclose'){el.writeAttribute("title","close");}
el.addClassName('calcontrol');el[typeof(part.u)=='object'?'insert':'update'](part.u).observe('click',part.f);}
cal_header.insert(el);}.bind(this));return cal_header;},_switchCal:function(){if(arguments[1]){var event=arguments[0];var direction=arguments[1];event.date=this.currentdate;}else{var direction=arguments[0];}
var params={f:'setTime',p:this.initDate.getTime()};var sday=this.currentdate.getDate();if(direction!='init'){var d=this.currentdate[direction.include('month')?'getMonth':'getFullYear']();params={f:direction.include('month')?'setMonth':'setYear',p:direction.include('up')?d+1:d-1};}
this.currentdate[params.f](params.p);if(this.currentdate.getDate()!=sday){this.currentdate.setDate(0);}
if(arguments[1]){this.options.oncalchange(event);}
this._update();},_update:function(){this._setCurrentDate(arguments[0]?arguments[0]:this.currentdate);this.title.update(this.currentdate.format(this.options.titleformat));this._buildCal();this._updateTitles();highlightScheduledDate(this.options.scheduleddate,this);},_setCurrentDate:function(date){this.currentdate=new Date(date.getFullYear(),date.getMonth(),date.getDate());this.firstofmonth=this.currentdate.firstofmonth();this.lastofmonth=this.currentdate.lastofmonth();},_getCellIndexByDate:function(d){var findDate=d.getTime();var cellIndex=0;this.dateRange.each(function(dt,i){if(dt.getTime()==findDate){cellIndex=i;throw $break;}});return cellIndex;},destroy:function(){this._emptyCells();if(this.table){this.table.remove();}else{this.cal_weeks_wrapper.remove();}
this.controls.descendants().invoke('stopObserving');[this.cal_wrapper,this.controls].invoke('remove');},setCurrentDate:function(direction){this[(direction instanceof Date)?'_update':'_switchCal'](direction);if(!arguments[1]){this._updateExternal();}
return this.currentdate;},toggleCalendar:function(){this.options[this.element.visible()?'closeeffect':'openeffect'](this.element,{duration:0.05});this.element.update('');if($('additional-items')){$('additional-items').hide();}},getElementByDate:function(d){return this.cells[this._getCellIndexByDate(d)];},getElementsByWeek:function(week){return this.element.select('.weekbox:nth-of-type('+(week+1)+') .daybox:not(.dayboxname)');},getSelectedElement:function(){return this.element.select('.dayselected')[0];},getTodaysElement:function(){return this.element.select('.today')[0];},getDateByElement:function(element){return this.dateRange[this.cells.indexOf(element)];},_setupPlanner:Prototype.emptyFunction,_updatePlanner:Prototype.emptyFunction,openCalendar:function(){if(!this.isOpen()){this.toggleCalendar();}},closeCalendar:function(){if(this.isOpen()){this.toggleCalendar();}},isOpen:function(){return this.element.visible();}};﻿scal.addMethods({_setupPlanner:function(planner){this.planner={};this._eventIndex={deleted:[]};planner.each(function(plan){this._setPlanner(plan);}.bind(this));},_setPlanner:function(plan){var plannerPeriod=Object.isArray(plan.period)?plan.period:(typeof plan.period)=='object'?[plan.period]:[new Date(plan.period)];plannerPeriod.each(function(planDate){if(!this.planner[planDate]){this.planner[planDate]=[];}
if(Object.isString(plan.cls)&&Object.isString(plan.label)){this.planner[planDate].push({cls:['dayboxevent',plan.cls],val:plan.label});this._updateEindex(plan.label,planDate);}else{var cls=Object.isArray(plan.cls)?plan.cls:[plan.cls];var labels=Object.isArray(plan.label)?plan.label:[plan.label];while(cls.size()>labels.size()){labels.push(labels[0]);}
while(labels.size()>cls.size()){cls.push(cls[0]);}
$A($R(0,cls.size()-1)).each(function(v){var label=labels.size()>1?labels.shift():labels[0];this.planner[planDate].push({cls:['dayboxevent',cls.shift()],val:label});this._updateEindex(label,planDate);}.bind(this));}}.bind(this));},_updateEindex:function(val,dt){if(!this._eventIndex[val]){this._eventIndex[val]=[];}
this._eventIndex[val].push(dt);},_updatePlanner:function(day,el){el.innerHTML='';if(this.planner[day]){this.planner[day].each(function(plan){plan.cls.push('highlightitemsdate');});}},_compareMonthYear:function(date1,date2){return Object.isUndefined(['getMonth','getFullYear'].find(function(n){return date1[n]()!=date2[n]();}));},getDatesByEvent:function(evt){var dates=[];if(this._eventIndex[evt]){this._eventIndex[evt].each(function(d){this._eventIndex.deleted=this._eventIndex.deleted.without(d);dates.push(d);}.bind(this));return dates;}
return false;},getEventsByDate:function(d){var pevents=[];if(this.planner[d]){this.planner[d].each(function(p){pevents.push(p.val);});return pevents;}
return false;},getCurrentEvents:function(){var currentMonth=arguments[0]?this.currentdate.getMonth():false;var plannerCheck=function(d){if(currentMonth){return this.planner[d]&&(d.getMonth()==currentMonth)?true:false;}
else{return this.planner[d]?true:false;}}.bind(this);var evts=[];this.dateRange.each(function(d,i){if(plannerCheck(d)){evts.push({dt:d,target:this.cells[i]});}}.bind(this));return evts;},removeEventsByDate:function(d){var cellIndex=this._getCellIndexByDate(d);var el=this.cells[cellIndex].select('.dayboxvalue')[0].up().down();el.removeClassName('highlightitemsdate');removedate=d.format("yyyy-mm-dd");if(this.options.scheduleddate.include(removedate)){delete this.options.scheduleddate[this.options.scheduleddate.indexOf(removedate)]}
this.options.scheduleddate.compact();},getEventElementsByDate:function(d){return this.getElementByDate(d).select('p.dayboxevent');},getEventElementsByWeek:function(week){return this.getElementsByWeek(week).collect(function(e){return e.select('p.dayboxevent');});},getSelectedEvents:function(){var selectedElement=this.getSelectedElement();return Object.isUndefined(selectedElement)?false:selectedElement.select('p.dayboxevent');},getTodaysEvents:function(){return this.getTodaysElement().select('p.dayboxevent');},updateDayValue:function(week,day,value){var planvalues=Object.isArray(value)?value:[value];var planclasses=arguments[3]?Object.isString(arguments[3])?[arguments[3]]:arguments[3]:[];week-=1;day-=1;this.dateRange.eachSlice(7,function(wk,i){if(i==week){this._setPlanner({period:wk[day],cls:planclasses.clone(),label:planvalues.clone()});throw $break}}.bind(this));planclasses.push('dayboxevent');var cellvalue='.cal_day_'+week+'_'+day+'_value';var el=this.element.select(cellvalue)[0];return el;},setPlannerValue:function(year,month,day,value){var planvalues=Object.isArray(value)?value:[value];var plannerdate=new Date();plannerdate.setHours(0,0,0,0);plannerdate.setYear(year);plannerdate.setMonth(month-1,1);plannerdate.setDate(day);var planclasses=arguments[4]?Object.isString(arguments[4])?[arguments[4]]:arguments[4]:[];this._setPlanner({period:plannerdate,cls:planclasses.clone(),label:planvalues.clone()});planclasses.push('highlightitemsdate');if(!this.options.scheduleddate.include(plannerdate.format('ddd, mmm dd, yyyy'))){this.options.scheduleddate.push(plannerdate.format('ddd, mmm dd, yyyy'));}
if(this.dateRange.first()>plannerdate||this.dateRange.last()<plannerdate){return;}
var cellIndex=this._getCellIndexByDate(plannerdate);var el=this.cells[cellIndex].select('.dayboxvalue')[0].up().down();el.addClassName("highlightitemsdate");return el;}});var PlaylistBar=Class.create({playlistType:['Bible Study','Daily Devotional','Reading Plan','Scripture Memory','Sermon Notes'],playlistbar:null,currentPlaylist:null,playlistId:null,itemEditMode:false,list:null,selectedRef:[],access:false,memorizing:false,accordion:null,controlEnabled:false,currentDate:null,newPlaylist:false,initialize:function(widget){this.ebible_widget=widget;this.itemcontent=($('eb-playlist-itemcontent'))?$('eb-playlist-itemcontent'):$('eb-main-box').insert('<div id="eb-playlist-itemcontent"><div id="item-titlebar"><div id="exit-item"></div><div id="playlist-title"></div><ul id="playlist-control" class="playlist-menu"><li><a href="javascript:" id="create-new-item" title="new" class="add-new" href="javascript;"></a></li><li class="calendar"><div id="list-cal" title="calendar"></div></li><li><a id ="prev-item" class="preview-btn" title="previous" href="javascript:"></a></li><li class="totalplaylist"><div></div></li><li><a title="next" id ="next-item" href="javascript:" class="preview-btn"></a></li></ul></div><div id="playlistItemContent"></div></div>').down('#eb-playlist-itemcontent');this.itemcontent.hide();this.playlistbar=($('eb-playlistbar'))?$('eb-playlistbar'):$('eb-main-box').insert('<div id="eb-playlistbar" style="bottom:0px"></div>').down('#eb-playlistbar');this.playlistbar.hide();var playlisttempbar=[];playlisttempbar.push('<div id="playlist-carousel" class="carousel" style="display:block;">');playlisttempbar.push('<a rel="next" class="carousel-control next listbar" href="javascript:">&nbsp;</a><a rel="prev" class="carousel-control prev listbar" href="javascript:">&nbsp;</a>');playlisttempbar.push('<div id="playlist-middle" class="playlist-middle-part"><div id="playlist-scroller" class="playlist-middle-part">');playlisttempbar.push('<ul id="playlist-items">');playlisttempbar.push('</ul></div></div><div id="add-item-button" class="add-item-button"></div></div>');this.playlistbar.update(playlisttempbar.join(""));var temp=[];temp.push('<div id ="playlist-table" class="table-column"><div id="slide-table"></div></div>');Element.update($("playlistItemContent"),temp.join(''));this.ajaxEditorMode=false;$('exit-item').observe('click',function(event){$('calendar-planner-view').hide();$('additional-items').hide();if($$('li.highlight').length>0){element=$$('li.highlight').first().removeClassName('highlight');element.addClassName('item');this._disablePlaylistItemEditing();if(this.access){this._createSortablePlaylist(this.playlistId);}
this._observeListItemElements();this.itemcontent.hide();$('calendar-view').hide();}
else{this.itemcontent.hide();}
if(this.itemEditMode==true){this.itemEditMode=false;}}.bindAsEventListener(this));this._createCalendarPlanner();},loadPlaylist:function(playlist_id,list_ele,swapPanel){this.itemcontent.hide();if($('calendar-planner-view').visible()){$('calendar-planner-view').hide();}
if($('additional-items')){$('additional-items').hide();}
if(!panelSwapper.isPanelVisible('eb-main-box')&&swapPanel!=false){document.location.href=$('verse_state').href;}
if($(list_ele)!=null){$('eb-table-footer').setStyle({bottom:"72px"});$('eb-playlistbar').show();this.ebible_widget._showLoading('eb-playlistbar',$(list_ele).down('a').innerHTML.gsub(/<\/?[^>]*[\w\W]*>/,""));$('loading_message').setStyle({'fontSize':'1.6em','color':'#255C9B'});}
if(this.playlistId==null||this.playlistId!=null&&this.playlistId!=playlist_id){this.newPlaylist=true;var url=this.ebible_widget.options.domain+'/playlists/'+playlist_id+'/playlist_items.json?callback='+this.ebible_widget.options.varName+'.playlist._addPlaylistContents';var transactionObj=YAHOO.util.Get.script(url,{onSuccess:function(o){this.waitingForCallback=false;if(current_user&&$("user-playlist")){$("user-playlist").childElements().each(function(li){if(li.id==list_ele){li.addClassName('selected-playlist');li.down('input[type=radio]').writeAttribute("checked",1);}else{li.removeClassName('selected-playlist');li.down('input[type=radio]').removeAttribute("checked");}});}
this.ebible_widget._hideLoading();this.itemEditMode=false;},onFailure:function(o){alert('Sorry, there was a problem contacting the server. Please try again or contact support@ebible.com');this.waitingForCallback=false;},scope:this});}else{this.ebible_widget._hideLoading();}
if(this.accordion!=null&&this.accordion.showAccordion!=null){this.accordion.deactivate();}},updateCurrentPlaylistCount:function(){$(this.currentPlaylist[0].id+"-count").update("["+this.currentPlaylist[1].length+"]");},_addPlaylistContents:function(playlist,access,selectedId){$("playlist-scroller").setStyle({left:'0px'});this.currentPlaylist=playlist;this.playlistId=this.currentPlaylist[0].id;console.log("ACCESS: "+access);(access)?this.access=true:this.access=false;this.currentDate=this._getFilteredDate(this.currentPlaylist[2]);var temp=[];var tabPanel=[];if(this.currentPlaylist[1].length>0){temp=this._insertPlaylistItems();for(var i=0;i<this.currentPlaylist[1].length;i++){if(this.currentPlaylist[0].type_index!=3){var tempTab=[];tempTab.push('<div id='+"item-table-"+this.currentPlaylist[1][i].id+' class="item-tab">');if(this.currentPlaylist[0].type_index==0||this.currentPlaylist[0].type_index==4){tempTab.push('<div class="row" style="display:none;"><div class="label">Date</div><div id='+"item-schedule-"+this.currentPlaylist[1][i].id+' class="col">'+this._getFilteredDate(this.currentPlaylist[1][i].scheduled_for,true)+'</div></div>');}else{tempTab.push('<div class="row"><div class="label">Date</div><div id='+"item-schedule-"+this.currentPlaylist[1][i].id+' class="col">'+this._getFilteredDate(this.currentPlaylist[1][i].scheduled_for,true)+'</div></div>');}
tempTab.push('<div class="row"><div class="label">Passage</div><div id='+"item-passage-"+this.currentPlaylist[1][i].id+' class="item-passage-col">'+nullToEmpty(this.currentPlaylist[1][i].passage)+'</div></div>');if(this.currentPlaylist[0].type_index==2){tempTab.push('<div class="row" style="display:none;"><div class="label">Title</div><div id='+"item-title-"+this.currentPlaylist[1][i].id+' class="col">'+nullToEmpty(this.currentPlaylist[1][i].title)+'</div></div>');tempTab.push('<div class="row" style="display:none;"><div class="label">Notes</div><div id='+"item-note-"+this.currentPlaylist[1][i].id+' class="col">'+nullToEmpty(this.currentPlaylist[1][i].note)+'</div></div>');}else{tempTab.push('<div class="row"><div class="label">Title</div><div id='+"item-title-"+this.currentPlaylist[1][i].id+' class="col">'+nullToEmpty(this.currentPlaylist[1][i].title)+'</div></div>');tempTab.push('<div class="row"><div class="label">Notes</div><div id='+"item-note-"+this.currentPlaylist[1][i].id+' class="col notes">'+nullToEmpty(this.currentPlaylist[1][i].note)+'</div></div>');}
if(this.access)
tempTab.push('<div class="row"><div class="label"></div><div class="col"><span id='+"edit-item-"+this.currentPlaylist[1][i].id+' class="item-edit" title="click to edit details">Edit</span><img id='+"edit-item-loading-"+this.currentPlaylist[1][i].id+' class="edit-item-loading"  style="display: none;" src="/images/spinner.gif" alt="processing"/></div></div>');tempTab.push('</div>');tabPanel.push(tempTab.join(""));$('slide-table').update(tabPanel.join(""));$$('.item-tab').each(function(tab){tab.setStyle({width:$('eb-playlistbar').getWidth()+'px'});});var slidepanelwidth=$$('.item-tab').length>0?$('eb-playlistbar').getWidth()*this.currentPlaylist[1].length+"px":"inherit";$('slide-table').setStyle({width:slidepanelwidth});$('playlist-title').update(this.playlistType[this.currentPlaylist[0].type_index]+" - "+this.currentPlaylist[0].name);}}}
else{temp.push('<li class="empty"> Drag here from your selected verses</li>');}
this.list=$("playlist-items");Element.update(this.list,temp.join(''));$$('.item-passage-col').each(function(passageLink){passageLink.observe('click',function(e){document.location.href="#"+passageLink.innerHTML;});});$$('.delete').each(function(del){del.show();});if(!this.playlistbar.visible()){this.playlistbar.show();}
this._observeListItemElements();this._buildCarouselList();if(this.access){this._createSortablePlaylist();if(!this.controlEnabled){this._enablePlaylistItemControls();this._displayCalendarPlanner();}}else{$('create-new-item').hide();$('add-item-button').hide();$('list-cal').hide();}
if(selectedId&&this.currentPlaylist[0].type_index!=3){this._highlightPlaylistItem(selectedId);var index=$('playlist-items').childElements().indexOf($$('li.highlight').first());this._updateTotalPlaylist();}
this._observeUpdateButtons();},_insertSinglePlaylistItem:function(playlist){var lastEle=$('playlist-items').select('li.item').last();var eleId=lastEle?lastEle.id:"";this._addPlaylistContents(playlist,true,eleId);this._highlightPlaylistItem($('playlist-items').select('li.item').last().id);if(this.currentPlaylist[0].type_index!=3){this.contentCarousel.moveTo("item-table-"+$$('li.highlight').first().id.gsub("drop_",""));}
else{this.itemcontent.hide();}
this.updateCurrentPlaylistCount();this._updateTotalPlaylist();},_insertPlaylistItems:function(){this.selectedRef=[];var itemtemp=[];for(var i=0;i<this.currentPlaylist[1].length;i++){var content="";if(this.currentPlaylist[1][i].title!=null&&this.currentPlaylist[1][i].title.length>0){content=this.currentPlaylist[1][i].title;}
else if((this.currentPlaylist[1][i].title==null||this.currentPlaylist[1][i].title.length==0)&&this.currentPlaylist[1][i].note!=null){content=this.currentPlaylist[1][i].note;}
if(this.currentPlaylist[0].type_index==1||this.currentPlaylist[0].type_index==0){itemtemp.push('<li class="item" id='+"drop_"+this.currentPlaylist[1][i].id+'><div class="item"><div class="ref">'+this.currentPlaylist[1][i].short_ref+'</div><div class="delete" title="delete">x</div></div><a class="carousel-jumper effects" rel='+"item-table-"+this.currentPlaylist[1][i].id+' title="click to see details"><div class="notes">'+content+'</div></a></li>');}
else if(this.currentPlaylist[0].type_index==2||this.currentPlaylist[0].type_index==1){itemtemp.push('<li class="item" id='+"drop_"+this.currentPlaylist[1][i].id+'><div class="item"><div class="ref readings">'+this._getFilteredDate(this.currentPlaylist[1][i].scheduled_for)+'</div><div class="delete" title="delete">x</div></div><a href="javascript:" class="carousel-jumper effects" rel='+"item-table-"+this.currentPlaylist[1][i].id+' title="click to see details"><div class="notes readings">'+this.currentPlaylist[1][i].passage+'</div></a></li>');}
else if(this.currentPlaylist[0].type_index==3){itemtemp.push('<li class="item" id='+"drop_"+this.currentPlaylist[1][i].id+'><div class="item"><div class="ref">'+this.currentPlaylist[1][i].short_ref+'</div><div class="delete" title="delete">x</div></div><a class="carousel-jumper effects" rel='+"item-table-"+this.currentPlaylist[1][i].id+' ><div class="notes">'+this.currentPlaylist[1][i].note+'</div></a></li>');var item=new Hash();item.ref=this.currentPlaylist[1][i].short_ref;this.selectedRef.push(item);}
else if(this.currentPlaylist[0].type_index==4){itemtemp.push('<li class="item" id='+"drop_"+this.currentPlaylist[1][i].id+'><div class="item"><div class="ref readings">'+this.currentPlaylist[1][i].short_ref+'</div><div class="delete" title="delete">x</div></div><a class="carousel-jumper effects" rel='+"item-table-"+this.currentPlaylist[1][i].id+'><div class="notes readings">'+content+'</div></a></li>');}}
itemtemp.push('<li class="droppable"></li>');return itemtemp;},_observeUpdateButtons:function(tabId){if(tabId){var imgID=tabId;$('edit-item-'+tabId).observe('click',function(event){new Ajax.Updater('item-table-'+tabId,'/playlists/'+this.currentPlaylist[0].id+'/playlist_items/'+tabId+'/edit',{method:'get',onLoading:function(){$('edit-item-loading-'+imgID).show();}.bind(this),onComplete:function(){$('edit-item-loading-'+imgID).hide();}.bind(this)});}.bindAsEventListener(this));}
else{$$('.item-edit').each(function(btn){btn.observe('click',function(event){var tabId=btn.id.gsub("edit-item-","");new Ajax.Updater('item-table-'+tabId,'/playlists/'+this.currentPlaylist[0].id+'/playlist_items/'+tabId+'/edit',{method:'get',onLoading:function(){$('edit-item-loading-'+btn.id.gsub("edit-item-","")).show();}.bind(this),onComplete:function(){$('edit-item-loading-'+btn.id.gsub("edit-item-","")).hide();}.bind(this),onSuccess:function(){this.itemEditMode=true;}.bind(this)});}.bindAsEventListener(this));}.bind(this));}},_insertItemTable:function(){var index=$('playlist-items').childElements().indexOf($$('li.highlight').first());var tempTab=[];if(this.currentPlaylist[0].type_index==0||this.currentPlaylist[0].type_index==4){tempTab.push('<div class="row" style="display:none;"><div class="label">Date</div><div id='+"item-schedule-"+this.currentPlaylist[1][index].id+' class="col">'+this._getFilteredDate(this.currentPlaylist[1][index].scheduled_for,true)+'</div></div>');}else{tempTab.push('<div class="row"><div class="label">Date</div><div id='+"item-schedule-"+this.currentPlaylist[1][index].id+' class="col">'+this._getFilteredDate(this.currentPlaylist[1][index].scheduled_for,true)+'</div></div>');}
tempTab.push('<div class="row"><div class="label">Passage</div><div id='+"item-passage-"+this.currentPlaylist[1][index].id+' class="item-passage-col">'+nullToEmpty(this.currentPlaylist[1][index].passage)+'</div></div>');if(this.currentPlaylist[0].type_index==2){tempTab.push('<div class="row" style="display:none;"><div class="label">Title</div><div id='+"item-title-"+this.currentPlaylist[1][index].id+' class="col">'+nullToEmpty(this.currentPlaylist[1][index].title)+'</div></div>');tempTab.push('<div class="row" style="display:none;"><div class="label">Notes</div><div id='+"item-note-"+this.currentPlaylist[1][index].id+' class="col">'+nullToEmpty(this.currentPlaylist[1][index].note)+'</div></div>');}else{tempTab.push('<div class="row"><div class="label">Title</div><div id='+"item-title-"+this.currentPlaylist[1][index].id+' class="col">'+nullToEmpty(this.currentPlaylist[1][index].title)+'</div></div>');tempTab.push('<div class="row"><div class="label">Notes</div><div id='+"item-note-"+this.currentPlaylist[1][index].id+' class="col notes">'+nullToEmpty(this.currentPlaylist[1][index].note)+'</div></div>');}
tempTab.push("<div style='clear:both'>&nbsp;</div>");tempTab.push('<div class="row"><div class="label"></div><div class="col"><span id='+"edit-item-"+this.currentPlaylist[1][index].id+' class="item-edit" title="click to edit details">Edit</span><img id='+"edit-item-loading-"+this.currentPlaylist[1][index].id+' class="edit-item-loading"  style="display: none;" src="/images/spinner.gif" alt="processing"/></div></div>');$('item-table-'+this.currentPlaylist[1][index].id).update(tempTab.join(""));this._observeUpdateButtons(this.currentPlaylist[1][index].id);this.itemEditMode=false;$("item-passage-"+this.currentPlaylist[1][index].id).observe('click',function(){document.location.href="#"+$("item-passage-"+this.currentPlaylist[1][index].id).innerHTML;}.bind(this));},_removePlaylistContents:function(playlistID){if(this.playlistId==playlistID){$('eb-playlistbar').hide();$('eb-playlist-itemcontent').hide();windowResized();}
$('playlist-'+playlistID).remove();},_enablePlaylistItemControls:function(){$('add-item-button').stopObserving('click');$('create-new-item').stopObserving('click');if(this.currentPlaylist[0].type_index==2||this.currentPlaylist[0].type_index==1){$('list-cal').show();}else{$('list-cal').hide();}
$('create-new-item').show();$('add-item-button').show();$('add-item-button').observe('click',function(){this._createBlankPlaylistItem();}.bindAsEventListener(this));$('create-new-item').observe('click',function(){this._createBlankPlaylistItem();}.bindAsEventListener(this));},_createCalendarPlanner:function(){var options=Object.extend({titleformat:'mmmm yyyy',closebutton:'x',dayheadlength:2,weekdaystart:0,planner:[],scheduleddate:[]},arguments[0]||{});this.playlistcal=new scal('calendar-planner-view',"",options);},_displayCalendarPlanner:function(){$('list-cal').observe("click",function(){if($('calendar-planner-view').childElements().length<1){this._createCalendarPlanner();}
var dates=[];this.currentPlaylist[1].each(function(item){dates.push(this._getFilteredDate(item.scheduled_for))}.bind(this));var cposition=$('list-cal').cumulativeOffset();$('calendar-planner-view').setStyle({position:'absolute',zIndex:'999999',top:(cposition[1]+25)+'px',right:'11px'});this.playlistcal.options.scheduleddate=[];$$('.highlightitemsdate').invoke('removeClassName','highlightitemsdate');highlightScheduledDate(dates,this.playlistcal);Effect.toggle($('calendar-planner-view'),'appear',{delay:0.3,duration:0.3});}.bindAsEventListener(this));},_createBlankPlaylistItem:function(){$$('div.item-tab').each(function(ele){ele.setStyle({visibility:'hidden'});});this.itemcontent.show();if($('item-table-blank')){$('item-table-blank').remove();}
$('slide-table').insert('<div id="item-table-blank" class="item-tab"></div>');if(this.currentPlaylist[0].type_index!=3&&this.contentCarousel){this.contentCarousel.slides.push($('item-table-blank'));}
$('playlist-title').update(this.playlistType[this.currentPlaylist[0].type_index]+" - "+this.currentPlaylist[0].name);var url=this.ebible_widget.options.domain+'/playlists/'+this.currentPlaylist[0].id+'/playlist_items/new.js';new Ajax.Updater('item-table-blank',url,{method:'get',onLoading:function(){this.ebible_widget._showLoading('playlist-table','Loading...');}.bind(this),onComplete:function(){this.ebible_widget._hideLoading();this.contentCarousel.moveTo($('item-table-blank'));}.bind(this),onSuccess:function(transport){}.bind(this)});},_makeItemTableVisible:function(){this.itemcontent.hide();if(this.currentPlaylist[0].type_index!=3){this.contentCarousel.slides=this.contentCarousel.slides.without($('item-table-blank'));$$('div.item-tab').each(function(ele){ele.setStyle({visibility:'visible'});});}
$('item-table-blank').remove();},_buildCarouselList:function(){$('next-item').stopObserving('click');$('prev-item').stopObserving('click');if(this.carousel&&this.contentCarousel){this.carousel.destroy();this.contentCarousel.destroy();}
if($$('li.item').length>0){this.carousel=new Carousel($('playlist-scroller'),$('playlist-carousel').down('.playlist-middle-part').select('li.item'),$('playlist-carousel').select('a.listbar'),{duration:0.5,transition:'spring',visibleSlides:parseInt($('playlist-middle').getWidth()/$$('li.item')[0].getWidth()),circular:false,carouselFor:'playlistbar'});if(this.newPlaylist){this.carousel.first();}}
this._setDroppablePlaylistbarWidth();if(this.currentPlaylist[0].type_index!=3&&$$('li.item').length>0){this.contentCarousel=new Carousel($('playlist-table'),$$('.item-tab'),$$('#playlist-items li.item a.effects'),{duration:0.5,wheel:false,carouselFor:'control'});$('next-item').observe('click',function(){if(($('playlist-items').childElements().indexOf($$('li.highlight').first())+1)<($('playlist-items').select('li.item').length)){var response=null;if(this.itemEditMode){response=confirm("You are currently editing a playlist item. Abandon changes?");if(response){this._insertItemTable();this.contentCarousel.next();this._loadNextPlaylistItem();this.itemEditMode=false;}}else{this.contentCarousel.next();this._loadNextPlaylistItem();}}}.bind(this));$('prev-item').observe('click',function(){var response=null;if(this.itemEditMode){response=confirm("You are currently editing a playlist item. Abandon changes?");if(response){this._insertItemTable();this.contentCarousel.prev();this._loadPrevPlaylistItem();this.itemEditMode=false;}}else{this.contentCarousel.prev();this._loadPrevPlaylistItem();}}.bind(this));}},_updateSingleItem:function(playlist_item){this.currentPlaylist[1][parseInt(playlist_item.position)-1]=playlist_item;this._insertItemTable();this._addPlaylistContents(this.currentPlaylist,this.access,"drop_"+playlist_item.id);},_observeListItemElements:function(){var playlistItemNote=$$('#playlist-items li a');var playlistItems=$$('#playlist-items li[id]');index=0;playlistItemNote.each(function(elem){var id=playlistItems[index].id.replace("drop_","");elem.observe('click',function(event){if(this.currentPlaylist[0].type_index!=3&&$$('li.item').length>0){$('item-table-'+elem.up('li').id.gsub('drop_','')).show();if(!this.itemcontent.visible()){this.itemcontent.show();}}
var idx=null;if(!this.itemEditMode){this._highlightPlaylistItem(elem.up('li').id);idx=$('playlist-items').childElements().indexOf($$('li.highlight').first());if(this.currentPlaylist[0].type_index==3){this._disablePlaylistItemEditing();this.itemcontent.hide();this.memorizing=true;this.ebible_widget.toolbar.memorizeAction('playlist');if(current_user&&current_user.membership_level_id>=10){this.ebible_widget.toolbar.memorize.passageTextReceived(this.currentPlaylist[1][idx].note,this.currentPlaylist[1][idx].passage);}}
this._updateTotalPlaylist();}
if($('additional-items').visible()){if($('additional-items').down().id.gsub("day-","")!=this.currentPlaylist[1][idx].scheduled_for){$('additional-items').hide();}}}.bind(this));index+=1;}.bind(this));var playlistDeleteButtons=$$('#playlist-items div.delete');var totalItems=playlistDeleteButtons.length;if(this.access){playlistDeleteButtons.each(function(ele){Event.stopObserving(ele);ele.observe('click',this._deletePlaylistItem.bind(this,ele));if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ele.observe('mousedown',this._deletePlaylistItem.bind(this,ele));}}.bind(this));}else{$$('.delete').each(function(del){del.hide();});}},_deletePlaylistItem:function(ele){var id=ele.up('li').id;var itemId=id.gsub('drop_','');new Effect.DropOut(id,{duration:2.0});new Ajax.Request('/playlists/'+this.playlistId+'/playlist_items/'+ele.up('li').id.gsub('drop_',''),{asynchronous:true,evalScripts:true,method:'delete',parameters:{playlist_items_id:itemId},onSuccess:function(transport){if(ele.up('li').hasClassName("highlight")){if(ele.up('li').next()&&ele.up('li').next().hasClassName('droppable')==false){ele.up('li').next().addClassName('highlight');}
else if(ele.up('li').previous()){ele.up('li').previous().addClassName('highlight');}}
if(this.currentPlaylist[0].type_index==1||this.currentPlaylist[0].type_index==2){var dateString=$('drop_'+itemId).down('div.ref').innerHTML;if(!dateString=="Date"||!dateString==""){this.playlistcal.options.scheduleddate=this.playlistcal.options.scheduleddate.without(dateString);this.playlistcal.removeEventsByDate(new Date(dateString));}}
this.carousel.slides=this.carousel.slides.without($("drop_"+itemId));if(this.itemcontent.visible())
this.contentCarousel.slides=this.contentCarousel.slides.without($("item-table-"+itemId));playlist=transport.responseText.evalJSON();this.currentPlaylist=playlist;this.updateCurrentPlaylistCount();if($(id)==this.carousel.current){var next_ele=$(id).next();if(next_ele){this.carousel.current=next_ele;}else if($(id).previous()){this.carousel.current=$(id).previous();}}
$(id).remove();if($$('li.highlight').length>0&&this.itemcontent.visible()){this._showNewItemAfterDelete(itemId);this._updateTotalPlaylist();}
if($('playlist-items').select('li.item').length<1){this.itemcontent.hide();$('playlist-items').update('<li class="empty"> Drag here from your selected verses</li>');this._createSortablePlaylist();}
this._setDroppablePlaylistbarWidth();}.bind(this)});},_showNewItemAfterDelete:function(playlist_item_id){if(this.currentPlaylist[0].type_index!=3){$('item-table-'+playlist_item_id).remove();var bwidth=96*$('playlist-items').childElements().length;var pwidth=$('slide-table').down().getWidth()*$('slide-table').childElements().length;$('playlist-items').setStyle({width:bwidth+"px"});$('slide-table').setStyle({width:pwidth+"px"});this.contentCarousel.moveTo("item-table-"+$$('li.highlight').first().id.gsub("drop_",""));}},_ajaxInplaceEditorEditMode:function(){this.ajaxEditorMode=true;if(this.currentPlaylist[0].type_index!=3){Sortable.destroy('playlist-items');}},_disablePlaylistItemEditing:function(){if(this.access){this._createSortablePlaylist();}
this.ajaxEditorMode=false;},_createSortablePlaylist:function(){Sortable.destroy('playlist-items');Sortable.create('playlist-items',{tag:'li',tree:true,treeTag:'ul',containment:['playlist-items','side-holder','bible-table-columns'],constraint:false,overlap:'horizontal',dropOnEmpty:true,ghosting:false,onUpdate:function(ele){if($('playlist-items').childElements().length>1){new Ajax.Request('/playlists/order',{asynchronous:true,evalScripts:true,parameters:{playlist_id:this.playlistId,data:Sortable.serialize("playlist-items")},onLoading:function(){this.ebible_widget._showLoading('playlist-carousel','sorting...');$('loading_message').setStyle({'fontSize':'1.6em'});}.bind(this),onComplete:function(transport){this.currentPlaylist=transport.responseText.evalJSON();if($$('li.highlight').length>0){this._addPlaylistContents(this.currentPlaylist,this.access,$$('li.highlight').first().id);}else{this._addPlaylistContents(this.currentPlaylist,this.access);}
this.ebible_widget._hideLoading();}.bind(this)});$$('#playlist-control li.totalplaylist div').first().update(($('playlist-items').childElements().indexOf($$('li.highlight').first())+1)+'/'+$('playlist-items').childElements().length);}}.bind(this)});},_highlightPlaylistItem:function(id){var playlistItems=$('playlist-items').select('li.item');playlistItems.each(function(elem){if(id==elem.id){$(elem.id).addClassName('highlight');}
else{$(elem.id).removeClassName('highlight');}});if(playlistItems.indexOf($$('li.highlight').first())==playlistItems.length-1&&playlistItems.length>this.carousel.options.visibleSlides){this.carousel.current=playlistItems.last().previous(this.carousel.options.visibleSlides-2)
this.carousel.next();this.carousel.disableNextBtn();}},_loadPrevPlaylistItem:function(){if($$('li.highlight').length>0&&$$('li.highlight').first().previous()){this._highlightPlaylistItem($$('li.highlight').first().previous().id);this._updateTotalPlaylist(($$('li.highlight').first().previous())?$$('li.highlight').first().previous():$$('li.highlight').first());var extremeRightPos=$$(".playlist-middle-part")[0].cumulativeOffset()[0];var viewportOffset=$$("li.highlight")[0].viewportOffset($$('.playlist-middle-part'))[0];if(viewportOffset<extremeRightPos){this.carousel.prev();}}},_loadNextPlaylistItem:function(){if($$('li.highlight').length>0&&$$('li.highlight').first().next()){this._highlightPlaylistItem($$('li.highlight').first().next().id);this._updateTotalPlaylist();var extremeLeftPos=$$(".playlist-middle-part")[0].getWidth()+$$(".playlist-middle-part")[0].cumulativeOffset()[0];var viewportOffset=$$("li.highlight")[0].viewportOffset($$('.playlist-middle-part'))[0];if((extremeLeftPos-92)<viewportOffset){this.carousel.next();}}},_updateTotalPlaylist:function(playlistItem){if(playlistItem){$$('#playlist-control li.totalplaylist div')[0].update((playlistItem.up().childElements().indexOf($$('li.highlight').first())+1)+'/'+$('playlist-items').select('li.item').length);}else{$$('#playlist-control li.totalplaylist div')[0].update(($('playlist-items').childElements().indexOf($$('li.highlight').first())+1)+'/'+$('playlist-items').select('li.item').length);}},_getFilteredDate:function(scheduled_for,empty){if(scheduled_for){date=new Date(new RegExp(/(\d{4}\-\d{2}\-\d{2})/).exec(scheduled_for)[1].gsub('-','/'));return date.format('ddd, mmm dd, yyyy');}
if(empty){return"";}
else{return"<i>Date</i>";}},_updateCalendarDates:function(mode,scheduled_date,old_scheduled){var scheduled=this._getFilteredDate(scheduled_date);if(this.playlistcal&&this.currentPlaylist[0].type_index==1||this.currentPlaylist[0].type_index==2){if(!mode&&!this.playlistcal.options.scheduleddate.include(scheduled)){highlightScheduledDate([scheduled],this.playlistcal)}else{var old_schedule=this._getFilteredDate(old_scheduled);this.playlistcal.removeEventsByDate(new Date(old_schedule));this.playlistcal.options.scheduleddate=this.playlistcal.options.scheduleddate.without(old_schedule);highlightScheduledDate([scheduled],this.playlistcal);this.playlistcal.options.scheduleddate.push(scheduled);}}},_showPlaylistEditForm:function(verseRef,currentPackId,position,action){var playlist=this.currentPlaylist;highlightItemId="drop_"+playlist[1][position-1].id;access=this.access;this._addPlaylistContents(playlist,access,highlightItemId);if(this.currentPlaylist[0].type_index!=3){var params=(action=='verseDrag')?"from=verseDrag":"from=editMode";new Ajax.Updater('item-table-'+playlist[1][position-1].id,'/playlists/'+currentPackId+'/playlist_items/'+playlist[1][position-1].id+'/edit',{method:'get',asynchronous:true,evalScripts:true,parameters:params,onComplete:function(transport){this.itemcontent.show();this.contentCarousel.moveTo($('item-table-'+playlist[1][position-1].id));}.bindAsEventListener(this)});}
this.updateCurrentPlaylistCount();},_adjustMultiple:function(multiple_records){var ele=[];var count=1;if(multiple_records.length>0){ele.push("<div id='day-"+multiple_records[0].scheduled_for+"'");multiple_records.each(function(item){ele.push("<div id='add-"+item.id+"' title='"+item.short_ref+"' class='add-item'>"+count+"</div>");count+=1;});ele.push("<div class='add-item-info'>Additional Records</div><div class='add-item-close' title='close'>x</div></div>");$('additional-items').update(ele.join(""));var cposition=$('eb-playlistbar').cumulativeOffset();$('additional-items').setStyle({position:'absolute',zIndex:'999999',bottom:'80px',right:'12px'});$('additional-items').show();$$('div.add-item').each(function(ele){ele.observe("click",function(){this.contentCarousel.moveTo($('item-table-'+ele.id.gsub('add-','')));this._highlightPlaylistItem('drop_'+ele.id.gsub('add-',''));}.bindAsEventListener(this));}.bind(this));$$('div.add-item-close').first().observe('click',function(){$('additional-items').hide();});}},_setDroppablePlaylistbarWidth:function(){var liWidth=($('playlist-items').childElements().length-1)*93;if($$('.playlist-middle-part').first().getWidth()>liWidth&&$('playlist-items').down('li.droppable')){$('playlist-items').setStyle({width:$('playlist-middle').getWidth()+'px'});var droppableWidth=$('playlist-middle').getWidth()-liWidth;$('playlist-items').down('li.droppable').setStyle({width:droppableWidth+'px'});$('playlist-scroller').setStyle({width:$('playlist-middle').getWidth()+"px"});}else if($$('.playlist-middle-part').first().getWidth()>liWidth){$('playlist-items').setStyle({width:$('playlist-middle').getWidth()+'px'});$('playlist-scroller').setStyle({width:$('playlist-middle').getWidth()+"px"});}else{$('playlist-items').setStyle({width:liWidth+'px'});$('playlist-scroller').setStyle({width:liWidth+"px"});}},verseExist:function(playlist_id,verseRef,title,note,date,position,type_id,action){if(confirm("Verse Reference Already Exists. Do you still want to add it.")){if(action=="create"){var params='playlist_item[passage]='+verseRef+'&playlist_item[title]='+title+'&playlist_item[note]='+note+'&playlist_item[date]='+date+'&playlist_item[position]='+position+'&playlist_item[type]='+type_id;var ajaxCreate=new Ajax.Request('/playlists/'+playlist_id+'/playlist_items',{method:'post',asynchronous:true,evalScripts:true,parameters:params});}
else{var params='playlist_item[passage]='+verseRef+'&playlist_item[title]='+title+'&playlist_item[note]='+note+'&playlist_item[date]='+date+'&playlist_item[position]='+position+'&playlist_item[id]='+type_id;var ajaxCreate=new Ajax.Request('/playlists/'+playlist_id+'/playlist_items/'+type_id,{method:'put',asynchronous:true,evalScripts:true,parameters:params});}}
else{this._insertItemTable();return false;}}});function showcalendars(dates){var options=Object.extend({titleformat:'mmmm yyyy',closebutton:'x',dayheadlength:2,weekdaystart:0,planner:[]},arguments[0]||{});popup=new scal('calendar-view',updateyear,options);}
function highlightScheduledDate(dates,calendar){if(dates){dates.each(function(dts){if(dts!=undefined){var itd=new Date(dts).format("yyyy-mm-dd");if(!itd.gsub("&nbsp;","").empty()){var ymd=itd.split("-");calendar.setPlannerValue(ymd[0],ymd[1],ymd[2],"",'highlightitemsdate');}}});}}
function switchcalendar(form){var d=new Date($F('switchyear'),$F('switchmonth'),$F('switchday'));popup.setCurrentDate(d);}
function buildcalendar(form){var inputs=form.getInputs();var options={};inputs.each(function(n){var id=n.getAttribute('id');if(id=='exactweeks'){var val=n.checked;}else{var val=n.value;}
if(/^\d+$/.test(val)){val=new Number(val);}
options[id]=val;});popup.destroy();createDatePickerCalendar(options);}
function updateyear(d){$('playlist_item_scheduled_for').value=(d.format('yyyy-mm-dd'));$('calendar-view').update('');}
function explodeday(){$(popup).setCurrentDate(popup.selecteddate);$(popup).buildCalendar();$(popup).getCalendar();$(popup.baseelement).update();$(popup.baseelement).appendChild(popup.selecteddatecell);}
function displayDatePicker(){var options=Object.extend({titleformat:'mmmm yyyy',closebutton:'x',dayheadlength:1,weekdaystart:0},arguments[0]||{});popup=new scal('calendar-view',updateyear,options);var cposition=$('popup-calendar').cumulativeOffset();var csposition=$('popup-calendar').cumulativeScrollOffset();$('calendar-view').setStyle({position:'absolute',zIndex:'999999',top:(cposition[1])+'px',left:(cposition[0]-csposition[0])+'px'});$('calendar-view').show();}
function closePlaylistForm(){Effect.BlindUp('create-playlist',{duration:1.0});Effect.Appear('create-new',{duration:1.0});}
function displayPlaylistForm(){Effect.Fade('create-new',{duration:1.0});Effect.BlindDown('create-playlist',{duration:1.0});if($('playlist-instruction').visible){$('playlist-instruction').hide();}}
function displayPlaylistEditForm(){$('user-playlist-container').hide();Effect.Fade('create-new',{duration:1.0});Effect.BlindDown('update-playlist',{duration:1.0});}
function closePlaylistEditForm(){Effect.BlindUp('update-playlist',{duration:1.0});Effect.Appear('create-new',{duration:1.0});$('user-playlist-container').show();}
function nullToEmpty(content){if(content!=null){return content;}else{return"";}}