//Packed with AutoPacker - http://thepcspy.com/autopacker
//Packed at 1291041756
//See unpacked.js for more details including copyright


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){
element=$(element);
var op=element.offsetParent,body=document.body,docEl=document.documentElement;


if(op&&op!==docEl)return $(op);
if(op===docEl||element===docEl||element===body)return $(body);

while((element=element.parentNode)&&element!==body)
if(Element.getStyle(element,'position')!='static')
return $(element);

return $(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 hs={

lang:{
cssDirection:'ltr',
loadingText:'Loading...',
loadingTitle:'Click to cancel',
focusTitle:'Click to bring to front',
fullExpandTitle:'Expand to actual size (f)',
creditsText:'Powered by <i>Highslide JS</i>',
creditsTitle:'Go to the Highslide JS homepage',
previousText:'Previous',
nextText:'Next',
moveText:'Move',
closeText:'Close',
closeTitle:'Close (esc)',
resizeTitle:'Resize',
playText:'Play',
playTitle:'Play slideshow (spacebar)',
pauseText:'Pause',
pauseTitle:'Pause slideshow (spacebar)',
previousTitle:'Previous (arrow left)',
nextTitle:'Next (arrow right)',
moveTitle:'Move',
fullExpandText:'1:1',
restoreTitle:'Click to close image, click and drag to move. Use arrow keys for next and previous.'
},

graphicsDir:'highslide/graphics/',
expandCursor:'zoomin.cur',
restoreCursor:'zoomout.cur',
expandDuration:250,
restoreDuration:250,
marginLeft:15,
marginRight:15,
marginTop:15,
marginBottom:15,
zIndexCounter:1001,
loadingOpacity:0.75,
allowMultipleInstances:true,
numberOfImagesToPreload:5,
outlineWhileAnimating:2,
outlineStartOffset:3,
padToMinWidth:false,
fullExpandPosition:'bottom right',
fullExpandOpacity:1,
showCredits:true,
creditsHref:'http://highslide.com/',
creditsTarget:'_self',
enableKeyListener:true,
openerTagNames:['a'],

allowWidthReduction:false,
allowHeightReduction:true,
preserveContent:true,
objectLoadTime:'before',
cacheAjax:true,
anchor:'auto',
align:'auto',
targetX:null,
targetY:null,
dragByHeading:true,
minWidth:200,
minHeight:200,
allowSizeReduction:true,
outlineType:'drop-shadow',skin:{
contentWrapper:
'<div class="highslide-header"><ul>'+
'<li class="highslide-previous">'+
'<a href="#" title="{hs.lang.previousTitle}" onclick="return hs.previous(this)">'+
'<span>{hs.lang.previousText}</span></a>'+
'</li>'+
'<li class="highslide-next">'+
'<a href="#" title="{hs.lang.nextTitle}" onclick="return hs.next(this)">'+
'<span>{hs.lang.nextText}</span></a>'+
'</li>'+
'<li class="highslide-move">'+
'<a href="#" title="{hs.lang.moveTitle}" onclick="return false">'+
'<span>{hs.lang.moveText}</span></a>'+
'</li>'+
'<li class="highslide-close">'+
'<a href="#" title="{hs.lang.closeTitle}" onclick="return hs.close(this)">'+
'<span>{hs.lang.closeText}</span></a>'+
'</li>'+
'</ul></div>'+
'<div class="highslide-body"></div>'+
'<div class="highslide-footer"><div>'+
'<span class="highslide-resize" title="{hs.lang.resizeTitle}"><span></span></span>'+
'</div></div>'
},




preloadTheseImages:[],
continuePreloading:true,
expanders:[],
overrides:[
'allowSizeReduction',
'useBox',
'anchor',
'align',
'targetX',
'targetY',
'outlineType',
'outlineWhileAnimating',
'captionId',
'captionText',
'captionEval',
'captionOverlay',
'headingId',
'headingText',
'headingEval',
'headingOverlay',
'creditsPosition',
'dragByHeading',

'width',
'height',

'contentId',
'allowWidthReduction',
'allowHeightReduction',
'preserveContent',
'maincontentId',
'maincontentText',
'maincontentEval',
'objectType',
'cacheAjax',
'objectWidth',
'objectHeight',
'objectLoadTime',
'wrapperClassName',
'minWidth',
'minHeight',
'maxWidth',
'maxHeight',
'slideshowGroup',
'easing',
'easingClose',
'fadeInOut',
'src'
],
overlays:[],
idCounter:0,
oPos:{
x:['leftpanel','left','center','right','rightpanel'],
y:['above','top','middle','bottom','below']
},
mouse:{},
headingOverlay:{},
captionOverlay:{},
timers:[],

pendingOutlines:{},
sleeping:[],
preloadTheseAjax:[],
cacheBindings:[],
cachedGets:{},
clones:{},
onReady:[],
uaVersion:parseFloat((navigator.userAgent.toLowerCase().match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,'0'])[1]),
ie:(document.all&&!window.opera),
safari:/Safari/.test(navigator.userAgent),
geckoMac:/Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent),

$:function(id){
if(id)return document.getElementById(id)},

push:function(arr,val){
arr[arr.length]=val},

createElement:function(tag,attribs,styles,parent,nopad){
var el=document.createElement(tag);
if(attribs)hs.extend(el,attribs);
if(nopad)hs.setStyles(el,{padding:0,border:'none',margin:0});
if(styles)hs.setStyles(el,styles);
if(parent)parent.appendChild(el);
return el},

extend:function(el,attribs){
for(var x in attribs)el[x]=attribs[x];
return el},

setStyles:function(el,styles){
for(var x in styles){
if(hs.ie&&x=='opacity'){
if(styles[x]>0.99)el.style.removeAttribute('filter');
else el.style.filter='alpha(opacity='+(styles[x]*100)+')'}
else el.style[x]=styles[x]}
},
animate:function(el,prop,opt){
var start,
end,
unit;
if(typeof opt!='object'||opt===null){
var args=arguments;
opt={
duration:args[2],
easing:args[3],
complete:args[4]
}}
if(typeof opt.duration!='number')opt.duration=250;
opt.easing=Math[opt.easing]||Math.easeInQuad;
opt.curAnim=hs.extend({},prop);
for(var name in prop){
var e=new hs.fx(el,opt,name);

start=parseFloat(hs.css(el,name))||0;
end=parseFloat(prop[name]);
unit=name!='opacity'?'px':'';

e.custom(start,end,unit)}
},
css:function(el,prop){
if(document.defaultView){
return document.defaultView.getComputedStyle(el,null).getPropertyValue(prop)}else{
if(prop=='opacity')prop='filter';
var val=el.currentStyle[prop.replace(/\-(\w)/g,function(a,b){return b.toUpperCase()})];
if(prop=='filter')
val=val.replace(/alpha\(opacity=([0-9]+)\)/,
function(a,b){return b/100});
return val===''?1:val}
},

getPageSize:function(){
var d=document,w=window,iebody=d.compatMode&&d.compatMode!='BackCompat'
?d.documentElement:d.body;

var width=hs.ie?iebody.clientWidth:
(d.documentElement.clientWidth||self.innerWidth),
height=hs.ie?iebody.clientHeight:self.innerHeight;

hs.page={
width:width,
height:height,
scrollLeft:hs.ie?iebody.scrollLeft:pageXOffset,
scrollTop:hs.ie?iebody.scrollTop:pageYOffset
}
},

getPosition:function(el){
var p={x:el.offsetLeft,y:el.offsetTop};
while(el.offsetParent){
el=el.offsetParent;
p.x+=el.offsetLeft;
p.y+=el.offsetTop;
if(el!=document.body&&el!=document.documentElement){
p.x-=el.scrollLeft;
p.y-=el.scrollTop}
}
return p},

expand:function(a,params,custom,type){
if(!a)a=hs.createElement('a',null,{display:'none'},hs.container);
if(typeof a.getParams=='function')return params;
if(type=='html'){
for(var i=0;i<hs.sleeping.length;i++){
if(hs.sleeping[i]&&hs.sleeping[i].a==a){
hs.sleeping[i].awake();
hs.sleeping[i]=null;
return false}
}
hs.hasHtmlExpanders=true}
try{
new hs.Expander(a,params,custom,type);
return false}catch(e){return true}
},

htmlExpand:function(a,params,custom){
return hs.expand(a,params,custom,'html')},

getSelfRendered:function(){
return hs.createElement('div',{
className:'highslide-html-content',
innerHTML:hs.replaceLang(hs.skin.contentWrapper)
})},
getElementByClass:function(el,tagName,className){
var els=el.getElementsByTagName(tagName);
for(var i=0;i<els.length;i++){
if((new RegExp(className)).test(els[i].className)){
return els[i]}
}
return null},
replaceLang:function(s){
s=s.replace(/\s/g,' ');
var re=/{hs\.lang\.([^}]+)\}/g,
matches=s.match(re),
lang;
if(matches)for(var i=0;i<matches.length;i++){
lang=matches[i].replace(re,"$1");
if(typeof hs.lang[lang]!='undefined')s=s.replace(matches[i],hs.lang[lang])}
return s},


getCacheBinding:function(a){
for(var i=0;i<hs.cacheBindings.length;i++){
if(hs.cacheBindings[i][0]==a){
var c=hs.cacheBindings[i][1];
hs.cacheBindings[i][1]=c.cloneNode(1);
return c}
}
return null},

preloadAjax:function(e){
var arr=hs.getAnchors();
for(var i=0;i<arr.htmls.length;i++){
var a=arr.htmls[i];
if(hs.getParam(a,'objectType')=='ajax'&&hs.getParam(a,'cacheAjax'))
hs.push(hs.preloadTheseAjax,a)}

hs.preloadAjaxElement(0)},

preloadAjaxElement:function(i){
if(!hs.preloadTheseAjax[i])return;
var a=hs.preloadTheseAjax[i];
var cache=hs.getNode(hs.getParam(a,'contentId'));
if(!cache)cache=hs.getSelfRendered();
var ajax=new hs.Ajax(a,cache,1);
ajax.onError=function(){};
ajax.onLoad=function(){
hs.push(hs.cacheBindings,[a,cache]);
hs.preloadAjaxElement(i+1)};
ajax.run()},

focusTopmost:function(){
var topZ=0,
topmostKey=-1,
expanders=hs.expanders,
exp,
zIndex;
for(var i=0;i<expanders.length;i++){
exp=expanders[i];
if(exp){
zIndex=exp.wrapper.style.zIndex;
if(zIndex&&zIndex>topZ){
topZ=zIndex;
topmostKey=i}
}
}
if(topmostKey==-1)hs.focusKey=-1;
else expanders[topmostKey].focus()},

getParam:function(a,param){
a.getParams=a.onclick;
var p=a.getParams?a.getParams():null;
a.getParams=null;

return(p&&typeof p[param]!='undefined')?p[param]:
(typeof hs[param]!='undefined'?hs[param]:null)},

getSrc:function(a){
var src=hs.getParam(a,'src');
if(src)return src;
return a.href},

getNode:function(id){
var node=hs.$(id),clone=hs.clones[id],a={};
if(!node&&!clone)return null;
if(!clone){
clone=node.cloneNode(true);
clone.id='';
hs.clones[id]=clone;
return node}else{
return clone.cloneNode(true)}
},

discardElement:function(d){
if(d)hs.garbageBin.appendChild(d);
hs.garbageBin.innerHTML=''},
transit:function(adj,exp){
var last=exp=exp||hs.getExpander();
if(hs.upcoming)return false;
else hs.last=last;
try{
hs.upcoming=adj;
adj.onclick()}catch(e){
hs.last=hs.upcoming=null}
try{
exp.close()}catch(e){}
return false},

previousOrNext:function(el,op){
var exp=hs.getExpander(el);
if(exp){
adj=exp.getAdjacentAnchor(op);
return hs.transit(adj,exp)}else return false},

previous:function(el){
return hs.previousOrNext(el,-1)},

next:function(el){
return hs.previousOrNext(el,1)},

keyHandler:function(e){
if(!e)e=window.event;
if(!e.target)e.target=e.srcElement;
if(typeof e.target.form!='undefined')return true;
var exp=hs.getExpander();

var op=null;
switch(e.keyCode){
case 70:
if(exp)exp.doFullExpand();
return true;
case 32:
case 34:
case 39:
case 40:
op=1;
break;
case 8:
case 33:
case 37:
case 38:
op=-1;
break;
case 27:
case 13:
op=0}
if(op!==null){hs.removeEventListener(document,window.opera?'keypress':'keydown',hs.keyHandler);
if(!hs.enableKeyListener)return true;

if(e.preventDefault)e.preventDefault();
else e.returnValue=false;
if(exp){
if(op==0){
exp.close()}else{
hs.previousOrNext(exp.key,op)}
return false}
}
return true},


registerOverlay:function(overlay){
hs.push(hs.overlays,hs.extend(overlay,{hsId:'hsId'+hs.idCounter++}))},


getWrapperKey:function(element,expOnly){
var el,re=/^highslide-wrapper-([0-9]+)$/;

el=element;
while(el.parentNode){
if(el.id&&re.test(el.id))return el.id.replace(re,"$1");
el=el.parentNode}

if(!expOnly){
el=element;
while(el.parentNode){
if(el.tagName&&hs.isHsAnchor(el)){
for(var key=0;key<hs.expanders.length;key++){
var exp=hs.expanders[key];
if(exp&&exp.a==el)return key}
}
el=el.parentNode}
}
return null},

getExpander:function(el,expOnly){
if(typeof el=='undefined')return hs.expanders[hs.focusKey]||null;
if(typeof el=='number')return hs.expanders[el]||null;
if(typeof el=='string')el=hs.$(el);
return hs.expanders[hs.getWrapperKey(el,expOnly)]||null},

isHsAnchor:function(a){
return(a.onclick&&a.onclick.toString().replace(/\s/g,' ').match(/hs.(htmlE|e)xpand/))},

reOrder:function(){
for(var i=0;i<hs.expanders.length;i++)
if(hs.expanders[i]&&hs.expanders[i].isExpanded)hs.focusTopmost()},

mouseClickHandler:function(e)
{
if(!e)e=window.event;
if(e.button>1)return true;
if(!e.target)e.target=e.srcElement;

var el=e.target;
while(el.parentNode
&&!(/highslide-(image|move|html|resize)/.test(el.className)))
{
el=el.parentNode}
var exp=hs.getExpander(el);
if(exp&&(exp.isClosing||!exp.isExpanded))return true;

if(exp&&e.type=='mousedown'){
if(e.target.form)return true;
var match=el.className.match(/highslide-(image|move|resize)/);
if(match){
hs.dragArgs={exp:exp,type:match[1],left:exp.x.pos,width:exp.x.size,top:exp.y.pos,
height:exp.y.size,clickX:e.clientX,clickY:e.clientY};


hs.addEventListener(document,'mousemove',hs.dragHandler);
if(e.preventDefault)e.preventDefault();

if(/highslide-(image|html)-blur/.test(exp.content.className)){
exp.focus();
hs.hasFocused=true}
return false}
else if(/highslide-html/.test(el.className)&&hs.focusKey!=exp.key){
exp.focus();
exp.doShowHide('hidden')}
}else if(e.type=='mouseup'){

hs.removeEventListener(document,'mousemove',hs.dragHandler);

if(hs.dragArgs){
if(hs.styleRestoreCursor&&hs.dragArgs.type=='image')
hs.dragArgs.exp.content.style.cursor=hs.styleRestoreCursor;
var hasDragged=hs.dragArgs.hasDragged;

if(!hasDragged&&!hs.hasFocused&&!/(move|resize)/.test(hs.dragArgs.type)){
exp.close()}
else if(hasDragged||(!hasDragged&&hs.hasHtmlExpanders)){
hs.dragArgs.exp.doShowHide('hidden')}

if(hs.dragArgs.exp.releaseMask)
hs.dragArgs.exp.releaseMask.style.display='none';

hs.hasFocused=false;
hs.dragArgs=null}else if(/highslide-image-blur/.test(el.className)){
el.style.cursor=hs.styleRestoreCursor}
}
return false},

dragHandler:function(e)
{
if(!hs.dragArgs)return true;
if(!e)e=window.event;
var a=hs.dragArgs,exp=a.exp;
if(exp.iframe){
if(!exp.releaseMask)exp.releaseMask=hs.createElement('div',null,
{position:'absolute',width:exp.x.size+'px',height:exp.y.size+'px',
left:exp.x.cb+'px',top:exp.y.cb+'px',zIndex:4,background:(hs.ie?'white':'none'),
opacity:.01},
exp.wrapper,true);
if(exp.releaseMask.style.display=='none')
exp.releaseMask.style.display=''}

a.dX=e.clientX-a.clickX;
a.dY=e.clientY-a.clickY;

var distance=Math.sqrt(Math.pow(a.dX,2)+Math.pow(a.dY,2));
if(!a.hasDragged)a.hasDragged=(a.type!='image'&&distance>0)
||(distance>(hs.dragSensitivity||5));

if(a.hasDragged&&e.clientX>5&&e.clientY>5){

if(a.type=='resize')exp.resize(a);
else{
exp.moveTo(a.left+a.dX,a.top+a.dY);
if(a.type=='image')exp.content.style.cursor='move'}
}
return false},

wrapperMouseHandler:function(e){
try{
if(!e)e=window.event;
var over=/mouseover/i.test(e.type);
if(!e.target)e.target=e.srcElement;
if(hs.ie)e.relatedTarget=
over?e.fromElement:e.toElement;
var exp=hs.getExpander(e.target);
if(!exp.isExpanded)return;
if(!exp||!e.relatedTarget||hs.getExpander(e.relatedTarget,true)==exp
||hs.dragArgs)return;
for(var i=0;i<exp.overlays.length;i++)(function(){
var o=hs.$('hsId'+exp.overlays[i]);
if(o&&o.hideOnMouseOut){
if(over)hs.setStyles(o,{visibility:'visible',display:''});
hs.animate(o,{opacity:over?o.opacity:0},o.dur)}
})()}catch(e){}
},
addEventListener:function(el,event,func){
if(el==document&&event=='ready')hs.push(hs.onReady,func);
try{
el.addEventListener(event,func,false)}catch(e){
try{
el.detachEvent('on'+event,func);
el.attachEvent('on'+event,func)}catch(e){
el['on'+event]=func}
}
},

removeEventListener:function(el,event,func){
try{
el.removeEventListener(event,func,false)}catch(e){
try{
el.detachEvent('on'+event,func)}catch(e){
el['on'+event]=null}
}
},

preloadFullImage:function(i){
if(hs.continuePreloading&&hs.preloadTheseImages[i]&&hs.preloadTheseImages[i]!='undefined'){
var img=document.createElement('img');
img.onload=function(){
img=null;
hs.preloadFullImage(i+1)};
img.src=hs.preloadTheseImages[i]}
},
preloadImages:function(number){
if(number&&typeof number!='object')hs.numberOfImagesToPreload=number;

var arr=hs.getAnchors();
for(var i=0;i<arr.images.length&&i<hs.numberOfImagesToPreload;i++){
hs.push(hs.preloadTheseImages,hs.getSrc(arr.images[i]))}


if(hs.outlineType)new hs.Outline(hs.outlineType,function(){hs.preloadFullImage(0)});
else

hs.preloadFullImage(0);


if(hs.restoreCursor)var cur=hs.createElement('img',{src:hs.graphicsDir+hs.restoreCursor})},


init:function(){
if(!hs.container){

hs.getPageSize();
hs.ieLt7=hs.ie&&hs.uaVersion<7;
hs.ie6SSL=hs.ieLt7&&location.protocol=='https:';
for(var x in hs.langDefaults){
if(typeof hs[x]!='undefined')hs.lang[x]=hs[x];
else if(typeof hs.lang[x]=='undefined'&&typeof hs.langDefaults[x]!='undefined')
hs.lang[x]=hs.langDefaults[x]}

hs.container=hs.createElement('div',{
className:'highslide-container'
},{
position:'absolute',
left:0,
top:0,
width:'100%',
zIndex:hs.zIndexCounter,
direction:'ltr'
},
document.body,
true
);
hs.loading=hs.createElement('a',{
className:'highslide-loading',
title:hs.lang.loadingTitle,
innerHTML:hs.lang.loadingText,
href:'javascript:;'
},{
position:'absolute',
top:'-9999px',
opacity:hs.loadingOpacity,
zIndex:1
},hs.container
);
hs.garbageBin=hs.createElement('div',null,{display:'none'},hs.container);
hs.clearing=hs.createElement('div',null,
{clear:'both',paddingTop:'1px'},null,true);


Math.linearTween=function(t,b,c,d){
return c*t/d+b};
Math.easeInQuad=function(t,b,c,d){
return c*(t/=d)*t+b};

hs.hideSelects=hs.ieLt7;
hs.hideIframes=((window.opera&&hs.uaVersion<9)||navigator.vendor=='KDE'
||(hs.ie&&hs.uaVersion<5.5))}
},
ready:function(){
if(hs.isReady)return;
hs.isReady=true;

for(var i=0;i<hs.onReady.length;i++)hs.onReady[i]()},

updateAnchors:function(){
var el,els,all=[],images=[],htmls=[],groups={},re;

for(var i=0;i<hs.openerTagNames.length;i++){
els=document.getElementsByTagName(hs.openerTagNames[i]);
for(var j=0;j<els.length;j++){
el=els[j];
re=hs.isHsAnchor(el);
if(re){
hs.push(all,el);
if(re[0]=='hs.expand')hs.push(images,el);
else if(re[0]=='hs.htmlExpand')hs.push(htmls,el);
var g=hs.getParam(el,'slideshowGroup')||'none';
if(!groups[g])groups[g]=[];
hs.push(groups[g],el)}
}
}
hs.anchors={all:all,groups:groups,images:images,htmls:htmls};
return hs.anchors},

getAnchors:function(){
return hs.anchors||hs.updateAnchors()},


close:function(el){
var exp=hs.getExpander(el);
if(exp)exp.close();
return false}
};hs.fx=function(elem,options,prop){
this.options=options;
this.elem=elem;
this.prop=prop;

if(!options.orig)options.orig={}};
hs.fx.prototype={
update:function(){
(hs.fx.step[this.prop]||hs.fx.step._default)(this);

if(this.options.step)
this.options.step.call(this.elem,this.now,this)},
custom:function(from,to,unit){
this.startTime=(new Date()).getTime();
this.start=from;
this.end=to;
this.unit=unit;
this.now=this.start;
this.pos=this.state=0;

var self=this;
function t(gotoEnd){
return self.step(gotoEnd)}

t.elem=this.elem;

if(t()&&hs.timers.push(t)==1){
hs.timerId=setInterval(function(){
var timers=hs.timers;

for(var i=0;i<timers.length;i++)
if(!timers[i]())
timers.splice(i--,1);

if(!timers.length){
clearInterval(hs.timerId)}
},13)}
},
step:function(gotoEnd){
var t=(new Date()).getTime();
if(gotoEnd||t>=this.options.duration+this.startTime){
this.now=this.end;
this.pos=this.state=1;
this.update();

this.options.curAnim[this.prop]=true;

var done=true;
for(var i in this.options.curAnim)
if(this.options.curAnim[i]!==true)
done=false;

if(done){
if(this.options.complete)this.options.complete.call(this.elem)}
return false}else{
var n=t-this.startTime;
this.state=n/this.options.duration;
this.pos=this.options.easing(n,0,1,this.options.duration);
this.now=this.start+((this.end-this.start)*this.pos);
this.update()}
return true}

};

hs.extend(hs.fx,{
step:{

opacity:function(fx){
hs.setStyles(fx.elem,{opacity:fx.now})},

_default:function(fx){
if(fx.elem.style&&fx.elem.style[fx.prop]!=null)
fx.elem.style[fx.prop]=fx.now+fx.unit;
else
fx.elem[fx.prop]=fx.now}
}
});

hs.Outline=function(outlineType,onLoad){
this.onLoad=onLoad;
this.outlineType=outlineType;
var v=hs.uaVersion,tr;

this.hasAlphaImageLoader=hs.ie&&v>=5.5&&v<7;
if(!outlineType){
if(onLoad)onLoad();
return}

hs.init();
this.table=hs.createElement(
'table',{
cellSpacing:0
},{
visibility:'hidden',
position:'absolute',
borderCollapse:'collapse',
width:0
},
hs.container,
true
);
var tbody=hs.createElement('tbody',null,null,this.table,1);

this.td=[];
for(var i=0;i<=8;i++){
if(i%3==0)tr=hs.createElement('tr',null,{height:'auto'},tbody,true);
this.td[i]=hs.createElement('td',null,null,tr,true);
var style=i!=4?{lineHeight:0,fontSize:0}:{position:'relative'};
hs.setStyles(this.td[i],style)}
this.td[4].className=outlineType+' highslide-outline';

this.preloadGraphic()};

hs.Outline.prototype={
preloadGraphic:function(){
var src=hs.graphicsDir+(hs.outlinesDir||"outlines/")+this.outlineType+".png";

var appendTo=hs.safari?hs.container:null;
this.graphic=hs.createElement('img',null,{position:'absolute',
top:'-9999px'},appendTo,true);

var pThis=this;
this.graphic.onload=function(){pThis.onGraphicLoad()};

this.graphic.src=src},

onGraphicLoad:function(){
var o=this.offset=this.graphic.width/4,
pos=[[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]],
dim={height:(2*o)+'px',width:(2*o)+'px'};
for(var i=0;i<=8;i++){
if(pos[i]){
if(this.hasAlphaImageLoader){
var w=(i==1||i==7)?'100%':this.graphic.width+'px';
var div=hs.createElement('div',null,{width:'100%',height:'100%',position:'relative',overflow:'hidden'},this.td[i],true);
hs.createElement('div',null,{
filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+this.graphic.src+"')",
position:'absolute',
width:w,
height:this.graphic.height+'px',
left:(pos[i][0]*o)+'px',
top:(pos[i][1]*o)+'px'
},
div,
true)}else{
hs.setStyles(this.td[i],{background:'url('+this.graphic.src+') '+(pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'})}

if(window.opera&&(i==3||i==5))
hs.createElement('div',null,dim,this.td[i],true);

hs.setStyles(this.td[i],dim)}
}
this.graphic=null;
if(hs.pendingOutlines[this.outlineType])hs.pendingOutlines[this.outlineType].destroy();
hs.pendingOutlines[this.outlineType]=this;
if(this.onLoad)this.onLoad()},

setPosition:function(pos,offset,vis,dur,easing){
var exp=this.exp,
stl=exp.wrapper.style,
offset=offset||0,
pos=pos||{
x:exp.x.pos+offset,
y:exp.y.pos+offset,
w:exp.x.get('wsize')-2*offset,
h:exp.y.get('wsize')-2*offset
};
if(vis)this.table.style.visibility=(pos.h>=4*this.offset)
?'visible':'hidden';
hs.setStyles(this.table,{
left:(pos.x-this.offset)+'px',
top:(pos.y-this.offset)+'px',
width:(pos.w+2*this.offset)+'px'
});

pos.w-=2*this.offset;
pos.h-=2*this.offset;
hs.setStyles(this.td[4],{
width:pos.w>=0?pos.w+'px':0,
height:pos.h>=0?pos.h+'px':0
});
if(this.hasAlphaImageLoader)this.td[3].style.height
=this.td[5].style.height=this.td[4].style.height},

destroy:function(hide){
if(hide)this.table.style.visibility='hidden';
else hs.discardElement(this.table)}
};

hs.Dimension=function(exp,dim){
this.exp=exp;
this.dim=dim;
this.ucwh=dim=='x'?'Width':'Height';
this.wh=this.ucwh.toLowerCase();
this.uclt=dim=='x'?'Left':'Top';
this.lt=this.uclt.toLowerCase();
this.ucrb=dim=='x'?'Right':'Bottom';
this.rb=this.ucrb.toLowerCase();
this.p1=this.p2=0};
hs.Dimension.prototype={
get:function(key){
switch(key){
case'loadingPos':
return this.tpos+this.tb+(this.t-hs.loading['offset'+this.ucwh])/2;
case'wsize':
return this.size+2*this.cb+this.p1+this.p2;
case'fitsize':
return this.clientSize-this.marginMin-this.marginMax;
case'maxsize':
return this.get('fitsize')-2*this.cb-this.p1-this.p2;
case'opos':
return this.pos-(this.exp.outline?this.exp.outline.offset:0);
case'osize':
return this.get('wsize')+(this.exp.outline?2*this.exp.outline.offset:0);
case'imgPad':
return this.imgSize?Math.round((this.size-this.imgSize)/2):0}
},
calcBorders:function(){

this.cb=(this.exp.content['offset'+this.ucwh]-this.t)/2;
this.marginMax=hs['margin'+this.ucrb]},
calcThumb:function(){
this.t=this.exp.el[this.wh]?parseInt(this.exp.el[this.wh]):
this.exp.el['offset'+this.ucwh];
this.tpos=this.exp.tpos[this.dim];
this.tb=(this.exp.el['offset'+this.ucwh]-this.t)/2;
if(this.tpos<1){
this.tpos=(hs.page[this.wh]/2)+hs.page['scroll'+this.uclt]}},
calcExpanded:function(){
var exp=this.exp;
this.justify='auto';


if(exp.align=='center')this.justify='center';
else if(new RegExp(this.lt).test(exp.anchor))this.justify=null;
else if(new RegExp(this.rb).test(exp.anchor))this.justify='max';



this.pos=this.tpos-this.cb+this.tb;
this.size=Math.min(this.full,exp['max'+this.ucwh]||this.full);
this.minSize=exp.allowSizeReduction?
Math.min(exp['min'+this.ucwh],this.full):this.full;
if(exp.isImage&&exp.useBox){
this.size=exp[this.wh];
this.imgSize=this.full}
if(this.dim=='x'&&hs.padToMinWidth)this.minSize=exp.minWidth;
this.target=exp['target'+this.dim.toUpperCase()];
this.marginMin=hs['margin'+this.uclt];
this.scroll=hs.page['scroll'+this.uclt];
this.clientSize=hs.page[this.wh]},
setSize:function(i){
var exp=this.exp;
if(exp.isImage&&(exp.useBox||hs.padToMinWidth)){
this.imgSize=i;
this.size=Math.max(this.size,this.imgSize);
exp.content.style[this.lt]=this.get('imgPad')+'px'}else
this.size=i;

exp.content.style[this.wh]=i+'px';
exp.wrapper.style[this.wh]=this.get('wsize')+'px';
if(exp.outline)exp.outline.setPosition();
if(exp.releaseMask)exp.releaseMask.style[this.wh]=i+'px';
if(exp.isHtml){
var d=exp.scrollerDiv;
if(this.sizeDiff===undefined)
this.sizeDiff=exp.innerContent['offset'+this.ucwh]-d['offset'+this.ucwh];
d.style[this.wh]=(this.size-this.sizeDiff)+'px';

if(this.dim=='x')exp.mediumContent.style.width='auto';
if(exp.body)exp.body.style[this.wh]='auto'}
if(this.dim=='x'&&exp.overlayBox)exp.sizeOverlayBox(true)},
setPos:function(i){
this.pos=i;
this.exp.wrapper.style[this.lt]=i+'px';

if(this.exp.outline)this.exp.outline.setPosition()}
};

hs.Expander=function(a,params,custom,contentType){
if(document.readyState&&hs.ie&&!hs.isReady){
hs.addEventListener(document,'ready',function(){
new hs.Expander(a,params,custom,contentType)});
return}
this.a=a;
this.custom=custom;
this.contentType=contentType||'image';
this.isHtml=(contentType=='html');
this.isImage=!this.isHtml;

hs.continuePreloading=false;
this.overlays=[];
hs.init();
var key=this.key=hs.expanders.length;

for(var i=0;i<hs.overrides.length;i++){
var name=hs.overrides[i];
this[name]=params&&typeof params[name]!='undefined'?
params[name]:hs[name]}
if(!this.src)this.src=a.href;


var el=(params&&params.thumbnailId)?hs.$(params.thumbnailId):a;
el=this.thumb=el.getElementsByTagName('img')[0]||el;
this.thumbsUserSetId=el.id||a.id;


for(var i=0;i<hs.expanders.length;i++){
if(hs.expanders[i]&&hs.expanders[i].a==a){
hs.expanders[i].focus();
return false}
}


if(!hs.allowSimultaneousLoading)for(var i=0;i<hs.expanders.length;i++){
if(hs.expanders[i]&&hs.expanders[i].thumb!=el&&!hs.expanders[i].onLoadStarted){
hs.expanders[i].cancelLoading()}
}
hs.expanders[key]=this;
if(!hs.allowMultipleInstances&&!hs.upcoming){
if(hs.expanders[key-1])hs.expanders[key-1].close();
if(typeof hs.focusKey!='undefined'&&hs.expanders[hs.focusKey])
hs.expanders[hs.focusKey].close()}


this.el=el;
this.tpos=hs.getPosition(el);
hs.getPageSize();
var x=this.x=new hs.Dimension(this,'x');
x.calcThumb();
var y=this.y=new hs.Dimension(this,'y');
y.calcThumb();
this.wrapper=hs.createElement(
'div',{
id:'highslide-wrapper-'+this.key,
className:'highslide-wrapper '+this.wrapperClassName
},{
visibility:'hidden',
position:'absolute',
zIndex:hs.zIndexCounter+=2
},null,true);

this.wrapper.onmouseover=this.wrapper.onmouseout=hs.wrapperMouseHandler;
if(this.contentType=='image'&&this.outlineWhileAnimating==2)
this.outlineWhileAnimating=0;


if(!this.outlineType){
this[this.contentType+'Create']()}else if(hs.pendingOutlines[this.outlineType]){
this.connectOutline();
this[this.contentType+'Create']()}else{
this.showLoading();
var exp=this;
new hs.Outline(this.outlineType,
function(){
exp.connectOutline();
exp[exp.contentType+'Create']()}
)}
return true};

hs.Expander.prototype={
error:function(e){

window.location.href=this.src},

connectOutline:function(){
var outline=this.outline=hs.pendingOutlines[this.outlineType];
outline.exp=this;
outline.table.style.zIndex=this.wrapper.style.zIndex-1;
hs.pendingOutlines[this.outlineType]=null},

showLoading:function(){
if(this.onLoadStarted||this.loading)return;

this.loading=hs.loading;
var exp=this;
this.loading.onclick=function(){
exp.cancelLoading()};
var exp=this,
l=this.x.get('loadingPos')+'px',
t=this.y.get('loadingPos')+'px';
setTimeout(function(){
if(exp.loading)hs.setStyles(exp.loading,{left:l,top:t,zIndex:hs.zIndexCounter++})}
,100)},

imageCreate:function(){
var exp=this;

var img=document.createElement('img');
this.content=img;
img.onload=function(){
if(hs.expanders[exp.key])exp.contentLoaded()};
if(hs.blockRightClick)img.oncontextmenu=function(){return false};
img.className='highslide-image';
hs.setStyles(img,{
visibility:'hidden',
display:'block',
position:'absolute',
maxWidth:'9999px',
zIndex:3
});
img.title=hs.lang.restoreTitle;
if(hs.safari)hs.container.appendChild(img);
if(hs.ie&&hs.flushImgSize)img.src=null;
img.src=this.src;

this.showLoading()},

htmlCreate:function(){

this.content=hs.getCacheBinding(this.a);
if(!this.content)
this.content=hs.getNode(this.contentId);
if(!this.content)
this.content=hs.getSelfRendered();
this.getInline(['maincontent']);
if(this.maincontent){
var body=hs.getElementByClass(this.content,'div','highslide-body');
if(body)body.appendChild(this.maincontent);
this.maincontent.style.display='block'}

var innerContent=this.innerContent=this.content;

if(/(swf|iframe)/.test(this.objectType))this.setObjContainerSize(innerContent);


hs.container.appendChild(this.wrapper);
hs.setStyles(this.wrapper,{
position:'static',
padding:'0 '+hs.marginRight+'px 0 '+hs.marginLeft+'px'
});
this.content=hs.createElement(
'div',{
className:'highslide-html'
},{
position:'relative',
zIndex:3,
overflow:'hidden'
},
this.wrapper
);
this.mediumContent=hs.createElement('div',null,null,this.content,1);
this.mediumContent.appendChild(innerContent);

hs.setStyles(innerContent,{
position:'relative',
display:'block',
direction:hs.lang.cssDirection||''
});
if(this.width)innerContent.style.width=this.width+'px';
if(this.height)hs.setStyles(innerContent,{
height:this.height+'px',
overflow:'hidden'
});
if(innerContent.offsetWidth<this.minWidth)
innerContent.style.width=this.minWidth+'px';



if(this.objectType=='ajax'&&!hs.getCacheBinding(this.a)){
this.showLoading();
var ajax=new hs.Ajax(this.a,innerContent);
var exp=this;
ajax.onLoad=function(){if(hs.expanders[exp.key])exp.contentLoaded()};
ajax.onError=function(){location.href=exp.src};
ajax.run()}
else

if(this.objectType=='iframe'&&this.objectLoadTime=='before'){
this.writeExtendedContent()}
else
this.contentLoaded()},

contentLoaded:function(){
try{
if(!this.content)return;
this.content.onload=null;
if(this.onLoadStarted)return;
else this.onLoadStarted=true;

var x=this.x,y=this.y;

if(this.loading){
hs.setStyles(this.loading,{top:'-9999px'});
this.loading=null}
if(this.isImage){
x.full=this.content.width;
y.full=this.content.height;

hs.setStyles(this.content,{
width:x.t+'px',
height:y.t+'px'
});
this.wrapper.appendChild(this.content);
hs.container.appendChild(this.wrapper)}else if(this.htmlGetSize)this.htmlGetSize();

x.calcBorders();
y.calcBorders();

hs.setStyles(this.wrapper,{
left:(x.tpos+x.tb-x.cb)+'px',
top:(y.tpos+x.tb-y.cb)+'px'
});
this.getOverlays();

var ratio=x.full/y.full;

x.calcExpanded();
this.justify(x);

y.calcExpanded();
this.justify(y);
if(this.isHtml)this.htmlSizeOperations();
if(this.overlayBox)this.sizeOverlayBox(0,1);

if(this.allowSizeReduction){
if(this.isImage)
this.correctRatio(ratio);
else this.fitOverlayBox();
if(this.isImage&&this.x.full>(this.x.imgSize||this.x.size)){
this.createFullExpand();
if(this.overlays.length==1)this.sizeOverlayBox()}
}
this.show()}catch(e){
this.error(e)}
},


setObjContainerSize:function(parent,auto){
var c=hs.getElementByClass(parent,'DIV','highslide-body');
if(/(iframe|swf)/.test(this.objectType)){
if(this.objectWidth)c.style.width=this.objectWidth+'px';
if(this.objectHeight)c.style.height=this.objectHeight+'px'}
},

writeExtendedContent:function(){
if(this.hasExtendedContent)return;
var exp=this;
this.body=hs.getElementByClass(this.innerContent,'DIV','highslide-body');
if(this.objectType=='iframe'){
this.showLoading();
var ruler=hs.clearing.cloneNode(1);
this.body.appendChild(ruler);
this.newWidth=this.innerContent.offsetWidth;
if(!this.objectWidth)this.objectWidth=ruler.offsetWidth;
var hDiff=this.innerContent.offsetHeight-this.body.offsetHeight,
h=this.objectHeight||hs.page.height-hDiff-hs.marginTop-hs.marginBottom,
onload=this.objectLoadTime=='before'?
' onload="if (hs.expanders['+this.key+']) hs.expanders['+this.key+'].contentLoaded()" ':'';

this.body.innerHTML+='<iframe name="hs'+(new Date()).getTime()+'" frameborder="0" key="'+this.key+'" '
+' allowtransparency="true" style="width:'+this.objectWidth+'px; height:'+h+'px" '
+onload+' src="'+this.src+'"></iframe>';
this.ruler=this.body.getElementsByTagName('div')[0];
this.iframe=this.body.getElementsByTagName('iframe')[0];

if(this.objectLoadTime=='after')this.correctIframeSize()}
this.hasExtendedContent=true},
htmlGetSize:function(){
if(this.iframe&&!this.objectHeight){
this.iframe.style.height=this.body.style.height=this.getIframePageHeight()+'px'}
this.innerContent.appendChild(hs.clearing);
if(!this.x.full)this.x.full=this.innerContent.offsetWidth;
this.y.full=this.innerContent.offsetHeight;
this.innerContent.removeChild(hs.clearing);
if(hs.ie&&this.newHeight>parseInt(this.innerContent.currentStyle.height)){
this.newHeight=parseInt(this.innerContent.currentStyle.height)}
hs.setStyles(this.wrapper,{position:'absolute',padding:'0'});
hs.setStyles(this.content,{width:this.x.t+'px',height:this.y.t+'px'})},

getIframePageHeight:function(){
var h;
try{
var doc=this.iframe.contentDocument||this.iframe.contentWindow.document;
var clearing=doc.createElement('div');
clearing.style.clear='both';
doc.body.appendChild(clearing);
h=clearing.offsetTop;
if(hs.ie)h+=parseInt(doc.body.currentStyle.marginTop)
+parseInt(doc.body.currentStyle.marginBottom)-1}catch(e){
h=300}
return h},
correctIframeSize:function(){
var wDiff=this.innerContent.offsetWidth-this.ruler.offsetWidth;
hs.discardElement(this.ruler);
if(wDiff<0)wDiff=0;

var hDiff=this.innerContent.offsetHeight-this.iframe.offsetHeight;
hs.setStyles(this.iframe,{
width:Math.abs(this.x.size-wDiff)+'px',
height:Math.abs(this.y.size-hDiff)+'px'
});
hs.setStyles(this.body,{
width:this.iframe.style.width,
height:this.iframe.style.height
});

this.scrollingContent=this.iframe;
this.scrollerDiv=this.scrollingContent},
htmlSizeOperations:function(){

this.setObjContainerSize(this.innerContent);



if(this.x.size<this.x.full&&!this.allowWidthReduction)this.x.size=this.x.full;
if(this.y.size<this.y.full&&!this.allowHeightReduction)this.y.size=this.y.full;
this.scrollerDiv=this.innerContent;
hs.setStyles(this.mediumContent,{
position:'relative',
width:this.x.size+'px'
});
hs.setStyles(this.innerContent,{
border:'none',
width:'auto',
height:'auto'
});
var node=hs.getElementByClass(this.innerContent,'DIV','highslide-body');
if(node&&!/(iframe|swf)/.test(this.objectType)){
var cNode=node;
node=hs.createElement(cNode.nodeName,null,{overflow:'hidden'},null,true);
cNode.parentNode.insertBefore(node,cNode);
node.appendChild(hs.clearing);
node.appendChild(cNode);

var wDiff=this.innerContent.offsetWidth-node.offsetWidth;
var hDiff=this.innerContent.offsetHeight-node.offsetHeight;
node.removeChild(hs.clearing);

var kdeBugCorr=hs.safari||navigator.vendor=='KDE'?1:0;
hs.setStyles(node,{
width:(this.x.size-wDiff-kdeBugCorr)+'px',
height:(this.y.size-hDiff)+'px',
overflow:'auto',
position:'relative'
}
);
if(kdeBugCorr&&cNode.offsetHeight>node.offsetHeight){
node.style.width=(parseInt(node.style.width)+kdeBugCorr)+'px'}
this.scrollingContent=node;
this.scrollerDiv=this.scrollingContent}
if(this.iframe&&this.objectLoadTime=='before')this.correctIframeSize();
if(!this.scrollingContent&&this.y.size<this.mediumContent.offsetHeight)this.scrollerDiv=this.content;

if(this.scrollerDiv==this.content&&!this.allowWidthReduction&&!/(iframe|swf)/.test(this.objectType)){
this.x.size+=17}
if(this.scrollerDiv&&this.scrollerDiv.offsetHeight>this.scrollerDiv.parentNode.offsetHeight){
setTimeout("try { hs.expanders["+this.key+"].scrollerDiv.style.overflow = 'auto'; } catch(e) {}",
hs.expandDuration)}
},

justify:function(p,moveOnly){
var tgtArr,tgt=p.target,dim=p==this.x?'x':'y';

if(tgt&&tgt.match(/ /)){
tgtArr=tgt.split(' ');
tgt=tgtArr[0]}
if(tgt&&hs.$(tgt)){
p.pos=hs.getPosition(hs.$(tgt))[dim];
if(tgtArr&&tgtArr[1]&&tgtArr[1].match(/^[-]?[0-9]+px$/))
p.pos+=parseInt(tgtArr[1]);
if(p.size<p.minSize)p.size=p.minSize}else if(p.justify=='auto'||p.justify=='center'){

var hasMovedMin=false;

var allowReduce=p.exp.allowSizeReduction;
if(p.justify=='center')
p.pos=Math.round(p.scroll+(p.clientSize+p.marginMin-p.marginMax-p.get('wsize'))/2);
else
p.pos=Math.round(p.pos-((p.get('wsize')-p.t)/2));
if(p.pos<p.scroll+p.marginMin){
p.pos=p.scroll+p.marginMin;
hasMovedMin=true}
if(!moveOnly&&p.size<p.minSize){
p.size=p.minSize;
allowReduce=false}
if(p.pos+p.get('wsize')>p.scroll+p.clientSize-p.marginMax){
if(!moveOnly&&hasMovedMin&&allowReduce){
p.size=p.get(dim=='y'?'fitsize':'maxsize')}else if(p.get('wsize')<p.get('fitsize')){
p.pos=p.scroll+p.clientSize-p.marginMax-p.get('wsize')}else{
p.pos=p.scroll+p.marginMin;
if(!moveOnly&&allowReduce)p.size=p.get(dim=='y'?'fitsize':'maxsize')}
}

if(!moveOnly&&p.size<p.minSize){
p.size=p.minSize;
allowReduce=false}


}else if(p.justify=='max'){
p.pos=Math.floor(p.pos-p.size+p.t)}


if(p.pos<p.marginMin){
var tmpMin=p.pos;
p.pos=p.marginMin;

if(allowReduce&&!moveOnly)p.size=p.size-(p.pos-tmpMin)}
},

correctRatio:function(ratio){
var x=this.x,
y=this.y,
changed=false,
xSize=Math.min(x.full,x.size),
ySize=Math.min(y.full,y.size),
useBox=(this.useBox||hs.padToMinWidth);

if(xSize/ySize>ratio){ 
xSize=ySize*ratio;
if(xSize<x.minSize){
xSize=x.minSize;
ySize=xSize/ratio}
changed=true}else if(xSize/ySize<ratio){ 
ySize=xSize/ratio;
changed=true}

if(hs.padToMinWidth&&x.full<x.minSize){
x.imgSize=x.full;
y.size=y.imgSize=y.full}else if(this.useBox){
x.imgSize=xSize;
y.imgSize=ySize}else{
x.size=xSize;
y.size=ySize}
this.fitOverlayBox(useBox?null:ratio);
if(useBox&&y.size<y.imgSize){
y.imgSize=y.size;
x.imgSize=y.size*ratio}
if(changed||useBox){
x.pos=x.tpos-x.cb+x.tb;
x.minSize=x.size;
this.justify(x,true);

y.pos=y.tpos-y.cb+y.tb;
y.minSize=y.size;
this.justify(y,true);
if(this.overlayBox)this.sizeOverlayBox()}
},
fitOverlayBox:function(ratio){
var x=this.x,y=this.y;
if(this.overlayBox){
while(y.size>this.minHeight&&x.size>this.minWidth
&&y.get('wsize')>y.get('fitsize')){
y.size-=10;
if(ratio)x.size=y.size*ratio;
this.sizeOverlayBox(0,1)}
}
},

reflow:function(){
if(this.scrollerDiv){
var h=/iframe/i.test(this.scrollerDiv.tagName)?this.getIframePageHeight()+1+'px':'auto';
if(this.body)this.body.style.height=h;
this.scrollerDiv.style.height=h;
this.y.setSize(this.innerContent.offsetHeight)}
},

show:function(){
var x=this.x,y=this.y;
this.doShowHide('hidden');


this.changeSize(
1,{
wrapper:{
width:x.get('wsize'),
height:y.get('wsize'),
left:x.pos,
top:y.pos
},
content:{
left:x.p1+x.get('imgPad'),
top:y.p1+y.get('imgPad'),
width:x.imgSize||x.size,
height:y.imgSize||y.size
}
},
hs.expandDuration
)},

changeSize:function(up,to,dur){

if(this.outline&&!this.outlineWhileAnimating){
if(up)this.outline.setPosition();
else this.outline.destroy(
(this.isHtml&&this.preserveContent))}


if(!up)this.destroyOverlays();

var exp=this,
x=exp.x,
y=exp.y,
easing=this.easing;
if(!up)easing=this.easingClose||easing;
var after=up?
function(){

if(exp.outline)exp.outline.table.style.visibility="visible";
setTimeout(function(){
exp.afterExpand()},50)}:
function(){
exp.afterClose()};
if(up)hs.setStyles(this.wrapper,{
width:x.t+'px',
height:y.t+'px'
});
if(up&&this.isHtml){
hs.setStyles(this.wrapper,{
left:(x.tpos-x.cb+x.tb)+'px',
top:(y.tpos-y.cb+y.tb)+'px'
})}
if(this.fadeInOut){
hs.setStyles(this.wrapper,{opacity:up?0:1});
hs.extend(to.wrapper,{opacity:up})}
hs.animate(this.wrapper,to.wrapper,{
duration:dur,
easing:easing,
step:function(val,args){
if(exp.outline&&exp.outlineWhileAnimating&&args.prop=='top'){
var fac=up?args.pos:1-args.pos;
var pos={
w:x.t+(x.get('wsize')-x.t)*fac,
h:y.t+(y.get('wsize')-y.t)*fac,
x:x.tpos+(x.pos-x.tpos)*fac,
y:y.tpos+(y.pos-y.tpos)*fac
};
exp.outline.setPosition(pos,0,1)}
if(exp.isHtml){
if(args.prop=='left')
exp.mediumContent.style.left=(x.pos-val)+'px';
if(args.prop=='top')
exp.mediumContent.style.top=(y.pos-val)+'px'}
}
});
hs.animate(this.content,to.content,dur,easing,after);
if(up){
this.wrapper.style.visibility='visible';
this.content.style.visibility='visible';
if(this.isHtml)this.innerContent.style.visibility='visible';
this.a.className+=' highslide-active-anchor'}
},




afterExpand:function(){
this.isExpanded=true;
this.focus();

if(this.isHtml&&this.objectLoadTime=='after')this.writeExtendedContent();
if(this.iframe){
try{
var exp=this,
doc=this.iframe.contentDocument||this.iframe.contentWindow.document;
hs.addEventListener(doc,'mousedown',function(){
if(hs.focusKey!=exp.key)exp.focus()})}catch(e){}
if(hs.ie&&typeof this.isClosing!='boolean')
this.iframe.style.width=(this.objectWidth-1)+'px'}
if(hs.upcoming&&hs.upcoming==this.a)hs.upcoming=null;
this.prepareNextOutline();
var p=hs.page,mX=hs.mouse.x+p.scrollLeft,mY=hs.mouse.y+p.scrollTop;
this.mouseIsOver=this.x.pos<mX&&mX<this.x.pos+this.x.get('wsize')
&&this.y.pos<mY&&mY<this.y.pos+this.y.get('wsize');
if(this.overlayBox)this.showOverlays()},


prepareNextOutline:function(){
var key=this.key;
var outlineType=this.outlineType;
new hs.Outline(outlineType,
function(){try{hs.expanders[key].preloadNext()}catch(e){}})},


preloadNext:function(){
var next=this.getAdjacentAnchor(1);
if(next&&next.onclick.toString().match(/hs\.expand/))
var img=hs.createElement('img',{src:hs.getSrc(next)})},


getAdjacentAnchor:function(op){
var current=this.getAnchorIndex(),as=hs.anchors.groups[this.slideshowGroup||'none'];


if(!as[current+op]&&this.slideshow&&this.slideshow.repeat){
if(op==1)return as[0];
else if(op==-1)return as[as.length-1]}

return as[current+op]||null},

getAnchorIndex:function(){
var arr=hs.getAnchors().groups[this.slideshowGroup||'none'];
if(arr)for(var i=0;i<arr.length;i++){
if(arr[i]==this.a)return i}
return null},


cancelLoading:function(){
hs.discardElement(this.wrapper);
hs.expanders[this.key]=null;
if(this.loading)hs.loading.style.left='-9999px'},

writeCredits:function(){
this.credits=hs.createElement('a',{
href:hs.creditsHref,
target:hs.creditsTarget,
className:'highslide-credits',
innerHTML:hs.lang.creditsText,
title:hs.lang.creditsTitle
});
this.createOverlay({
overlayId:this.credits,
position:this.creditsPosition||'top left'
})},

getInline:function(types,addOverlay){
for(var i=0;i<types.length;i++){
var type=types[i],s=null;
if(!this[type+'Id']&&this.thumbsUserSetId)
this[type+'Id']=type+'-for-'+this.thumbsUserSetId;
if(this[type+'Id'])this[type]=hs.getNode(this[type+'Id']);
if(!this[type]&&!this[type+'Text']&&this[type+'Eval'])try{
s=eval(this[type+'Eval'])}catch(e){}
if(!this[type]&&this[type+'Text']){
s=this[type+'Text']}
if(!this[type]&&!s){
var next=this.a.nextSibling;
while(next&&!hs.isHsAnchor(next)){
if((new RegExp('highslide-'+type)).test(next.className||null)){
this[type]=next.cloneNode(1);
break}
next=next.nextSibling}
}

if(!this[type]&&s)this[type]=hs.createElement('div',
{className:'highslide-'+type,innerHTML:s});

if(addOverlay&&this[type]){
var o={position:(type=='heading')?'above':'below'};
for(var x in this[type+'Overlay'])o[x]=this[type+'Overlay'][x];
o.overlayId=this[type];
this.createOverlay(o)}
}
},



doShowHide:function(visibility){
if(hs.hideSelects)this.showHideElements('SELECT',visibility);
if(hs.hideIframes)this.showHideElements('IFRAME',visibility);
if(hs.geckoMac)this.showHideElements('*',visibility)},
showHideElements:function(tagName,visibility){
var els=document.getElementsByTagName(tagName);
var prop=tagName=='*'?'overflow':'visibility';
for(var i=0;i<els.length;i++){
if(prop=='visibility'||(document.defaultView.getComputedStyle(
els[i],"").getPropertyValue('overflow')=='auto'
||els[i].getAttribute('hidden-by')!=null)){
var hiddenBy=els[i].getAttribute('hidden-by');
if(visibility=='visible'&&hiddenBy){
hiddenBy=hiddenBy.replace('['+this.key+']','');
els[i].setAttribute('hidden-by',hiddenBy);
if(!hiddenBy)els[i].style[prop]=els[i].origProp}else if(visibility=='hidden'){
var elPos=hs.getPosition(els[i]);
elPos.w=els[i].offsetWidth;
elPos.h=els[i].offsetHeight;


var clearsX=(elPos.x+elPos.w<this.x.get('opos')
||elPos.x>this.x.get('opos')+this.x.get('osize'));
var clearsY=(elPos.y+elPos.h<this.y.get('opos')
||elPos.y>this.y.get('opos')+this.y.get('osize'));
var wrapperKey=hs.getWrapperKey(els[i]);
if(!clearsX&&!clearsY&&wrapperKey!=this.key){
if(!hiddenBy){
els[i].setAttribute('hidden-by','['+this.key+']');
els[i].origProp=els[i].style[prop];
els[i].style[prop]='hidden'}else if(hiddenBy.indexOf('['+this.key+']')==-1){
els[i].setAttribute('hidden-by',hiddenBy+'['+this.key+']')}
}else if((hiddenBy=='['+this.key+']'||hs.focusKey==wrapperKey)
&&wrapperKey!=this.key){
els[i].setAttribute('hidden-by','');
els[i].style[prop]=els[i].origProp||''}else if(hiddenBy&&hiddenBy.indexOf('['+this.key+']')>-1){
els[i].setAttribute('hidden-by',hiddenBy.replace('['+this.key+']',''))}

}
}
}
},

focus:function(){
this.wrapper.style.zIndex=hs.zIndexCounter+=2;

for(var i=0;i<hs.expanders.length;i++){
if(hs.expanders[i]&&i==hs.focusKey){
var blurExp=hs.expanders[i];
blurExp.content.className+=' highslide-'+blurExp.contentType+'-blur';
if(blurExp.isImage){
blurExp.content.style.cursor=hs.ie?'hand':'pointer';
blurExp.content.title=hs.lang.focusTitle}
}
}


if(this.outline)this.outline.table.style.zIndex
=this.wrapper.style.zIndex-1;
this.content.className='highslide-'+this.contentType;
if(this.isImage){
this.content.title=hs.lang.restoreTitle;

if(hs.restoreCursor){
hs.styleRestoreCursor=window.opera?'pointer':'url('+hs.graphicsDir+hs.restoreCursor+'), pointer';
if(hs.ie&&hs.uaVersion<6)hs.styleRestoreCursor='hand';
this.content.style.cursor=hs.styleRestoreCursor}
}
hs.focusKey=this.key;
hs.addEventListener(document,window.opera?'keypress':'keydown',hs.keyHandler)},
moveTo:function(x,y){
this.x.setPos(x);
this.y.setPos(y)},
resize:function(e){
var w,h,r=e.width/e.height;
w=Math.max(e.width+e.dX,Math.min(this.minWidth,this.x.full));
if(this.isImage&&Math.abs(w-this.x.full)<12)w=this.x.full;
h=this.isHtml?e.height+e.dY:w/r;
if(h<Math.min(this.minHeight,this.y.full)){
h=Math.min(this.minHeight,this.y.full);
if(this.isImage)w=h*r}
this.resizeTo(w,h)},
resizeTo:function(w,h){
this.y.setSize(h);
this.x.setSize(w)},

close:function(){
if(this.isClosing||!this.isExpanded)return;
this.isClosing=true;

hs.removeEventListener(document,window.opera?'keypress':'keydown',hs.keyHandler);

try{
if(this.isHtml)this.htmlPrepareClose();
this.content.style.cursor='default';
this.changeSize(
0,{
wrapper:{
width:this.x.t,
height:this.y.t,
left:this.x.tpos-this.x.cb+this.x.tb,
top:this.y.tpos-this.y.cb+this.y.tb
},
content:{
left:0,
top:0,
width:this.x.t,
height:this.y.t
}
},hs.restoreDuration
)}catch(e){this.afterClose()}
},

htmlPrepareClose:function(){
if(hs.geckoMac){
if(!hs.mask)hs.mask=hs.createElement('div',null,
{position:'absolute'},hs.container);
hs.setStyles(hs.mask,{width:this.x.size+'px',height:this.y.size+'px',
left:this.x.pos+'px',top:this.y.pos+'px',display:'block'})}

if(this.objectLoadTime=='after'&&!this.preserveContent)this.destroyObject();
if(this.scrollerDiv&&this.scrollerDiv!=this.scrollingContent)
this.scrollerDiv.style.overflow='hidden'},

destroyObject:function(){
if(hs.ie&&this.iframe)
try{this.iframe.contentWindow.document.body.innerHTML=''}catch(e){}
this.body.innerHTML=''},

sleep:function(){
if(this.outline)this.outline.table.style.display='none';
this.releaseMask=null;
this.wrapper.style.display='none';
hs.push(hs.sleeping,this)},

awake:function(){try{

hs.expanders[this.key]=this;

if(!hs.allowMultipleInstances&&hs.focusKey!=this.key){
try{hs.expanders[hs.focusKey].close()}catch(e){}
}

var z=hs.zIndexCounter++,stl={display:'',zIndex:z};
hs.setStyles(this.wrapper,stl);
this.isClosing=false;

var o=this.outline||0;
if(o){
if(!this.outlineWhileAnimating)stl.visibility='hidden';
hs.setStyles(o.table,stl)}

this.show()}catch(e){}


},

createOverlay:function(o){
var el=o.overlayId;
if(typeof el=='string')el=hs.getNode(el);
if(o.html)el=hs.createElement('div',{innerHTML:o.html});
if(!el||typeof el=='string')return;
el.style.display='block';
this.genOverlayBox();
var width=o.width&&/^[0-9]+(px|%)$/.test(o.width)?o.width:'auto';
if(/^(left|right)panel$/.test(o.position)&&!/^[0-9]+px$/.test(o.width))width='200px';
var overlay=hs.createElement(
'div',{
id:'hsId'+hs.idCounter++,
hsId:o.hsId
},{
position:'absolute',
visibility:'hidden',
width:width,
direction:hs.lang.cssDirection||'',
opacity:0
},this.overlayBox,
true
);

overlay.appendChild(el);
hs.extend(overlay,{
opacity:1,
offsetX:0,
offsetY:0,
dur:(o.fade===0||o.fade===false||(o.fade==2&&hs.ie))?0:250
});
hs.extend(overlay,o);

if(this.gotOverlays){
this.positionOverlay(overlay);
if(!overlay.hideOnMouseOut||this.mouseIsOver)
hs.animate(overlay,{opacity:overlay.opacity},overlay.dur)}
hs.push(this.overlays,hs.idCounter-1)},
positionOverlay:function(overlay){
var p=overlay.position||'middle center',
offX=overlay.offsetX,
offY=overlay.offsetY;
if(overlay.parentNode!=this.overlayBox)this.overlayBox.appendChild(overlay);
if(/left$/.test(p))overlay.style.left=offX+'px';

if(/center$/.test(p))hs.setStyles(overlay,{
left:'50%',
marginLeft:(offX-Math.round(overlay.offsetWidth/2))+'px'
});

if(/right$/.test(p))overlay.style.right=-offX+'px';

if(/^leftpanel$/.test(p)){
hs.setStyles(overlay,{
right:'100%',
marginRight:this.x.cb+'px',
top:-this.y.cb+'px',
bottom:-this.y.cb+'px',
overflow:'auto'
});
this.x.p1=overlay.offsetWidth}else if(/^rightpanel$/.test(p)){
hs.setStyles(overlay,{
left:'100%',
marginLeft:this.x.cb+'px',
top:-this.y.cb+'px',
bottom:-this.y.cb+'px',
overflow:'auto'
});
this.x.p2=overlay.offsetWidth}

if(/^top/.test(p))overlay.style.top=offY+'px';
if(/^middle/.test(p))hs.setStyles(overlay,{
top:'50%',
marginTop:(offY-Math.round(overlay.offsetHeight/2))+'px'
});
if(/^bottom/.test(p))overlay.style.bottom=-offY+'px';
if(/^above$/.test(p)){
hs.setStyles(overlay,{
left:(-this.x.p1-this.x.cb)+'px',
right:(-this.x.p2-this.x.cb)+'px',
bottom:'100%',
marginBottom:this.y.cb+'px',
width:'auto'
});
this.y.p1=overlay.offsetHeight}else if(/^below$/.test(p)){
hs.setStyles(overlay,{
position:'relative',
left:(-this.x.p1-this.x.cb)+'px',
right:(-this.x.p2-this.x.cb)+'px',
top:'100%',
marginTop:this.y.cb+'px',
width:'auto'
});
this.y.p2=overlay.offsetHeight;
overlay.style.position='absolute'}
},

getOverlays:function(){
this.getInline(['heading','caption'],true);
if(this.heading&&this.dragByHeading)this.heading.className+=' highslide-move';
if(hs.showCredits)this.writeCredits();
for(var i=0;i<hs.overlays.length;i++){
var o=hs.overlays[i],tId=o.thumbnailId,sg=o.slideshowGroup;
if((!tId&&!sg)||(tId&&tId==this.thumbsUserSetId)
||(sg&&sg===this.slideshowGroup)){
if(this.isImage||(this.isHtml&&o.useOnHtml))
this.createOverlay(o)}
}
var os=[];
for(var i=0;i<this.overlays.length;i++){
var o=hs.$('hsId'+this.overlays[i]);
if(/panel$/.test(o.position))this.positionOverlay(o);
else hs.push(os,o)}
for(var i=0;i<os.length;i++)this.positionOverlay(os[i]);
this.gotOverlays=true},
genOverlayBox:function(){
if(!this.overlayBox)this.overlayBox=hs.createElement(
'div',{
className:this.wrapperClassName
},{
position:'absolute',
width:(this.x.size||(this.useBox?this.width:null)
||this.x.full)+'px',
height:(this.y.size||this.y.full)+'px',
visibility:'hidden',
overflow:'hidden',
zIndex:hs.ie?4:null
},
hs.container,
true
)},
sizeOverlayBox:function(doWrapper,doPanels){
var overlayBox=this.overlayBox,
x=this.x,
y=this.y;
hs.setStyles(overlayBox,{
width:x.size+'px',
height:y.size+'px'
});
if(doWrapper||doPanels){
for(var i=0;i<this.overlays.length;i++){
var o=hs.$('hsId'+this.overlays[i]);
var ie6=(hs.ieLt7||document.compatMode=='BackCompat');
if(o&&/^(above|below)$/.test(o.position)){
if(ie6){
o.style.width=(overlayBox.offsetWidth+2*x.cb
+x.p1+x.p2)+'px'}
y[o.position=='above'?'p1':'p2']=o.offsetHeight}
if(o&&ie6&&/^(left|right)panel$/.test(o.position)){
o.style.height=(overlayBox.offsetHeight+2*y.cb)+'px'}
}
}
if(doWrapper){
hs.setStyles(this.content,{
top:y.p1+'px'
});
hs.setStyles(overlayBox,{
top:(y.p1+y.cb)+'px'
})}
},

showOverlays:function(){
var b=this.overlayBox;
b.className='';
hs.setStyles(b,{
top:(this.y.p1+this.y.cb)+'px',
left:(this.x.p1+this.x.cb)+'px',
overflow:'visible'
});
if(hs.safari)b.style.visibility='visible';
this.wrapper.appendChild(b);
for(var i=0;i<this.overlays.length;i++){
var o=hs.$('hsId'+this.overlays[i]);
o.style.zIndex=4;
if(!o.hideOnMouseOut||this.mouseIsOver){
o.style.visibility='visible';
hs.setStyles(o,{visibility:'visible',display:''});
hs.animate(o,{opacity:o.opacity},o.dur)}
}
},

destroyOverlays:function(){
if(!this.overlays.length)return;
if(this.isHtml&&this.preserveContent){
this.overlayBox.style.top='-9999px';
hs.container.appendChild(this.overlayBox)}else
hs.discardElement(this.overlayBox)},



createFullExpand:function(){
this.fullExpandLabel=hs.createElement(
'a',{
href:'javascript:hs.expanders['+this.key+'].doFullExpand();',
title:hs.lang.fullExpandTitle,
className:'highslide-full-expand'
}
);

this.createOverlay({
overlayId:this.fullExpandLabel,
position:hs.fullExpandPosition,
hideOnMouseOut:true,
opacity:hs.fullExpandOpacity
})},

doFullExpand:function(){
try{
if(this.fullExpandLabel)hs.discardElement(this.fullExpandLabel);

this.focus();
var xSize=this.x.size;
this.resizeTo(this.x.full,this.y.full);

var xpos=this.x.pos-(this.x.size-xSize)/2;
if(xpos<hs.marginLeft)xpos=hs.marginLeft;

this.moveTo(xpos,this.y.pos);
this.doShowHide('hidden')}catch(e){
this.error(e)}
},


afterClose:function(){
this.a.className=this.a.className.replace('highslide-active-anchor','');

this.doShowHide('visible');

if(this.isHtml&&this.preserveContent){
this.sleep()}else{
if(this.outline&&this.outlineWhileAnimating)this.outline.destroy();

hs.discardElement(this.wrapper)}
if(hs.mask)hs.mask.style.display='none';

hs.expanders[this.key]=null;
hs.reOrder()}

};



hs.Ajax=function(a,content,pre){
this.a=a;
this.content=content;
this.pre=pre};

hs.Ajax.prototype={
run:function(){
if(!this.src)this.src=hs.getSrc(this.a);
if(this.src.match('#')){
var arr=this.src.split('#');
this.src=arr[0];
this.id=arr[1]}
if(hs.cachedGets[this.src]){
this.cachedGet=hs.cachedGets[this.src];
if(this.id)this.getElementContent();
else this.loadHTML();
return}
try{this.xmlHttp=new XMLHttpRequest()}
catch(e){
try{this.xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")}
catch(e){
try{this.xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")}
catch(e){this.onError()}
}
}
var pThis=this;
this.xmlHttp.onreadystatechange=function(){
if(pThis.xmlHttp.readyState==4){
if(pThis.id)pThis.getElementContent();
else pThis.loadHTML()}
};
var src=this.src;
if(hs.forceAjaxReload)
src=src.replace(/$/,(/\?/.test(src)?'&':'?')+'dummy='+(new Date()).getTime());
this.xmlHttp.open('GET',src,true);
this.xmlHttp.setRequestHeader('X-Requested-With','XMLHttpRequest');
this.xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
this.xmlHttp.send(null)},

getElementContent:function(){
hs.init();
var attribs=window.opera||hs.ie6SSL?{src:'about:blank'}:null;

this.iframe=hs.createElement('iframe',attribs,
{position:'absolute',top:'-9999px'},hs.container);

this.loadHTML()},

loadHTML:function(){
var s=this.cachedGet||this.xmlHttp.responseText;
if(this.pre)hs.cachedGets[this.src]=s;
if(!hs.ie||hs.uaVersion>=5.5){
s=s.replace(/\s/g,' ').replace(
new RegExp('<link[^>]*>','gi'),'').replace(
new RegExp('<script[^>]*>.*?</script>','gi'),'');

if(this.iframe){
var doc=this.iframe.contentDocument;
if(!doc&&this.iframe.contentWindow)doc=this.iframe.contentWindow.document;
if(!doc){
var pThis=this;
setTimeout(function(){pThis.loadHTML()},25);
return}
doc.open();
doc.write(s);
doc.close();
try{s=doc.getElementById(this.id).innerHTML}catch(e){
try{s=this.iframe.document.getElementById(this.id).innerHTML}catch(e){}
}
hs.discardElement(this.iframe)}else{
s=s.replace(new RegExp('^.*?<body[^>]*>(.*?)</body>.*?$','i'),'$1')}
}
hs.getElementByClass(this.content,'DIV','highslide-body').innerHTML=s;
this.onLoad();
for(var x in this)this[x]=null}
};
if(hs.ie){
(function(){
try{
document.documentElement.doScroll('left')}catch(e){
setTimeout(arguments.callee,50);
return}
hs.ready()})()}
hs.addEventListener(document,'DOMContentLoaded',hs.ready);
hs.addEventListener(window,'load',hs.ready);
hs.langDefaults=hs.lang;

var HsExpander=hs.Expander;


hs.addEventListener(window,'load',function(){
if(hs.expandCursor){
var sel='.highslide img',
dec='cursor: url('+hs.graphicsDir+hs.expandCursor+'), pointer !important;';

var style=hs.createElement('style',{type:'text/css'},null,
document.getElementsByTagName('HEAD')[0]);

if(!hs.ie){
style.appendChild(document.createTextNode(sel+" {"+dec+"}"))}else{
var last=document.styleSheets[document.styleSheets.length-1];
if(typeof(last.addRule)=="object")last.addRule(sel,dec)}
}
});
hs.addEventListener(window,'resize',function(){
hs.getPageSize()});
hs.addEventListener(document,'mousemove',function(e){
hs.mouse={x:e.clientX,y:e.clientY}});
hs.addEventListener(document,'mousedown',hs.mouseClickHandler);
hs.addEventListener(document,'mouseup',hs.mouseClickHandler);

hs.addEventListener(document,'ready',hs.getAnchors);
hs.addEventListener(window,'load',hs.preloadImages);
hs.addEventListener(window,'load',hs.preloadAjax);


if(typeof infosoftglobal=="undefined")var infosoftglobal=new Object();
if(typeof infosoftglobal.FusionChartsUtil=="undefined")infosoftglobal.FusionChartsUtil=new Object();
infosoftglobal.FusionCharts=function(swf,id,w,h,debugMode,registerWithJS,c,scaleMode,lang){
if(!document.getElementById){return}


this.initialDataSet=false;


this.params=new Object();
this.variables=new Object();
this.attributes=new Array();


if(swf){this.setAttribute('swf',swf)}
if(id){this.setAttribute('id',id)}
if(w){this.setAttribute('width',w)}
if(h){this.setAttribute('height',h)}


if(c){this.addParam('bgcolor',c)}


this.addParam('quality','high');


this.addParam('allowScriptAccess','always');

this.addParam('wmode','transparent');


this.addVariable('chartWidth',w);
this.addVariable('chartHeight',h);


debugMode=debugMode?debugMode:0;
this.addVariable('debugMode',debugMode);

this.addVariable('DOMId',id);

registerWithJS=registerWithJS?registerWithJS:0;
this.addVariable('registerWithJS',registerWithJS);


scaleMode=scaleMode?scaleMode:'noScale';
this.addVariable('scaleMode',scaleMode);

lang=lang?lang:'EN';
this.addVariable('lang',lang)};

infosoftglobal.FusionCharts.prototype={
setAttribute:function(name,value){
this.attributes[name]=value},
getAttribute:function(name){
return this.attributes[name]},
addParam:function(name,value){
this.params[name]=value},
getParams:function(){
return this.params},
addVariable:function(name,value){
this.variables[name]=value},
getVariable:function(name){
return this.variables[name]},
getVariables:function(){
return this.variables},
getVariablePairs:function(){
var variablePairs=new Array();
var key;
var variables=this.getVariables();
for(key in variables){
variablePairs.push(key+"="+variables[key])}
return variablePairs},
getSWFHTML:function(){
var swfNode="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){

swfNode='<embed type="application/x-shockwave-flash" src="'+this.getAttribute('swf')+'" width="'+this.getAttribute('width')+'" height="'+this.getAttribute('height')+'"  ';
swfNode+=' id="'+this.getAttribute('id')+'" name="'+this.getAttribute('id')+'" ';
var params=this.getParams();
for(var key in params){swfNode+=[key]+'="'+params[key]+'" '}
var pairs=this.getVariablePairs().join("&");
if(pairs.length>0){swfNode+='flashvars="'+pairs+'"'}
swfNode+='/>'}else{
swfNode='<object id="'+this.getAttribute('id')+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+this.getAttribute('width')+'" height="'+this.getAttribute('height')+'">';
swfNode+='<param name="movie" value="'+this.getAttribute('swf')+'" />';
var params=this.getParams();
for(var key in params){
swfNode+='<param name="'+key+'" value="'+params[key]+'" />'}
var pairs=this.getVariablePairs().join("&");
if(pairs.length>0){swfNode+='<param name="flashvars" value="'+pairs+'" />'}
swfNode+="</object>"}
return swfNode},
setDataURL:function(strDataURL){


if(this.initialDataSet==false){
this.addVariable('dataURL',strDataURL);

this.initialDataSet=true}else{


var chartObj=infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
chartObj.setDataURL(strDataURL)}
},
setDataXML:function(strDataXML){

if(this.initialDataSet==false){

this.addVariable('dataXML',strDataXML);

this.initialDataSet=true}else{


var chartObj=infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
chartObj.setDataXML(strDataXML)}
},
render:function(elementId){
var n=(typeof elementId=='string')?document.getElementById(elementId):elementId;
n.innerHTML=this.getSWFHTML();
return true}
};



infosoftglobal.FusionChartsUtil.cleanupSWFs=function(){
if(window.opera||!document.all)return;
var objects=document.getElementsByTagName("OBJECT");
for(var i=0;i<objects.length;i++){
objects[i].style.display='none';
for(var x in objects[i]){
if(typeof objects[i][x]=='function'){
objects[i][x]=function(){}}
}
}
};


infosoftglobal.FusionChartsUtil.prepUnload=function(){
__flash_unloadHandler=function(){};
__flash_savedUnloadHandler=function(){};
if(typeof window.onunload=='function'){
var oldUnload=window.onunload;
window.onunload=function(){
infosoftglobal.FusionChartsUtil.cleanupSWFs();
oldUnload()}
}else{
window.onunload=infosoftglobal.FusionChartsUtil.cleanupSWFs}
};

if(typeof window.onbeforeunload=='function'){
var oldBeforeUnload=window.onbeforeunload;
window.onbeforeunload=function(){
infosoftglobal.FusionChartsUtil.prepUnload();
oldBeforeUnload()}
}else{
window.onbeforeunload=infosoftglobal.FusionChartsUtil.prepUnload}


if(Array.prototype.push==null){Array.prototype.push=function(item){this[this.length]=item;return this.length}}


infosoftglobal.FusionChartsUtil.getChartObject=function(id)
{
if(window.document[id]){
return window.document[id]}
if(navigator.appName.indexOf("Microsoft Internet")==-1){
if(document.embeds&&document.embeds[id])
return document.embeds[id]}else{
return document.getElementById(id)}
};


var getChartFromId=infosoftglobal.FusionChartsUtil.getChartObject;
var FusionCharts=infosoftglobal.FusionCharts;



if(typeof deconcept=="undefined")var deconcept=new Object();
if(typeof deconcept.util=="undefined")deconcept.util=new Object();
if(typeof deconcept.SWFObjectUtil=="undefined")deconcept.SWFObjectUtil=new Object();
deconcept.SWFObject=function(swf,id,w,h,ver,c,quality,xiRedirectUrl,redirectUrl,detectKey){
if(!document.getElementById){return}
this.DETECT_KEY=detectKey?detectKey:'detectflash';
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(swf){this.setAttribute('swf',swf)}
if(id){this.setAttribute('id',id)}
if(w){this.setAttribute('width',w)}
if(h){this.setAttribute('height',h)}
if(ver){this.setAttribute('version',new deconcept.PlayerVersion(ver.toString().split(".")))}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
if(!window.opera&&document.all&&this.installedVer.major>7){
deconcept.SWFObject.doPrepUnload=true}
if(c){this.addParam('bgcolor',c)}
var q=quality?quality:'high';
this.addParam('quality',q);
this.setAttribute('useExpressInstall',false);
this.setAttribute('doExpressInstall',false);
var xir=(xiRedirectUrl)?xiRedirectUrl:window.location;
this.setAttribute('xiRedirectUrl',xir);
this.setAttribute('redirectUrl','');
if(redirectUrl){this.setAttribute('redirectUrl',redirectUrl)}
};

deconcept.SWFObject.prototype={
useExpressInstall:function(path){
this.xiSWFPath=!path?"expressinstall.swf":path;
this.setAttribute('useExpressInstall',true)},
setAttribute:function(name,value){
this.attributes[name]=value},
getAttribute:function(name){
return this.attributes[name]},
addParam:function(name,value){
this.params[name]=value},
getParams:function(){
return this.params},
addVariable:function(name,value){
this.variables[name]=value},
getVariable:function(name){
return this.variables[name]},
getVariables:function(){
return this.variables},
getVariablePairs:function(){
var variablePairs=new Array();
var key;
var variables=this.getVariables();
for(key in variables){
variablePairs.push(key+"="+variables[key])}
return variablePairs},
getSWFHTML:function(){
var swfNode="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","PlugIn");
this.setAttribute('swf',this.xiSWFPath)}
swfNode='<embed type="application/x-shockwave-flash" src="'+this.getAttribute('swf')+'" width="'+this.getAttribute('width')+'" height="'+this.getAttribute('height')+'"';
swfNode+=' id="'+this.getAttribute('id')+'" name="'+this.getAttribute('id')+'" ';
var params=this.getParams();
for(var key in params){swfNode+=[key]+'="'+params[key]+'" '}
var pairs=this.getVariablePairs().join("&");
if(pairs.length>0){swfNode+='flashvars="'+pairs+'"'}
swfNode+='/>'}else{if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","ActiveX");
this.setAttribute('swf',this.xiSWFPath)}
swfNode='<object id="'+this.getAttribute('id')+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+this.getAttribute('width')+'" height="'+this.getAttribute('height')+'">';
swfNode+='<param name="movie" value="'+this.getAttribute('swf')+'" />';
var params=this.getParams();
for(var key in params){
swfNode+='<param name="'+key+'" value="'+params[key]+'" />'}
var pairs=this.getVariablePairs().join("&");
if(pairs.length>0){swfNode+='<param name="flashvars" value="'+pairs+'" />'}
swfNode+="</object>"}
return swfNode},
write:function(elementId){
if(this.getAttribute('useExpressInstall')){
var expressInstallReqVer=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(expressInstallReqVer)&&!this.installedVer.versionIsValid(this.getAttribute('version'))){
this.setAttribute('doExpressInstall',true);
this.addVariable("MMredirectURL",escape(this.getAttribute('xiRedirectUrl')));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title)}
}
if(this.skipDetect||this.getAttribute('doExpressInstall')||this.installedVer.versionIsValid(this.getAttribute('version'))){
var n=(typeof elementId=='string')?document.getElementById(elementId):elementId;
n.innerHTML=this.getSWFHTML();
return true}else{
if(this.getAttribute('redirectUrl')!=""){
document.location.replace(this.getAttribute('redirectUrl'))}
}
return false}
};


deconcept.SWFObjectUtil.getPlayerVersion=function(){
var PlayerVersion=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){
PlayerVersion=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."))}
}else{
try{
var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")}catch(e){
try{
var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
PlayerVersion=new deconcept.PlayerVersion([6,0,21]);
axo.AllowScriptAccess="always"}catch(e){
if(PlayerVersion.major==6){
return PlayerVersion}
}
try{
axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(e){}
}
if(axo!=null){
PlayerVersion=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","))}
}
return PlayerVersion};

deconcept.PlayerVersion=function(arrVersion){
this.major=arrVersion[0]!=null?parseInt(arrVersion[0]):0;
this.minor=arrVersion[1]!=null?parseInt(arrVersion[1]):0;
this.rev=arrVersion[2]!=null?parseInt(arrVersion[2]):0};

deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major)return false;
if(this.major>fv.major)return true;
if(this.minor<fv.minor)return false;
if(this.minor>fv.minor)return true;
if(this.rev<fv.rev)return false;
return true};


deconcept.util={
getRequestParameter:function(param){
var q=document.location.search||document.location.hash;
if(q){
var pairs=q.substring(1).split("&");
for(var i=0;i<pairs.length;i++){
if(pairs[i].substring(0,pairs[i].indexOf("="))==param){
return pairs[i].substring((pairs[i].indexOf("=")+1))}
}
}
return""}
};


deconcept.SWFObjectUtil.cleanupSWFs=function(){
var objects=document.getElementsByTagName("OBJECT");
for(var i=0;i<objects.length;i++){
objects[i].style.display='none';
for(var x in objects[i]){
if(typeof objects[i][x]=='function'){
objects[i][x]=function(){}}
}
}
};

if(deconcept.SWFObject.doPrepUnload){
deconcept.SWFObjectUtil.prepUnload=function(){
__flash_unloadHandler=function(){};
__flash_savedUnloadHandler=function(){};
window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs)};

window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload)};


if(Array.prototype.push==null){Array.prototype.push=function(item){this[this.length]=item;return this.length}}


var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;






if(typeof Prototype=='undefined')
alert("CalendarDateSelect Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (e.g. <%= javascript_include_tag :defaults %>) *before* it includes calendar_date_select.js (e.g. <%= calendar_date_select_includes %>).");

Element.addMethods({
purgeChildren:function(element){$A(element.childNodes).each(function(e){$(e).remove()})},
build:function(element,type,options,style){
newElement=Element.buildAndAppend(type,options,style);
element.appendChild(newElement);
return newElement}
});

Element.buildAndAppend=function(type,options,style){
var e=$(document.createElement(type));
$H(options).each(function(pair){eval("e."+pair.key+" = pair.value")});
if(style)
$H(style).each(function(pair){eval("e.style."+pair.key+" = pair.value")});
return e};

nil=null;

Date.one_day=24*60*60*1000;
Date.holidays=new Array;
Date.weekdays=$w("S M T W T F S");
Date.first_day_of_week=0;
Date.months=$w("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
Date.padded2=function(hour){var padded2=hour.toString();if(parseInt(hour)<10)padded2="0"+padded2;return padded2};
Date.prototype.getPaddedMinutes=function(){return Date.padded2(this.getMinutes())};
Date.prototype.getAMPMHour=function(){var hour=this.getHours();return(hour==0)?12:(hour>12?hour-12:hour)};
Date.prototype.getAMPM=function(){return(this.getHours()<12)?"AM":"PM"};
Date.prototype.stripTime=function(){return new Date(this.getFullYear(),this.getMonth(),this.getDate())};
Date.prototype.daysDistance=function(compare_date){return Math.round((compare_date-this)/Date.one_day)};
Date.prototype.toFormattedString=function(include_time){
str=Date.months[this.getMonth()]+" "+this.getDate()+", "+this.getFullYear();

if(include_time){hour=this.getHours();str+=" "+this.getAMPMHour()+":"+this.getPaddedMinutes()+" "+this.getAMPM()}
return str};

Date.parseFormattedString=function(string){return new Date(string)};
window.f_height=function(){return([window.innerHeight?window.innerHeight:null,document.documentElement?document.documentElement.clientHeight:null,document.body?document.body.clientHeight:null].select(function(x){return x>0}).first()||0)};
window.f_scrollTop=function(){return([window.pageYOffset?window.pageYOffset:null,document.documentElement?document.documentElement.scrollTop:null,document.body?document.body.scrollTop:null].select(function(x){return x>0}).first()||0)};

_translations={
"OK":"OK",
"Now":"Now",
"Today":"Today"
};

CalendarDateSelect=Class.create();
CalendarDateSelect.prototype={
initialize:function(target_element,options){
this.target_element=$(target_element);


if(options.start_year!=undefined){
this.isStartYear=true}


this.options=$H({
embedded:false,
time:false,
buttons:true,
year_range:0,
start_year:2007,
calendar_div:nil,
close_on_click:nil,
minute_interval:5,
onchange:this.target_element.onchange
}).merge(options||{});


var currDate=new Date();
this.current_year=currDate.getFullYear();

this.selection_made=$F(this.target_element)!="";

if(this.target_element.calendar_date_select){
this.target_element.calendar_date_select.close();
return false}

this.target_element.calendar_date_select=this;
this.callback("before_show");
this.calendar_div=$(this.options.get('calendar_div'));

if(!this.target_element){
alert("Target element "+target_element+" not found!");
return false}

this.parseDate();


if(this.calendar_div==nil){
this.calendar_div=$(this.options.embedded?this.target_element.parentNode:document.body).build('div')}

if(!this.options.get('embedded')){
this.calendar_div.setStyle({position:"absolute",visibility:"hidden"});
this.positionCalendarDiv()}

this.calendar_div.addClassName("calendar_date_select");

if(this.options.get('embedded')){
this.options.set('close_on_click',false)}


if(this.options.get('close_on_click')===nil){
if(this.options.get('time')){
this.options.set('close_on_click',false)}

else{
this.options.set('close_on_click',true)}
}


if(!this.options.get('embedded')){
Event.observe(document.body,"mousedown",this.bodyClick_handler=this.bodyClick.bindAsEventListener(this))}

this.initFrame();

if(!this.options.get('embedded')){
this.positionCalendarDiv(true)}

this.callback("after_show")},

positionCalendarDiv:function(post_painted){
above=false;
c_pos=Element.cumulativeOffset(this.target_element);
c_left=c_pos[0];
c_top=c_pos[1];
c_dim=this.calendar_div.getDimensions();
c_height=c_dim.height;
c_width=c_dim.width;
w_top=window.f_scrollTop();
w_height=window.f_height();
e_dim=Element.cumulativeOffset(this.target_element);
e_top=e_dim[1];
e_left=e_dim[0];

if((post_painted)&&((c_top+c_height)>(w_top+w_height))&&(c_top-c_height>w_top)){
above=true}

left_px=e_left.toString()+"px";
top_px=(above?(e_top-c_height):(e_top+this.target_element.getDimensions().height)).toString()+"px";

this.calendar_div.style.left=left_px;this.calendar_div.style.top=top_px;


if(post_painted){
this.iframe=$(document.body).build("iframe",{},{position:"absolute",left:left_px,top:top_px,height:c_height.toString()+"px",width:c_width.toString()+"px",border:"0px"});
this.calendar_div.setStyle({visibility:""})}
},

initFrame:function(){
that=this;

$w("header body").each(function(name){
eval(name+"_div = that."+name+"_div = that.calendar_div.build('div', { className: 'cds_"+name+"' }, { clear: 'left'} ); ")});


this.next_month_button=header_div.build("input",{type:"button",value:">",className:"next"});
this.prev_month_button=header_div.build("input",{type:"button",value:"<",className:"prev"});
this.month_select=header_div.build("select",{className:"month"});
this.year_select=header_div.build("select",{className:"year"});


for(x=0;x<12;x++){
this.month_select.options[x]=new Option(Date.months[x],x)}

Event.observe(this.prev_month_button,'mousedown',function(){this.navMonth(this.date.getMonth()-1)}.bindAsEventListener(this));
Event.observe(this.next_month_button,'mousedown',function(){this.navMonth(this.date.getMonth()+1)}.bindAsEventListener(this));
Event.observe(this.month_select,'change',(function(){this.navMonth($F(this.month_select))}).bindAsEventListener(this));
Event.observe(this.year_select,'change',(function(){this.navYear($F(this.year_select))}).bindAsEventListener(this));


this.calendar_day_grid=[];
days_table=body_div.build("table",{cellPadding:"0px",cellSpacing:"0px",width:"100%"}).build("tbody");


weekdays_row=days_table.build("tr",{className:"weekdays"});
Date.weekdays.each(function(weekday){
weekdays_row.build("td",{innerHTML:weekday})});


for(cell_index=0;cell_index<42;cell_index++){
weekday=(cell_index+Date.first_day_of_week)%7;
if(cell_index%7==0)days_row=days_table.build("tr",{className:"days"});

(this.calendar_day_grid[cell_index]=days_row.build("td",{
calendar_date_select:this,
onmouseover:function(){this.calendar_date_select.dayHover(this)},
onmouseout:function(){this.calendar_date_select.dayHoverOut(this)},
onclick:function(){this.calendar_date_select.updateSelectedDate(this)},
className:(weekday==0)||(weekday==6)?" weekend":""
}
)).build("div")}
this.refresh()},

allowCloseButtons:function(){
return(!this.options.get('embedded')&&this.options.get('time'))},

dateString:function(){
return(this.selection_made)?this.selected_date.toFormattedString(this.options.get('time')):"&nbsp;"},

navMonth:function(month){
month=parseInt(month);
prev_day=this.date.getDate();


if(month>11&&this.date.getFullYear()==this.maxYear||month==-1&&this.date.getFullYear()==this.options.get('start_year')){
return}

this.date.setMonth(month);


var lastDay=this.getLastDayOfTheMonth(this.date.getFullYear(),month);


this.updateSelectedDate({day:(this.calendar_div.id=='calendar2'?lastDay:1),month:month,year:this.date.getFullYear()},true);

this.refresh();
this.callback("after_navigate",this.date)},

navYear:function(year){
year=parseInt(year);
this.date.setYear(year);


var lastDay=this.getLastDayOfTheMonth(year,this.date.getMonth());


this.updateSelectedDate({day:(this.calendar_div.id=='calendar2'?lastDay:1),month:this.date.getMonth(),year:year},true);

this.refresh();
this.callback("after_navigate",this.date)},

getLastDayOfTheMonth:function(year,month){
var dd=new Date(year,month+1,0);
return dd.getDate()},

setYearRangeValue:function(value){
var e=$(this.year_select);
var matched=false;
$R(0,e.options.length-1).each(function(i){if(e.options[i].value==value.toString()){e.selectedIndex=i;matched=true}});
return matched},

populateYearRange:function(selectedYear){


if(this.options.get('year_range')==0){
var values=this.startYearRange().toArray()}
else{
var values=this.yearRange(selectedYear).toArray()}

this.element=$(this.year_select);
var that=this;$A(values.reverse()).each(function(pair){if(typeof(pair)!="object"){pair=[pair,pair]};that.element.build("option",{value:pair[1],innerHTML:pair[0]})})},

yearRange:function(value){
return $R(value-this.options.get("year_range"),value+this.options.get("year_range"))},

startYearRange:function(){
return $R(this.options.get("start_year"),this.current_year)},

refresh:function(){

this.month_select.selectedIndex=this.date.getMonth();
this.maxYear=this.current_year+this.options.get('year_range');


if(this.date.getFullYear()>this.maxYear){
this.date.setYear(this.current_year)}
else if(this.date.getFullYear()<this.options.get('start_year')){
this.date.setYear(this.options.get('start_year'))}


this.year_select.purgeChildren();


if(this.isStartYear==true&&this.options.get('year_range')!=0){
var selectedYear=this.options.get("start_year")}
else{
var selectedYear=this.current_year}

this.populateYearRange(selectedYear);
this.setYearRangeValue(this.date.getFullYear());


this.beginning_date=new Date(this.date).stripTime();
this.beginning_date.setDate(1);
pre_days=this.beginning_date.getDay();
if(pre_days<3){
pre_days+=7}

this.beginning_date.setDate(1-pre_days+Date.first_day_of_week);

iterator=new Date(this.beginning_date);

today=new Date().stripTime();
this_month=this.date.getMonth();
for(cell_index=0;cell_index<42;cell_index++){
day=iterator.getDate();month=iterator.getMonth();year=iterator.getFullYear();
cell=this.calendar_day_grid[cell_index];

Element.remove(cell.childNodes[0]);div=cell.build("div",{innerHTML:day});

if(month!=this_month)div.className="other";

if(Date.holidays!=''){

if(month+1<10){
var dateMonth='0'+(month+1)}
else{
var dateMonth=(month+1)}

if(day<10){
var dateDay='0'+day}
else{
var dateDay=day}

if(Date.holidays.inArray(year+'-'+dateMonth+'-'+dateDay)){

if(month!=this_month){
div.className='otherHoliday'}
else{
div.className='holiday'}
}
}

cell.day=day;cell.month=month;cell.year=year;
iterator.setDate(day+1)}

if(this.today_cell){
this.today_cell.removeClassName("today")}

if($R(0,41).include(days_until=this.beginning_date.daysDistance(today))){
this.today_cell=this.calendar_day_grid[days_until];
this.today_cell.addClassName("today")}

this.setSelectedClass()},

dayHover:function(element){
element.addClassName("hover");
hover_date=new Date(this.selected_date);
hover_date.setYear(element.year);
hover_date.setMonth(element.month);
hover_date.setDate(element.day)},

dayHoverOut:function(element){
element.removeClassName("hover")},

setSelectedClass:function(){
if(!this.selection_made){
return}


if(this.selected_cell){
this.selected_cell.removeClassName("selected")}

if($R(0,42).include(days_until=this.beginning_date.daysDistance(this.selected_date.stripTime()))){
this.selected_cell=this.calendar_day_grid[days_until];
this.selected_cell.addClassName("selected")}
},

reparse:function(){
this.parseDate();
this.refresh()},

parseDate:function(){
this.date=Date.parseFormattedString(this.options.get('date')||$F(this.target_element));
if(isNaN(this.date)){
this.date=new Date()}

this.selected_date=new Date(this.date);
this.date.setDate(1)},

updateSelectedDate:function(parts,preventClose){

if(parts.day){
this.selection_made=true;
for(x=0;x<=1;x++){
this.selected_date.setDate(parts.day);
this.selected_date.setMonth(parts.month);
this.selected_date.setYear(parts.year)}
}

this.setSelectedClass();

if(this.selection_made){
this.updateValue()}

if(!preventClose&&this.options.get('close_on_click')){
this.close()}
},

updateValue:function(){
last_value=this.target_element.value;
this.target_element.value=this.dateString();
if(last_value!=this.target_element.value){
this.callback("onchange")}
},

today:function(){
this.date=new Date();
d=new Date();
this.updateSelectedDate({day:d.getDate(),month:d.getMonth(),year:d.getFullYear()});
this.refresh()},

close:function(){
this.callback("before_close");
this.target_element.calendar_date_select=nil;
Event.stopObserving(document.body,"mousedown",this.bodyClick_handler);
this.calendar_div.remove();
if(this.iframe){
this.iframe.remove()}

this.callback("after_close")},
bodyClick:function(e){
if(!$(Event.element(e)).descendantOf(this.calendar_div)){
this.close()}
},

callback:function(name,param){
if(this.options.get(name)){
this.options.get(name).bind(this.target_element)(param)}
}
};




var jsDateSelect=Class.create();
jsDateSelect.prototype={
initialize:function(){},


checkDateRange:function(fromDate,toDate){
if(toDate<fromDate){
var msg='Selected date range is incorrect. Ending date cannot be earlier than beginning date.';
try{
alert(_(msg))}catch(e){
alert(msg)}

return false}

return true},



toggleCalendar:function(event){
var dateInfo=$('dateInfo');
var dateSelect=$('dateSelect');

if(dateSelect.visible()){
this.hideCalendar()}

else{
this.showCalendar()}

dateInfo&&dateInfo.focus()},



hideCalendar:function(){
var dateSelect=$('dateSelect');
var dateInfo=$('dateInfo');

dateSelect.hide();
if(dateInfo){
Element.removeClassName(dateInfo,'selectOpen');
Element.addClassName(dateInfo,'selectClose')}

Event.stopObserving(document.body,'click',DateSelect.hidingObserver)},



showCalendar:function(){
var dateSelect=$('dateSelect');
var dateInfo=$('dateInfo');

dateSelect.show();
if(dateInfo){
Element.removeClassName(dateInfo,'selectClose');
Element.addClassName(dateInfo,'selectOpen')}

Event.observe(document.body,'click',DateSelect.hidingObserver)},



dateParse:function(inputDate){
var month=inputDate.getMonth()+1;
if(month<10)
month='0'+month;
var day=inputDate.getDate();
if(day<10)
day='0'+day;
return inputDate.getFullYear()+'-'+month+'-'+day},



selectDateRange:function(range){
try{
var fromDate,toDate;
var now=new Date();

switch(range){
case'thisWeek':
toDate=now.toFormattedString();
now.setDate(now.getDate()-now.getDay());
fromDate=now.toFormattedString();
break;
case'lastWeek':
now.setDate(now.getDate()-now.getDay()-1);
toDate=now.toFormattedString();
now.setDate(now.getDate()-6);
fromDate=now.toFormattedString();
break;
case'thisMonth':
toDate=now.toFormattedString();
now.setDate(1);
fromDate=now.toFormattedString();
break;
case'lastMonth':
now.setDate(1);
now.setMonth(now.getMonth()-1);
fromDate=now.toFormattedString();
now.setMonth(now.getMonth()+1);
now.setDate(now.getDate()-1);
toDate=now.toFormattedString();
break;
default:
break}

$('fDateDaily').value=fromDate;
$('tDateDaily').value=toDate;

calendar1.reparse();
calendar2.reparse();

$('fromDate').value=this.dateParse(calendar1.selected_date);
$('toDate').value=this.dateParse(calendar2.selected_date);

Wait.show('dateSelect');
$('dateSelectForm').submit()}

catch(e){
exceptionAlert('Error in function: selectDateRange().',e)}

return false},

selectMonthRange:function(range){
try{
var fromDate,toDate;
var now=new Date();

switch(range){
case'thisYear':
fromDate="Jan, "+now.getFullYear();
toDate=Date.months[now.getMonth()]+", "+now.getFullYear();
break;
case'lastYear':
var lastYear=now.getFullYear()-1;
fromDate="Jan, "+lastYear;
toDate="Dec, "+lastYear;
break;
case'thisHalfYear':
if(now.getMonth()<6){
fromDate="Jan, "+now.getFullYear();
toDate="Jun, "+now.getFullYear()}

else{
fromDate="Jul, "+now.getFullYear();
toDate="Dec, "+now.getFullYear()}
break;
case'lastHalfYear':
if(now.getMonth()<6){
var lastYear=now.getFullYear()-1;
fromDate="Jul, "+lastYear;
toDate="Dec, "+lastYear}

else{
fromDate="Jan, "+now.getFullYear();
toDate="Jun, "+now.getFullYear()}
break;
default:
break}

$('fDateMonthly').value=fromDate;
$('tDateMonthly').value=toDate;

calendar3.reparse();
calendar4.reparse();

$('fromDate').value=this.dateParse(calendar3.selected_date);
$('toDate').value=this.dateParse(calendar4.selected_date);

Wait.show('dateSelect');
$('dateSelectForm').submit()}

catch(e){
exceptionAlert('Error in function: selectMonthRange().',e)}

return false},

switchToDaily:function(){
try{
$('dateSelectInner').show();
$('monthSelectInner').hide();
$('calendarType').value='daily';
$('dateSelectDaily').addClassName('selectedTab');
$('dateSelectMonthly').removeClassName('selectedTab')}

catch(e){
exceptionAlert('Error in function: switchToDaily().',e)}

return false},

switchToMonthly:function(){
try{
$('dateSelectInner').hide();
$('monthSelectInner').show();
$('calendarType').value='monthly';
$('dateSelectDaily').removeClassName('selectedTab');
$('dateSelectMonthly').addClassName('selectedTab')}

catch(e){
exceptionAlert('Error in function: switchToMonthly().',e)}

return false},

checkNsubmit:function(fromDate,toDate){
var result=this.checkDateRange(fromDate,toDate);

if(result){
Wait.show('dateSelect');
return true}

return result}
};

var DateSelect=new jsDateSelect();

DateSelect.hidingObserver=function(event){
var elt=Event.element(event);
if(elt&&elt.id!='dateInfo'&&elt.id!='dateSelect'&&!Element.descendantOf(elt,$('dateSelect'))&&!Element.descendantOf(elt,$('dateInfo'))){
Event.stop(event);
DateSelect.hideCalendar()}
}.bindAsEventListener(DateSelect);


Date.months=$w("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");



mCalendar=Class.create();
mCalendar.prototype={
initialize:function(target_element,options){
this.target_element=$(target_element);
if(options.start_year!=undefined){
this.isStartYear=true}

this.options=$H({
embedded:false,
buttons:true,
year_range:0,
start_year:2007,
calendar_div:nil,
close_on_click:nil,
onchange:this.target_element.onchange
}).merge(options||{});

var currDate=new Date();
this.current_year=currDate.getFullYear();

this.selection_made=$F(this.target_element)!="";

if(this.target_element.calendar_date_select){
this.target_element.calendar_date_select.close();
return false}

this.target_element.calendar_date_select=this;
this.callback("before_show");
this.calendar_div=$(this.options.get('calendar_div'));

if(!this.target_element){
alert("Target element "+target_element+" not found!");
return false}

this.parseDate();

if(this.calendar_div==nil){
this.calendar_div=$(this.options.embedded?this.target_element.parentNode:document.body).build('div')}

if(!this.options.get('embedded')){
this.calendar_div.setStyle({position:"absolute",visibility:"hidden"});
this.positionCalendarDiv()}

this.calendar_div.addClassName("calendar_date_select");

if(this.options.get('embedded')){
this.options.set('close_on_click',false)}

if(this.options.get('close_on_click')===nil){
if(this.options.get('time')){
this.options.set('close_on_click',false)}

else{
this.options.set('close_on_click',true)}
}

if(!this.options.get('embedded')){
Event.observe(document.body,"mousedown",this.bodyClick_handler=this.bodyClick.bindAsEventListener(this))}

this.initFrame();

if(!this.options.get('embedded')){
this.positionCalendarDiv(true)}

this.callback("after_show")},

initFrame:function(){
that=this;
$w("header body").each(function(name){
eval(name+"_div = that."+name+"_div = that.calendar_div.build('div', { className: 'cds_"+name+"' }, { clear: 'left'} ); ")});

this.next_month_button=header_div.build("input",{type:"button",value:">",className:"next"});
this.prev_month_button=header_div.build("input",{type:"button",value:"<",className:"prev"});
this.year_select=header_div.build("select",{className:"year"});

Event.observe(this.prev_month_button,'mousedown',function(){this.navYear(this.date.getFullYear()-1)}.bindAsEventListener(this));
Event.observe(this.next_month_button,'mousedown',function(){this.navYear(this.date.getFullYear()+1)}.bindAsEventListener(this));
Event.observe(this.year_select,'change',(function(){this.navYear($F(this.year_select))}).bindAsEventListener(this));

this.calendar_day_grid=[];
days_table=body_div.build("table",{cellPadding:"0px",cellSpacing:"0px",width:"100%"}).build("tbody");

for(cell_index=0;cell_index<12;cell_index++){
if(cell_index%4==0){
months_row=days_table.build("tr",{className:"months"})}

(this.calendar_day_grid[cell_index]=months_row.build("td",{
calendar_date_select:this,
onmouseover:function(){this.calendar_date_select.monthHover(this)},
onmouseout:function(){this.calendar_date_select.monthHoverOut(this)},
onclick:function(){this.calendar_date_select.updateSelectedDate(this)},
className:""
}
)).build("div")}

this.refresh()},

refresh:function(){
this.maxYear=this.current_year+this.options.get('year_range');

if(this.date.getFullYear()>this.maxYear){
this.date.setYear(this.current_year)}
else if(this.date.getFullYear()<this.options.get('start_year')){
this.date.setYear(this.options.get('start_year'))}

this.year_select.purgeChildren();

if(this.isStartYear==true&&this.options.get('year_range')!=0){
var selectedYear=this.options.get("start_year")}
else{
var selectedYear=this.current_year}

this.populateYearRange(selectedYear);
this.setYearRangeValue(this.date.getFullYear());

for(x=0;x<12;x++){
cell=this.calendar_day_grid[x];

var year=this.date.getFullYear();
var default_day=this.getDefaultDayOfTheMonth(year,x);

cell.day=default_day;
cell.month=x;
cell.year=year;
Element.remove(cell.childNodes[0]);div=cell.build("div",{innerHTML:Date.months[x]})}

if(this.this_month_cell){
this.this_month_cell.removeClassName("today")}

if(this.date.getFullYear()==this.current_year){
this.beginning_date=new Date().stripTime();
this.beginning_date.setDate(1);

this.this_month_cell=this.calendar_day_grid[this.beginning_date.getMonth()];
this.this_month_cell.addClassName("today")}

this.setSelectedClass()},

getDefaultDayOfTheMonth:function(year,month){
var default_day=this.options.get('default_day');

if(default_day=='first'){
default_day=1}
else if(default_day=='last'){
default_day=this.getLastDayOfTheMonth(year,month)}
else{
default_day=parseInt(default_day);
if(default_day=='NaN'){
default_day=1}
}

return default_day},

setYearRangeValue:function(value){
var e=$(this.year_select);
var matched=false;
$R(0,e.options.length-1).each(function(i){if(e.options[i].value==value.toString()){e.selectedIndex=i;matched=true}});
return matched},

populateYearRange:function(selectedYear){

if(this.options.get('year_range')==0){
var values=this.startYearRange().toArray()}
else{
var values=this.yearRange(selectedYear).toArray()}

this.element=$(this.year_select);
var that=this;
$A(values.reverse()).each(function(pair){if(typeof(pair)!="object"){pair=[pair,pair]};that.element.build("option",{value:pair[1],innerHTML:pair[0]})})},

startYearRange:function(){
return $R(this.options.get("start_year"),this.current_year)},

monthHover:function(element){
element.addClassName("hover");
hover_date=new Date(this.selected_date);
hover_date.setYear(element.year);
hover_date.setMonth(element.month);
hover_date.setDate(element.day)},

monthHoverOut:function(element){
element.removeClassName("hover")},

navYear:function(year){
year=parseInt(year);

if(year>this.current_year||year<this.options.get('start_year')){
return}

this.date.setYear(year);

if(this.selected_cell){
this.updateSelectedDate({day:this.getDefaultDayOfTheMonth(year,this.selected_date.getMonth()),month:this.selected_date.getMonth(),year:year},true)}

this.refresh();
this.callback("after_navigate",this.date)},

getLastDayOfTheMonth:function(year,month){
var dd=new Date(year,month+1,0);
return dd.getDate()},

setSelectedClass:function(){
if(!this.selection_made){
return}

if(this.selected_cell){
this.selected_cell.removeClassName("selected")}

this.selected_cell=this.calendar_day_grid[this.selected_date.getMonth()];
this.selected_cell.addClassName("selected")},

parseDate:function(){
var d=this.options.get('date')||$F(this.target_element);
var parts=d.split(', ');
var month=Date.months.indexOf(parts[0]);
var year=parts[1];
var day=this.getDefaultDayOfTheMonth(year,month);

this.date=new Date();
this.date.setDate(day);
this.date.setMonth(month);
this.date.setYear(year);
this.selected_date=new Date(this.date)},

updateSelectedDate:function(parts,preventClose){
if(parts.month||parts.month==0){
this.selection_made=true;
for(x=0;x<=1;x++){
this.selected_date.setDate(parts.day);
this.selected_date.setMonth(parts.month);
this.selected_date.setYear(parts.year)}
}

this.setSelectedClass();

if(this.selection_made){
this.updateValue()}

if(!preventClose&&this.options.get('close_on_click')){
this.close()}
},

updateValue:function(){
last_value=this.target_element.value;

this.target_element.value=this.dateString();

if(last_value!=this.target_element.value){
this.callback("onchange")}
},

dateString:function(){
return(this.selection_made)?Date.months[this.selected_date.getMonth()]+", "+this.selected_date.getFullYear():"&nbsp;"},

reparse:function(){
this.parseDate();
this.refresh()},

callback:function(name,param){
if(this.options.get(name)){
this.options.get(name).bind(this.target_element)(param)}
}
};





Object.extend(Element,{

center:function(element,area){
try{
if(typeof element!="object"){
element=$(element)}

if(!area){
Element.viewportCenter(element)}
else{
element.style.top=Math.floor((Element.getHeight(area)-Element.getHeight(element))/2)+'px';
element.style.left=Math.floor((Element.getWidth(area)-Element.getWidth(element))/2)+'px'}
}

catch(e){
exceptionAlert('Element.center() exception.',e)}
},

centerViaAreaInViewport:function(element,area){
try{
if(typeof element!="object"){
element=$(element)}

if(area){
var dimensions=document.viewport.getDimensions();
var scrollOffset=document.viewport.getScrollOffsets();
var areaCoords=area.cumulativeOffset();
var areaDimensions=area.getDimensions();

var y1=(scrollOffset[1]>areaCoords[1])?scrollOffset[1]-areaCoords[1]:1;
var y2=((areaDimensions.height+areaCoords[1])>(dimensions.height+scrollOffset[1]))?dimensions.height-areaCoords[1]:(areaDimensions.height-y1);

var elementDimensions=Element.getDimensions(element);

var posTop=(((y1+y2)-y1)/2)+y1-(elementDimensions.height/2);

element.style.top=posTop>5?posTop+'px':'5px';
element.style.left=Math.floor((Element.getWidth(area)-elementDimensions.width)/2)+'px'}
}

catch(e){
exceptionAlert('Element.centerInViewport() exception.',e)}
},


viewportCenter:function(element){
try{
if(typeof element!="object"){
element=$(element)}

var dimmensions=document.viewport.getDimensions();
var scrollOffset=document.viewport.getScrollOffsets();
var elementDimensions=Element.getDimensions(element);

var posTop=dimmensions.height/2-elementDimensions.height/2+scrollOffset.top;
element.style.top=posTop>5?posTop+'px':'5px';
var posLeft=dimmensions.width/2-elementDimensions.width/2+scrollOffset.left;
element.style.left=posLeft>5?posLeft+'px':'5px';
Element.show(element)}

catch(e){
exceptionAlert('Element.viewportCenter() exception.',e)}
}
});


Object.extend(String.prototype,{

strtr:function(from,to){
if(arguments.length==2){
return this.replace(from,to)};

var str=this;
var i,o=from;

for(i in o){
str=str.strtr(i,o[i])};

return str},


trim:function(){
return this.strip()},


strrev:function(){
return this.split('').reverse().join('')},


ucfirst:function(){
var letters=this.split('');
letters[0]=letters[0].toUpperCase();
return letters.join('')}
});


Object.extend(Form,{

selectUpdate:function(selectObject,selectOptions,setNamesAsValues){
try{
selectObject=$(selectObject);

while(selectObject.options.length){
selectObject.remove(0)}

selectOptions=$H(selectOptions);

selectOptions.each(
function(option){
if(typeof option.value!='string'){
return}

var opt=new Option();
var optionText=document.createTextNode(option.value);
opt.appendChild(optionText);
opt.setAttribute("value",setNamesAsValues?option.value:option.key);
selectObject.appendChild(opt)}
)}

catch(e){
exceptionAlert('Form.selectUpdate() exception.',e)}
}
});


Object.extend(Event,{
_domReady:function(){
if(arguments.callee.done)return;
arguments.callee.done=true;

if(this._timer)clearInterval(this._timer);

this._readyCallbacks.each(function(f){f()});
this._readyCallbacks=null},
onDOMReady:function(f){
if(!this._readyCallbacks){
var domReady=this._domReady.bind(this);

if(document.addEventListener)
document.addEventListener("DOMContentLoaded",domReady,false);




if(/WebKit/i.test(navigator.userAgent)){
this._timer=setInterval(function(){
if(/loaded|complete/.test(document.readyState))domReady()},10)}

Event.observe(window,'load',domReady);
Event._readyCallbacks=[]}
Event._readyCallbacks.push(f)}
});


var Cookie={
data:{},
options:{expires:null,domain:"",path:"",secure:false},

init:function(options,data){
Cookie.options=Object.extend(Cookie.options,options||{});

var payload=Cookie.retrieve();
if(payload){
Cookie.data=payload.evalJSON()}
else{
Cookie.data=data||{}}
Cookie.store()},
getData:function(key){
return Cookie.data[key]},
setData:function(key,value){
Cookie.data[key]=value;
Cookie.store()},
removeData:function(key){
delete Cookie.data[key];
Cookie.store()},
retrieve:function(){
var start=document.cookie.indexOf(Cookie.options.name+"=");

if(start==-1){
return null}
if(Cookie.options.name!=document.cookie.substr(start,Cookie.options.name.length)){
return null}

var len=start+Cookie.options.name.length+1;
var end=document.cookie.indexOf(';',len);

if(end==-1){
end=document.cookie.length}
return unescape(document.cookie.substring(len,end))},
store:function(){
var expires='';

if(Cookie.options.expires){
var today=new Date();
expires=Cookie.options.expires*1000;
expires=';expires='+new Date(today.getTime()+expires)}

document.cookie=Cookie.options.name+'='+escape(Object.toJSON(Cookie.data))+Cookie.getOptions()+expires},
erase:function(){
document.cookie=Cookie.options.name+'='+Cookie.getOptions()+';expires=Thu, 01-Jan-1970 00:00:01 GMT'},
getOptions:function(){
return(Cookie.options.path?';path='+Cookie.options.path:'')+(Cookie.options.domain?';domain='+Cookie.options.domain:'')+(Cookie.options.secure?';secure':'')}
};








var debugMode=true;

exceptionAlert=debugMode?
function(msg,e){
var text=msg;
if(typeof e!='object'){
text+='\r\n'+e}
else{
for(var i in e){
text+='\r\n'+(i+' = '+e[i])}
}

alert(text)}:function(){return};



var jsTools=Class.create();
jsTools.prototype={
initialize:function(){},


amountFormat:function(amount){
var negativeNumber=false;

amount=amount.toFixed(2);

if(amount<0){
negativeNumber=true;
amount=Math.abs(amount)}

amount=amount.toString();

if(amount.length>6){
var parts=amount.split('.');

if(!parts[1]){
parts[1]='00'}

parts[0]=parts[0].strrev();
parts[0]=parts[0].gsub(/\d{3}/,'#{0},');
parts[0]=parts[0].replace(/,$/,'');
parts[0]=parts[0].strrev();
amount=parts.join('.')}

amount='$'+amount;

if(negativeNumber){
amount='-'+amount}

return amount},


dateFormat:function(date){
try{
var parts=date.split('-');
if(parts.length!=3){
throw'Invalid date format. Please use YYYY-MM-DD.'}

date=new Date(Date.UTC(parts[0],parts[1]-1,parts[2]));
dateString=date.toUTCString();
parts=dateString.split(' ');
return parts[2]+' '+parts[1]+', '+parts[3]}

catch(e){
exceptionAlert('Tools.dateFormat() exception.',e)}
},


blockReturnKey:function(e,callback){
try{
var key=e.which||e.keyCode;
if(key==Event.KEY_RETURN){
Event.stop(e);
if(callback){
eval(callback)}
}
}

catch(e){exceptionAlert('Tools.blockReturnKey() exception.',e)}
},


popUp:function(link){
if(typeof(link)!==undefined&&link&&link.getAttribute("href")){
var options={
width:'550',
height:'600',
toolbar:'0',
location:'0',
menubar:'0',
statusbar:'0',
resizable:'1',
scrollbars:'1'
};
var opts=$H(options);

var params=new Array;
var i=0;
opts.each(function(pair){params[i]=pair[0]+'='+pair[1];++i});
params=params.join(', ');
var WindowObjectReference=window.open(link.getAttribute("href"),'windowPopUp',params);
WindowObjectReference.focus()}

return false},


ip2long:function(ip){
try{
var sip=ip.split('.');

if(sip.length>4){
return 0}

var ret=parseFloat(sip[0]*256*256*256)
+parseFloat(sip[1]*256*256)
+parseFloat(sip[2]*256)
+parseFloat(sip[3]);

return ret}

catch(e){
return 0}
},


fnSelect:function(obj){
this.fnDeSelect();
if(document.selection&&document.selection.empty){
var range=document.body.createTextRange();
range.moveToElementText($(obj));
range.select()}

else if(window.getSelection){
var range=document.createRange();
range.selectNodeContents($(obj));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range)}
},


fnDeSelect:function(){
if(document.selection&&document.selection.empty){
document.selection.empty()}

else if(window.getSelection){
window.getSelection().removeAllRanges()}
}

};

var Tools=new jsTools();




var jsCheckbox=Class.create();
jsCheckbox.prototype={
initialize:function(){},


toggleAll:function(checker,formId,chkName){
try{
var inputs=Form.getInputs(formId,'checkbox',chkName);
var i=0;
while(i<inputs.length){
if(inputs[i].disabled==false){
inputs[i].checked=$(checker).checked}
i++}
}

catch(e){
exceptionAlert('Checkbox.toggleAll() exception.',e)}
},


areAllChecked:function(formId,chkName,target){
try{
var inputs=Form.getInputs(formId,'checkbox',chkName);
var cnt=0;
var i=0;

while(i<inputs.length){
if(inputs[i].checked){
cnt++}
i++}
if(target)
$(target).checked=(inputs.length==cnt)?true:false;
return(inputs.length==cnt)?true:false}

catch(e){
exceptionAlert('Checkbox.areAllChecked() exception.',e)}

},


forceOneChecked:function(formId,chkName,checkbox){
try{
var inputs=Form.getInputs(formId,'checkbox',chkName);
var cnt=0;
var i=0;
var lastInput;

while(i<inputs.length){
if(inputs[i].checked){
cnt++;
lastInput=inputs[i]}
i++}

if(cnt==1){
lastInput.checked=true}else if(cnt==0){
if(checkbox){
$(checkbox).checked=true}else{
inputs[0].checked=true}
}
}

catch(e){
exceptionAlert('Checkbox.forceOneChecked() exception.',e)}

},


toggleDisable:function(formId,fieldName,controlField){
try{
var checkbox=$(controlField);
var disabled=checkbox.checked==true?true:false;
var inputs=Form.getInputs(formId,'checkbox',fieldName);
var i=0;

while(i<inputs.length){
if(inputs[i].id!=checkbox.id){
inputs[i].disabled=disabled}

i++}
}

catch(e){
exceptionAlert('Checkbox.toggleDisable() exception.',e)}
},



mark:function(e,rowHandler,cssClass){
try{
var o=Event.element(e);
var checkbox=false;

if(o.type=="checkbox"){
checkbox=o}

else{
var inputs=rowHandler.getElementsByTagName('INPUT');
var i=0;
while(!checkbox&&i<inputs.length){
if(inputs[i].type=="checkbox")
checkbox=inputs[i];
i++}

if(checkbox)
checkbox.checked=checkbox.checked?'':'checked'}

if(checkbox){
var classes=Element.ClassNames(rowHandler);

if(checkbox.checked){
classes.add(cssClass)}else{
classes.remove(cssClass)}
}

}

catch(e){
exceptionAlert('Checkbox.mark() exception.',e)}
}
};

var Checkbox=new jsCheckbox();



var jsInterface=Class.create();
jsInterface.prototype={
initialize:function(){},


vLayer:function(show){
try{
Element.setStyle('vLayer',{width:'800px',height:'600px',top:0,left:0});
$('vLayer').style.display=(show?'block':'none')}

catch(e){
exceptionAlert('Virtual layer error',e)}
},



showWrapper:function(parent,options){
if(!$(parent)){
return false}

this.options=$H({
id:'wrapper',
className:null,
opacity:0.7,
blendColor:'#fff'
}).merge(options||{});

var dim=$(parent).getDimensions();

if($(parent).tagName.toLowerCase()=='body'){
dim=document.viewport.getDimensions()}

var wrapper=document.createElement('div');
var wrapperId=this.options.get('id');

if(this.options.get('className')){
wrapper.className=this.options.get('className')}

wrapper.id=wrapperId;
wrapper.setAttribute('id',wrapperId);
Element.setStyle(wrapper,{
backgroundColor:this.options.get('blendColor'),
display:'none',
position:'absolute',
zIndex:9998,
filter:'alpha(opacity='+(this.options.get('opacity')*100)+')',
MozOpacity:this.options.get('opacity'),
opacity:this.options.get('opacity'),
border:0,
width:dim.width+'px',
height:dim.height+'px'
});

$(parent).appendChild(wrapper);
Element.clonePosition(wrapper,$(parent),{setWidth:false,setHeight:false});
Element.show(wrapper);

if(Prototype.Browser.IE){
var iframeId=this.options.get('id')+'_iframe';
var underlay=document.createElement('iframe');

underlay.id=iframeId;
underlay.setAttribute('id',iframeId);
underlay.setAttribute('src','javascript:null;');
Element.setStyle(underlay,{
position:'absolute',
display:'none',
border:0,
margin:0,
opacity:0.01,
padding:0,
background:'none',
zIndex:9997,
width:dim.width+'px',
height:dim.height+'px'
});

underlay.frameBorder=0;

$(parent).appendChild(underlay);
Element.clonePosition(underlay,$(parent));
Element.show(underlay)}

return true},


hideWrapper:function(wrapperId){
wrapperId=wrapperId||'wrapper';

if($(wrapperId)){
Element.remove(wrapperId)}

var iframeId=wrapperId+'_iframe';
if($(iframeId)){
Element.remove(iframeId)}
},



tooltip:function(parent,element){
try{
var pos=Element.viewportOffset(parent);

var scroll=Element.cumulativeScrollOffset(document.body);
pos[0]+=scroll[0];
pos[1]+=scroll[1];

this.element=$(element);
var dimensions=Element.getDimensions(this.element);

Element.setStyle('vLayer',{
'top':pos[1]-20+'px',
'left':pos[0]-125+'px',
'width':dimensions.width+4+'px','height':dimensions.height+4+'px',
'display':'block'
});

Element.setStyle(this.element,{'top':pos[1]-20+'px','left':pos[0]-125+'px'});
Element.show(this.element);

Element.observe(this.element,'mouseout',function(){Element.hide(this.element);Element.hide('vLayer')}.bind(this))}

catch(e){
exceptionAlert('Interface.tooltip() exception.',e)}
},


waitShow:function(){
this.delay=250;this.duration=800;
var date=new Date();
this.start=date.getTime();
this.timer=setTimeout(
function(){
vLayer(true);
Element.center('waitDiv',document.body);
Element.show('waitDiv')},this.delay
);

setTimeout(
function(){
vLayer(false);
Element.hide('waitDiv')},10000
)},


waitHide:function(){
clearTimeout(this.timer);
delete this.timer;

var date=new Date();
var time=date.getTime()-this.start;
var duration=time<this.duration?this.duration-time:1;
setTimeout(
function(){
vLayer(false);
Element.hide('waitDiv')},duration
)},


markErrorFields:function(form,errorFields){
try{
if(errorFields.length>0){
errorFields=$A(errorFields)}

if(!$(errorFields[0])){
throw'Can\'t find field with id: "'+errorFields[0]+'"'}

$(errorFields[0]).focus();

$(form).getElements().each(function(field){field.removeClassName('formError')});

errorFields.each(function(field){
if($(field)){
$(field).addClassName('formError')}
});

$(form).select('label').each(function(label){
var labelFor=label.getAttribute('htmlFor')||label.getAttribute('for');

if(errorFields.indexOf(labelFor)>=0){
label.addClassName('formError')}

else{
label.removeClassName('formError')}
})}

catch(e){
exceptionAlert('Interface.markErrorFields() exception.',e)}
},


getPageSizeWithScroll:function(){
var yWithScroll;
var xWithScroll;

if(window.innerHeight&&window.scrollMaxY){
yWithScroll=window.innerHeight+window.scrollMaxY;
xWithScroll=window.innerWidth+window.scrollMaxX}
else if(document.body.scrollHeight>document.body.offsetHeight){
yWithScroll=document.body.scrollHeight;
xWithScroll=document.body.scrollWidth}
else{yWithScroll=document.body.offsetHeight;
xWithScroll=document.body.offsetWidth}

return[xWithScroll,yWithScroll]},



displayErrors:function(errorMessages){
try{
errorMessages=errorMessages.inject('',function(acc,n){return acc+'<li>'+n+'</li>'});
errorMessages='<div class="errors_header"><!-- --></div><div class="errors_content"><ul>'+errorMessages+'</ul></div><div class="errors_footer"><!-- --></div>';

var messagesBox=$('messages').down('div.errors');

var infoMessagesBox=$('messages').down('div.infos');
if(infoMessagesBox){
infoMessagesBox.remove()}

var noticeMessagesBox=$('messages').down('div.notice');
if(noticeMessagesBox){
noticeMessagesBox.remove()}

if(messagesBox){
messagesBox.replace('<div class="msgs errors">'+errorMessages+'</div>')}

else{
$('messages').insert('<div class="msgs errors">'+errorMessages+'</div>')}

$('messages').scrollTo()}

catch(e){
exceptionAlert('Interface.displayErrors() exception.',e)}
},



displayInfos:function(infoMessages){
try{
infoMessages=infoMessages.inject('',function(acc,n){return acc+'<li>'+n+'</li>'});
infoMessages='<div class="infos_header"><!-- --></div><div class="infos_content"><ul>'+infoMessages+'</ul></div><div class="infos_footer"><!-- --></div>';

var messagesBox=$('messages').down('div.infos');

var errorMessagesBox=$('messages').down('div.errors');
if(errorMessagesBox){
errorMessagesBox.remove()}

var noticeMessagesBox=$('messages').down('div.notice');
if(noticeMessagesBox){
noticeMessagesBox.remove()}

if(messagesBox){
messagesBox.replace('<div class="msgs infos">'+infoMessages+'</div>')}

else{
$('messages').insert('<div class="msgs infos">'+infoMessages+'</div>')}

$('messages').scrollTo()}

catch(e){
exceptionAlert('Interface.displayInfos() exception.',e)}
},



clearErrors:function(){
try{
var messagesBox=$('messages').down('div.errors');
if(messagesBox){
messagesBox.remove()}
}

catch(e){
exceptionAlert('Interface.clearErrors() exception.',e)}
}
};

var Interface=new jsInterface();




var Wait=Class.create();
Wait.prototype={};

Wait.show=function(waitDiv,options){

this.options=$H({
delay:0,
duration:800,
opacity:0.7,
blendColor:'#fff',
msg:"Please wait...",
msgColor:'#000',
spinnerImg:$('ajaxSpinner')?$('ajaxSpinner').src:'/gfx/spinner.gif',
spinnerClass:'spinner',
blend:true
}).merge(options||{});

var date=new Date();
this.start=this.namespace=date.getTime();
var namespace=this.namespace;

this.timer=setTimeout(
function(){
var spanId=$(waitDiv).id+'ajaxWait'+namespace;

var span=document.createElement('div');

if(this.options.get('msg')){
var msg=document.createTextNode(this.options.get('msg'));
span.style.color=this.options.get('msgColor');
span.appendChild(msg)}

if(this.options.get('spinnerImg')!=false){
var img=document.createElement('img');
img.src=this.options.get('spinnerImg');
img.style.position='relative';
img.style.top='5px';
img.style.marginRight='5px';
img.style.display='block';
img.className=this.options.get('spinnerClass');
span.appendChild(img)}

span.id=spanId;
span.style.zIndex=9999;
span.style.display='none';
span.style.position='absolute';
span.setAttribute("id",spanId);



$(waitDiv).appendChild(span);
Element.centerViaAreaInViewport(span,$(waitDiv));
Element.absolutize(spanId);
Element.show(spanId);

if(this.options.get('blend')){
Interface.showWrapper($(waitDiv),{
id:$(waitDiv).id+'iframe'+namespace,
className:'ajaxBlendFrame',
blendColor:this.options.get('blendColor'),
opacity:this.options.get('opacity')
})}
}.bind(this),this.options.get('delay')
);

setTimeout(
function(){
Interface.hideWrapper($(waitDiv).id+'iframe'+namespace);

var spanId=$(waitDiv).id+'ajaxWait'+namespace;
if($(spanId)!=null){
Element.remove(spanId)}
},10000
)};

Wait.hide=function(waitDiv,secondDiv){
clearTimeout(this.timer);
delete this.timer;

var date=new Date();
var time=date.getTime()-this.start;
var duration=this.options&&time<this.options.get('duration')?this.options.get('duration')-time:1;
var namespace=this.namespace;

setTimeout(
function(){
var spanId=$(waitDiv).id+'ajaxWait'+namespace;

if($(spanId)!=null){
Element.remove(spanId)}

Interface.hideWrapper($(waitDiv).id+'iframe'+namespace);

if(secondDiv&&$(secondDiv)!=null){
Element.hide(secondDiv)}
},duration
)};



var jsLister=Class.create();
jsLister.prototype={
initialize:function(){
this.activeSearchInterval=0;
this.refreshCounter=0;
this.refreshInterval=0},



toggleSearch:function(boxId,show,iconId){
try{
var plusClass='searchFormHidden';
var minusClass='searchFormVisible';
var params={duration:0.5};
if(show==null){
$disp=$(boxId).style.display=='block'||!$(boxId).style.display;
if(typeof(Effect)!='undefined'&&Effect){
$disp?Effect.BlindUp(boxId,params):Effect.BlindDown(boxId,params)}
else{
$disp?$(boxId).style.display='none':$(boxId).style.display='block'}
if($(iconId)&&!($(iconId).hasClassName($disp?plusClass:minusClass)))
$(iconId).className=$disp?plusClass:minusClass}

else{
if(typeof(Effect)!='undefined'&&Effect){
show?Effect.BlindDown(boxId,params):Effect.BlindUp(boxId,params)}
else{
show?$(boxId).style.display='block':$(boxId).style.display='none'}
if($(iconId)&&!($(iconId).hasClassName(show?minusClass:plusClass)))
$(iconId).className=show?minusClass:plusClass}
}

catch(e){
exceptionAlert('Lister.toggleSearch() exception.',e)}
},


repeatSearchStart:function(seconds,counter){
if(currentSearch&&this.activeSearchInterval==0&&ajaxHistory){
var that=this;
var fire=function(){that.refreshCountDown(counter)};
$(counter).innerHTML=this.refreshInterval=seconds;
this.refreshCounter=(seconds-1);
this.activeSearchInterval=setInterval(fire,1000)}
},


repeatSearchStop:function(){
if(this.activeSearchInterval>0){
clearInterval(this.activeSearchInterval);
this.activeSearchInterval=0}
},

refreshCountDown:function(counter){
if(this.refreshCounter==0){
ajaxHistory.fireHistoryEvent(currentSearch);
this.refreshCounter=this.refreshInterval}
$(counter).innerHTML=this.refreshCounter;
if(ajaxHistory){
if(!ajaxHistory.getAjaxInProgress())
this.refreshCounter--}else{
this.refreshCounter--}
},


enableEnterKeySubmit:function(container,formId){
setTimeout(function(){
$$(container+' input[type=text]').each(function(i){
i.onkeypress=function(e){
if(!e)var e=window.event;
if(((e.keyCode)?e.keyCode:e.which)==Event.KEY_RETURN)
return Lister.formSubmit('search',formId);
else
return true}})},250)},


formSubmit:function(){},


showColumsList:function(element){
Element.viewportCenter(element);
Element.show(element)}
};

var Lister=new jsLister();





var Validator=Class.create();
Validator.prototype={


initialize:function(checks,fieldsDescr,fieldsMap){
try{
if(arguments.length<2){
throw('Constructor needs two parameters.')}

this.fieldsDescr=$H(fieldsDescr);
this.fieldsMap=$H(fieldsMap);
this.checks=$H(checks);
this.errorFields=[];
this.errorMessages=[];
this.form=null}

catch(e){
exceptionAlert('Validator.initialize() exception.',e)}
},


setInput:function(form){
try{
this.form=$(form);

if(form.tagName.toLowerCase()!='form'){
throw('Invalid form handler or form id.')}

this.input=new Hash();
var formElements=Form.getElements(form);

formElements.each(function(element){
if(/\[\]$/.test(element.name)){
var fieldName=element.name.replace(/\[\]$/,'');
var oldValue=this.input.get(fieldName);
var newValue=oldValue?[oldValue,element.value]:[element.value];
this.input.set(fieldName,newValue.flatten())}

else{
this.input.set(element.name,element.value)}
}.bind(this))}

catch(e){
exceptionAlert('Validator.setInput() exception.',e)}
},


check:function(){
this.fieldNames=$A(arguments);

this.fieldNames.each(function(fieldName){
var args;
var check=this.checks.get(fieldName);

if(check){
if(typeof check[0]=='string'){
this.makeTest(fieldName,check)}

else if(typeof check[0]=='object'){
check.each(function(item){
var result=this.makeTest(fieldName,item);

if(!result){
throw $break}
}.bind(this))}
}
}.bind(this))},


makeTest:function(fieldName,testDefinition){
try{
if(testDefinition){
var testName=testDefinition[0];
var args=testDefinition.slice(1);
args.unshift(fieldName);
args=args.toJSON();
args=args.substring(1,args.length-1);
return eval('this.test'+testName.ucfirst()+'('+args+')')}
}

catch(e){
exceptionAlert('Validator.makeTest() exception.',e)}
},


setError:function(fieldName,errorMsg,isOwnMsg){
try{
var map=this.fieldsMap.get(fieldName);

if(map&&typeof map=='string'&&this.errorFields.indexOf(map)<0){
this.errorFields.push(map)}

else if(map&&typeof map=='object'){
this.errorFields.push(map);
this.errorFields=this.errorFields.flatten();
this.errorFields=this.errorFields.uniq()}

else if(this.errorFields.indexOf(fieldName)<0){
this.errorFields.push(fieldName)}

var msg=errorMsg.interpolate({fieldName:'<b>'+this.fieldsDescr.get(fieldName)+'</b>'});
if(!isOwnMsg&&msg==errorMsg){
msg=this._translate("Error in '<b>#{fieldName}</b>'.").interpolate({fieldName:this.fieldsDescr.get(fieldName)})+' '+msg}

this.errorMessages.push(msg)}

catch(e){
exceptionAlert('Validator.setError() exception.',e)}
},


getErrors:function(){
return[this.errorFields,this.errorMessages]},


testAlnum:function(fieldName,errorMsg){
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var regex=/^[0-9a-z]*$/i;
var result=regex.test(this.input.get(fieldName));

if(!result){
this.setError(fieldName,!errorMsg?this._translate('Value should have only alphabetic and digit characters.'):errorMsg,isOwnMsg)}

return result},


testAlpha:function(fieldName,errorMsg){
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var regex=/^[a-z]*$/i;
var result=regex.test(this.input.get(fieldName));

if(!result){
this.setError(fieldName,!errorMsg?this._translate('Value should have only alphabetic characters.'):errorMsg,isOwnMsg)}

return result},


testAmount:function(fieldName,errorMsg){
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var result=!isNaN(this.input.get(fieldName));

if(!result){
this.setError(fieldName,!errorMsg?this._translate('#{fieldName} should be a number with or without decimal places, e.g. 150 or 35.25'):errorMsg,isOwnMsg)}

return result},


testBetween:function(fieldName,values,errorMsg){
if(typeof values!='object'||values.length<2){
throw('Valiator.testBetween() needs at least two parameters - minimum and maximum value.')}

var min=values[0];
var max=values[1];
var incl=values[2];
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var result=false;

if(incl){
result=this.input.get(fieldName)>=min&&this.input.get(fieldName)<=max}

else{
result=this.input.get(fieldName)>min&&this.input.get(fieldName)<max}

if(!result){
if(!errorMsg&&incl){
errorMsg=this._translate("Value should be between '#{minValue}' and '#{maxValue}', inclusively")}

else if(!errorMsg){
errorMsg=this._translate("Value should be strictly between '#{minValue}' and '#{maxValue}'")}

this.setError(fieldName,errorMsg.interpolate({fieldName:'<b>'+this.fieldsDescr.get(fieldName)+'</b>',minValue:min,maxValue:max}),isOwnMsg)}

return result},


testCallback:function(fieldName,callback,args,errorMsg){
try{
args=[fieldName,this.input,args,errorMsg];
args=args.toJSON();
args=args.substring(1,args.length-1);
var ret=eval(callback+'('+args+')');

if(!ret[0]){
this.setError(fieldName,ret[1],ret[2])}

return ret[0]}

catch(e){
exceptionAlert('Validator.testCallback() exception.',e)}
},


testCcnum:function(fieldName,errorMsg){
var isOwnMsg=!(!errorMsg||errorMsg.empty());

var valueFiltered=this.input.get(fieldName).replace(/\s+/g,'');
var length=valueFiltered.toString().length;

if(length<13||length>19){
if(!isOwnMsg){
errorMsg=this._translate('Invalid credit card number length. Should have from 13 to 19 digits.')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

var sum=0;
var weight=2;

for(var i=length-2;i>=0;i--){
var digit=weight*valueFiltered[i];
sum+=Math.floor(digit/10)+digit%10;
weight=weight%2+1}

if((10-sum%10)%10!=valueFiltered[length-1]){
if(!isOwnMsg){
errorMsg=this._translate('Invalid credit card number.')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

return true},


testDate:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());

if(!/^\d{4}-\d{2}-\d{2}$/.test(this.input.get(fieldName))){
if(!isOwnMsg){
errorMsg=this._translate('Date is not of the format YYYY-MM-DD')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

var parts=this.input.get(fieldName).split('-');
var year=parseInt(parts[0]);
var month=parseInt(parts[1]-1);var day=parseInt(parts[2]);

var months30=[3,5,8,10];

var myDate=new Date(year,month,day);
if(month<0||myDate.getFullYear()!=year||myDate.getMonth()!=month
||myDate.getDate()!=day
||month==2&&(day>29&&!(year%4)||day>28&&year%4)
||months30.indexOf(month)>=0&&day>30
){
if(!isOwnMsg){
errorMsg=this._translate('Invalid date. Please check if selected day is correct for chosen month.')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testDate() exception.',e)}
},


testDigits:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var value=this.input.get(fieldName);

if(value!=value.replace(/[^0-9]/,'')){
if(!isOwnMsg){
errorMsg=this._translate('Value should contain only digit characters')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testDigits() exception.',e)}
},


testEmailAddress:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var regex=/^[^\@]+\@[^\@]+\.[a-z0-9]{2,4}$/i;

var input=this.input.get(fieldName);
input=input.strip();

var result=regex.test(input);

if(!result){
if(!isOwnMsg){
errorMsg=this._translate('Value is not a valid email address in the basic format local-part@hostname')}

this.setError(fieldName,errorMsg,isOwnMsg)}

return result}

catch(e){
exceptionAlert('Validator.testEmailAddress() exception.',e)}
},


testFloat:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var value=this.input.get(fieldName);
if(parseFloat(value)!=value){
if(!isOwnMsg){
errorMsg=this._translate('Value does not appear to be a float')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testFloat() exception.',e)}
},


testGreaterThan:function(fieldName,args,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var min=parseFloat(typeof args=='object'?args[0]:args);
var inclusive=(typeof args=='object'?args[1]:false);
var value=this.input.get(fieldName);

if(inclusive&&value<min||!inclusive&&value<=min){
if(!isOwnMsg&&inclusive){
errorMsg=this._translate("#{fieldName} must be greater than or equal '#{minValue}'.")}

else if(!errorMsg){
errorMsg=this._translate("#{fieldName} must be greater than '#{minValue}'.")}

this.setError(fieldName,errorMsg.interpolate({fieldName:'<b>'+this.fieldsDescr.get(fieldName)+'</b>',minValue:min}),isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testGreaterThan() exception.',e)}
},


testHex:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var value=this.input.get(fieldName);
var regex=/^(0x)?[0-9a-f]+$/i;

if(!regex.test(value)){
if(!isOwnMsg){
errorMsg=this._translate('Value should have only hexadecimal digit characters')}

this.setError(fieldName,errorMsg,isOwnMsg);
return true}

return false}

catch(e){
exceptionAlert('Validator.testHex() exception.',e)}
},


testHostname:function(fieldName,errorMsg){
try{
var result=true;
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var validTlds=[
'ac','ad','ae','aero','af','ag','ai','al','am','an','ao',
'aq','ar','arpa','as','asia','at','au','aw','ax','az','ba','bb',
'bd','be','bf','bg','bh','bi','biz','bj','bm','bn','bo',
'br','bs','bt','bv','bw','by','bz','ca','cat','cc','cd',
'cf','cg','ch','ci','ck','cl','cm','cn','co','com','coop',
'cr','cu','cv','cx','cy','cz','de','dj','dk','dm','do',
'dz','ec','edu','ee','eg','er','es','et','eu','fi','fj',
'fk','fm','fo','fr','ga','gb','gd','ge','gf','gg','gh',
'gi','gl','gm','gn','gov','gp','gq','gr','gs','gt','gu',
'gw','gy','hk','hm','hn','hr','ht','hu','id','ie','il',
'im','in','info','int','io','iq','ir','is','it','je','jm',
'jo','jobs','jp','ke','kg','kh','ki','km','kn','kr','kw',
'ky','kz','la','lb','lc','li','lk','lr','ls','lt','lu',
'lv','ly','ma','mc','md','mg','mh','mil','mk','ml','mm',
'mn','mo','mobi','mp','mq','mr','ms','mt','mu','museum','mv',
'mw','mx','my','mz','na','name','nc','ne','net','nf','ng',
'ni','nl','no','np','nr','nu','nz','om','org','pa','pe',
'pf','pg','ph','pk','pl','pm','pn','pr','pro','ps','pt',
'pw','py','qa','re','ro','ru','rw','sa','sb','sc','sd',
'se','sg','sh','si','sj','sk','sl','sm','sn','so','sr',
'st','su','sv','sy','sz','tc','td','tf','tg','th','tj',
'tk','tl','tm','tn','to','tp','tr','travel','tt','tv','tw',
'tz','ua','ug','uk','um','us','uy','uz','va','vc','ve',
'vg','vi','vn','vu','wf','ws','ye','yt','yu','za','zm','zw'
];

var domain=this.input.get(fieldName);
var domainParts=domain.split('.');

if(/^http|\/|\:|\?/i.test(domain)){
if(!isOwnMsg){
errorMsg=this._translate('Hostname should be a domain name without "http://" part and without query string.')}

result=false}

else if(domain.length<4||domain.length>254){
if(!isOwnMsg){
errorMsg=this._translate('Invalid hostname string length. It should be between 4 and 254 characters.')}

result=false}

else if(validTlds.indexOf(domainParts.last())==-1){
if(!isOwnMsg){
errorMsg=this._translate('Invalid top level domain.')}

result=false}

if(!result){
this.setError(fieldName,errorMsg,isOwnMsg)}

return result}

catch(e){
exceptionAlert('Validator.testHostname() exception.',e)}
},


testInArray:function(fieldName,arr,errorMsg){
try{
if(typeof arr!='object'||!arr.length){
throw('Second parameter must be an array.')}

arr=$A(arr).flatten();

arr=arr.collect(function(item){return item.toString()});

var isOwnMsg=!(!errorMsg||errorMsg.empty());
if(arr.indexOf(this.input.get(fieldName))==-1){
if(!isOwnMsg){
errorMsg=this._translate('Value not found in array: #{array}')}

this.setError(fieldName,errorMsg.interpolate({fieldName:'<b>'+this.fieldsDescr.get(fieldName)+'</b>',array:arr.join(', ')}),isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testInArray() exception.',e)}
},


testInt:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var value=this.input.get(fieldName);

if(value!=parseInt(value).toString()){
if(!isOwnMsg){
errorMsg=this._translate('Please enter a whole number, without decimal places.')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}
}

catch(e){
exceptionAlert('Validator.testInt() exception.',e)}
},


testIp:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
if(!Tools.ip2long(this.input.get(fieldName))){
if(!isOwnMsg){
errorMsg=this._translate('Value does not appear to be a valid IP address.')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testIp() exception.',e)}
},


testIsChecked:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var result=true;

var checkbox=this.form.getInputs('checkbox',fieldName);
if(checkbox&&checkbox.first()){
if(!checkbox.first().checked){
this.setError(fieldName,!errorMsg?this._translate('Required option not checked.'):errorMsg,isOwnMsg)}
}

else{
var radios=this.form.getInputs('radio',fieldName);
this.isChecked=false;
radios.each(function(radio){
this.isChecked|=radio.checked}.bind(this));

if(!this.isChecked){
this.setError(fieldName,!errorMsg?this._translate('Required option not checked.'):errorMsg,isOwnMsg)}
}

return result}

catch(e){
exceptionAlert('Validator.testIsChecked() exception.',e)}
},


testLessThan:function(fieldName,args,errorMsg){
try{
if(!args){
throw('Second parameter should be non-empty')}

var isOwnMsg=!(!errorMsg||errorMsg.empty());
var max=parseFloat(typeof args=='object'?args[0]:args);
var inclusive=(typeof args=='object'?args[1]:false);
var value=this.input.get(fieldName);

if(inclusive&&value>max||!inclusive&&value>=max){
if(!isOwnMsg&&inclusive){
errorMsg=this._translate("#{fieldName} must be less than or equal '#{maxValue}'.")}

else if(!errorMsg){
errorMsg=this._translate("#{fieldName} must be less than '#{maxValue}'.")}

this.setError(fieldName,errorMsg.interpolate({fieldName:'<b>'+this.fieldsDescr.get(fieldName)+'</b>',maxValue:max}),isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testLessThan() exception.',e)}
},


testMultiple:function(fieldName,testName,args,errorMsg){
try{
var globalRet=true;

if(args&&typeof args=='object'){
args=args.toJSON();
args=args.substring(1,args.length-1)}

var i=0;
this.input.get(fieldName).each(function(value){
var tmpFieldName=fieldName+'_'+i;
this.input.set(tmpFieldName,value);
this.fieldsDescr.set(tmpFieldName,this.fieldsDescr.get(fieldName));
this.fieldsMap.set(tmpFieldName,this.fieldsDescr.get(fieldName));

globalRet=globalRet&eval('this.test'+testName.ucfirst()+'("'+tmpFieldName+'", '+args+')');

this.input.unset(tmpFieldName,value);
this.fieldsDescr.unset(tmpFieldName,this.fieldsDescr.get(fieldName));
this.fieldsMap.unset(tmpFieldName,this.fieldsDescr.get(fieldName));

i++}.bind(this));

return globalRet}

catch(e){
exceptionAlert('Validator.testMultiple() exception.',e)}
},


testNotEmpty:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());

if(this.input.get(fieldName).empty()){
this.setError(fieldName,!errorMsg?this._translate('Value is empty, but a non-empty value is required.'):errorMsg,isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testNotEmpty() exception.',e)}
},


testPasswordMatch:function(fieldName,field2Name,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
if(this.input.get(fieldName)!=this.input.get(field2Name)){
if(!isOwnMsg){
errorMsg=this._translate('Password doesn\'t match its confirmation.')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testPasswordMatch() exception.',e)}
},


testPasswordStrength:function(fieldName,errorMsg){
try{
throw('Not implemented')}

catch(e){
exceptionAlert('Validator.testPasswordStrength() exception.',e)}
},


testPhoneNumber:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
if(!/^\+[0-9 -]{8,20}$/.test(this.input.get(fieldName))){
if(!isOwnMsg){
errorMsg=this._translate('Phone number has to be in valid international format, i.e. +1-222-333-4444.')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testPhoneNumber() exception.',e)}
},


testPostalCode:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
if(!/^[0-9a-zA-Z \-_#(),\.]+$/.test(this.input.get(fieldName))){
if(!isOwnMsg){
errorMsg=this._translate('Postal code is not valid.')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testPostalCode() exception.',e)}
},


testRegex:function(fieldName,regex,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
regex=eval(regex);
if(!regex.test(this.input.get(fieldName))){
if(!isOwnMsg){
errorMsg=this._translate('Value does not match against pattern "#{regex}"')}

this.setError(fieldName,errorMsg.interpolate({fieldName:'<b>'+this.fieldsDescr.get(fieldName)+'</b>',regex:regex}),isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testRegex() exception.',e)}
},


testStringLength:function(fieldName,args,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var string=this.input.get(fieldName);
if(string.length<args[0]||string.length>args[1]){
if(!isOwnMsg){
errorMsg=this._translate('Value length should be between #{minLength} and #{maxLength} characters')}

this.setError(fieldName,errorMsg.interpolate({fieldName:'<b>'+this.fieldsDescr.get(fieldName)+'</b>',minLength:args[0],maxLength:args[1]}),isOwnMsg);
return false}

return true}

catch(e){
exceptionAlert('Validator.testStringLength() exception.',e)}
},


testUri:function(fieldName,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());
var uri=this.input.get(fieldName);
var regex=/^http(s)?\:\/\/[^\.]+?\.[a-z]{2,4}(\/|$)/i;

if(!regex.test(uri)){
if(!isOwnMsg){
errorMsg=this._translate('Uri has to be in proper format, i.e. http://mydomain.com')}

this.setError(fieldName,errorMsg,isOwnMsg);
return false}


return true}

catch(e){
exceptionAlert('Validator.testUri() exception.',e)}
},


testUsernameAvailability:function(fieldName,uri,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());

if(!isOwnMsg){
errorMsg=this._translate('Entered #{fieldName} is not available. Please enter alternate #{fieldName}.')}

uri=uri.replace(/\/$/,'')+'/username/';

this._testAvailability(fieldName,uri,errorMsg,isOwnMsg)}

catch(e){
exceptionAlert('Validator.testUsernameAvailibility() exception.',e)}
},


testEmailAvailability:function(fieldName,uri,errorMsg){
try{
var isOwnMsg=!(!errorMsg||errorMsg.empty());

if(!isOwnMsg){
errorMsg=this._translate('Entered #{fieldName} is already registered in our database.')}

uri=uri.replace(/\/$/,'')+'/email/';

this._testAvailability(fieldName,uri,errorMsg,isOwnMsg)}

catch(e){
exceptionAlert('Validator.testEmailAvailibility() exception.',e)}
},


_testAvailability:function(fieldName,uri,errorMsg,isOwnMsg){
try{
this.fieldName=fieldName;
this.errorMsg=errorMsg;
this.isOwnMsg=isOwnMsg;
var item=this.input.get(this.fieldName);

if(!Object.isHash(this.lastAvailabilityCheckResult)){
this.lastAvailabilityCheckResult=new Hash()}

if(!Object.isHash(this.lastCheckedItem)){
this.lastCheckedItem=new Hash()}

if(item==this.lastCheckedItem[fieldName]){
if(this.lastAvailabilityCheckResult[fieldName]===false){
this.setError(this.fieldName,this.errorMsg,this.isOwnMsg);
return false}

return true}

else{
this.lastCheckedItem[fieldName]=item}

var requestUrl=uri+item;

new Ajax.Request(requestUrl,{
method:'get',

asynchronous:false,

onSuccess:function(transport){
if(transport.responseText){
var response=eval('('+transport.responseText+')');
if(response["isAvailabile"]==0){
this.setError(this.fieldName,this.errorMsg,this.isOwnMsg);
this.lastAvailabilityCheckResult[fieldName]=false;return false}

else{
this.lastAvailabilityCheckResult[fieldName]=true;return true}
}
}.bind(this),
onException:exceptionAlert,
onFailure:exceptionAlert
});

return this.lastAvailabilityCheckResult[fieldName]}

catch(e){
exceptionAlert('Validator._testAvailibility() exception.',e)}
},


simpleValidate:function(form){
try{
this.errorFields=[];
this.errorMessages=[];

this.setInput(form);
this.input.keys().each(this.check.bind(this));
var errors=this.getErrors();

if(errors[0].length>0){
Interface.markErrorFields(form,this.getErrors()[0]);
Interface.displayErrors(this.getErrors()[1]);
return false}

else{
return true}
}

catch(e){
exceptionAlert('Validator.simpleValidate() exception.',e)}
},


_translate:function(txt){
try{
return _(txt)}

catch(e){
return txt}
}

};





var PasswordStrengthMeter=Class.create();
PasswordStrengthMeter.prototype={


initialize:function(passFieldId,stringsToAvoid,infoBarObjectId,infoMessageObjectId,caseSensitive,minimalLength){
this.passFieldId=passFieldId;
this.stringsToAvoid=stringsToAvoid;

this.lastMarkCellClassName=null;
this.lastMarkCell=null;
this.lastCheckedPassword=null;
this.markBoxClassName=null;

this.minimalLength=6;
if(!isNaN(minimalLength)){
this.minimalLength=minimalLength}

this.infoBarObjectId=infoBarObjectId;
this.infoMessageObjectId=infoMessageObjectId;
this.caseSensitive=caseSensitive},


ckeckPasswordStrength:function(){
this.pass=$(this.passFieldId).value;

if(!this._stringsToAvoid&&Object.isArray(this.stringsToAvoid)){
this._stringsToAvoid=this.stringsToAvoid}

else if(!this._stringsToAvoid){
this._stringsToAvoid=$(this.stringsToAvoid)?$(this.stringsToAvoid).value:this.stringsToAvoid}

var infoMessage;

if(this.pass==this.lastCheckedPassword){
return}

var passLength=this.pass.length;
var passLowerCase=this.pass.toLowerCase();
var translator;
this.infoMessage='';

if(passLength<this.minimalLength){
this.infoMessage=this.translate('Password should have at least #{length} characters').interpolate({length:this.minimalLength});
this.updatePasswordStrengthMark(0);
this.updateInfoMessageBox();
return}

var denumeratedPass=passLowerCase.strtr('5301!1','seolli');

if(this._stringsToAvoid){
if(!Object.isArray(this._stringsToAvoid)){
this._stringsToAvoid=[this._stringsToAvoid]}

var stringsToAvoidLength=this._stringsToAvoid.length;

for(i=0;i<stringsToAvoidLength;i++){
stringToAvoid=this._stringsToAvoid[i];
var stringToAvoidLowerCase=stringToAvoid;

var msg=this.translate('Password must be different than "#{pass}"');
var mark;
if(this.caseSensitive){
if(this.pass==stringToAvoid){
this.infoMessage=msg.interpolate({pass:this.pass});
mark=0}
else if(this.pass==stringToAvoid.strrev()){
this.infoMessage=msg.interpolate({pass:this.pass});
mark=1}
else if(denumeratedPass==stringToAvoid){
this.infoMessage=msg.interpolate({pass:this.pass});
mark=1}
else if(denumeratedPass==stringToAvoid.strrev()){
this.infoMessage=msg.interpolate({pass:this.pass});
mark=2}
}
else{
if(passLowerCase==stringToAvoidLowerCase){
this.infoMessage=msg.interpolate({pass:this.pass});
mark=0}
else if(passLowerCase==stringToAvoidLowerCase.strrev()){
this.infoMessage=msg.interpolate({pass:this.pass});
mark=1}
else if(denumeratedPass==stringToAvoidLowerCase){
this.infoMessage=msg.interpolate({pass:this.pass});
mark=1}
else if(denumeratedPass==stringToAvoidLowerCase.strrev()){
infoMessage=msg.interpolate({pass:this.pass});
mark=2}
}

if(!isNaN(mark)){
this.updatePasswordStrengthMark(mark);
this.updateInfoMessageBox();
return}
}
}

var mark=1;

if(passLength>=8&&passLength<12){
this.infoMessage=this.translate('The password length should be greater');
++mark}
else if(passLength>=12&&passLength<16){
mark=mark+2}
else if(passLength>=16&&passLength<24){
mark=mark+3}
else if(passLength>=24){
mark=mark+4}

var upperCaseCharacters=0;var lowerCaseCharacters=0;
var alphaCharacters=0;var digitCharacters=0;var otherCharacters=0;

for(i=0,j=passLength;i<j;i++){
character=this.pass.substr(i,1);

if(this.caseSensitive&&character.match('[A-Z]')){
++upperCaseCharacters}
else if(this.caseSensitive&&character.match('[a-z]')){
++lowerCaseCharacters}
else if(!this.caseSensitive&&character.match('[a-zA-Z_-]')){
++alphaCharacters}
else if(character.match('[0-9]')){
++digitCharacters}
else{
++otherCharacters}
}

var charactersGroups=0;

if(this.caseSensitive){
if(upperCaseCharacters>0){
++charactersGroups}

if(lowerCaseCharacters>0){
++charactersGroups}
}
else if(alphaCharacters>0){
++charactersGroups}

if(digitCharacters>0){
++charactersGroups}

if(otherCharacters>0){
++charactersGroups;
++mark}

if(charactersGroups==1){
this.infoMessage=this.translate('Use more than one characters groups (letters, digits and special chars)')}
else if(charactersGroups==2){
++mark}
else if(charactersGroups>2){
mark=mark+2}

if(mark>5){
mark=5}

if(mark==5){
this.infoMessage=this.translate('We hope you can remember this')}

this.updatePasswordStrengthMark(mark);
this.updateInfoMessageBox()},



updatePasswordStrengthMark:function(passwordMark){
var boxToUpdate=$(this.infoBarObjectId);
var object;

if(this.markBoxClassName){
if(this.lastMark){
var lastCell=this.lastMark}
else{
var lastCell=passwordMark}

for(i=0;i<=lastCell;i++){
object=$('passwordMark'+i);
object.removeClassName(this.markBoxClassName)}
}
this.lastMark=passwordMark;
var textMark;

if(passwordMark==0){
this.markBoxClassName='unacceptable';
textMark=this.translate('Unacceptable')}
else if(passwordMark==1){
this.markBoxClassName='veryWeak';
textMark=this.translate('Very weak')}
else if(passwordMark==2){
this.markBoxClassName='weak';
textMark=this.translate('Weak')}
else if(passwordMark==3){
this.markBoxClassName='medium';
textMark=this.translate('Medium')}
else if(passwordMark==4){
this.markBoxClassName='good';
textMark=this.translate('Good')}
else if(passwordMark==5){
this.markBoxClassName='excellent';
textMark=this.translate('Excellent')}

if(boxToUpdate.hasChildNodes()){
while(boxToUpdate.childNodes.length>=1){
boxToUpdate.removeChild(boxToUpdate.firstChild)}
}

var passwordMarkText=document.createTextNode(textMark);
boxToUpdate.appendChild(passwordMarkText);

for(i=0;i<=passwordMark;i++){
object=$('passwordMark'+i);
object.addClassName(this.markBoxClassName)}

boxToUpdate.addClassName(this.markBoxClassName)},



updateInfoMessageBox:function(){
if(!this.infoMessageObjectId){
return}

infoMessageObject=$(this.infoMessageObjectId);

if(infoMessageObject.hasChildNodes()){
while(infoMessageObject.childNodes.length>=1){
infoMessageObject.removeChild(infoMessageObject.firstChild)}
}

if(!this.infoMessage){
return}

var infoMessageText=document.createTextNode(" \u2014 "+this.infoMessage);
infoMessageObject.appendChild(infoMessageText)},



translate:function(txt){
try{
return _(txt)}

catch(e){
return txt}
}
};




var jsAjaxHistory=Class.create();
jsAjaxHistory.prototype={
initialize:function(){
this.currentLocation='';
this.callback=null;
this.ignoreLocationChange=false;
this.ignoreWait=0;
this.iframe=null;
this.garbageCollectorThreshold=2000000;
this.garbageCollectorInterval=8000;
this.garbageCollectorActive=false;
this.ajaxInProgress=false},


getCurrentHash:function(){
if(Prototype.Browser.IE){
if(window.frames['ajaxHistoryFrame']&&parseInt(window.frames['ajaxHistoryFrame'].location.toString().split('?')[1])>0&&window.frames['ajaxHistoryFrame'].location.toString().split('?')[1]!=window.location.href.toString().split('#')[1]){
window.location.hash=window.frames['ajaxHistoryFrame'].location.toString().split('?')[1];
return window.frames['ajaxHistoryFrame'].location.toString().split('?')[1]}else if(parseInt(window.location.href.toString().split('#')[1])>0){
return window.location.href.toString().split('#')[1]}
}else{
return window.location.href.toString().split('#')[1]}
},


registerCallback:function(callback){
this.callback=callback},

getAjaxInProgress:function(){
return this.ajaxInProgress},

setAjaxInProgress:function(val){
this.ajaxInProgress=val},


fireHistoryEvent:function(hash){
var data=this.load(hash);
if(data){
this.callback.call(null,hash,data)}
},


ram:function(k,v){
var that=this;
var tryAgain=function(){that.ram(k,v)};

if(this.ramLocked){
this.log("Ram (): ram is locked, waiting","#5FF3FF");
setTimeout(tryAgain,100)}else{
this.ramLocked=true;
var c=String.fromCharCode(1);
var f=function(k,v){
return v?k.toString().replace(/\x01\x01/g,c):k.toString().replace(/\x01/g,c+c)};
var p=".";
var w=window;
var r=w.name.split(k=p+c+p+f(k)+p+c+p);
this.ramLocked=false;
return arguments.length<2?f(r[1]||"",1):(w.name=[r[0],f(v),r[2]||""].join(k))&&v}
},


ramUsage:function(){
return window.name.length},


ramClear:function(){
window.name=''},


ramSlice:function(){
var c=String.fromCharCode(1);
var p=".";
window.name=window.name.split(p+c+p).slice(4).join(p+c+p)},


garbageCollector:function(){
if(!this.garbageCollectorActive){
this.garbageCollectorActive=true;
if(this.ramUsage()>this.garbageCollectorThreshold){
while(this.ramUsage()>this.garbageCollectorThreshold){
this.ramSlice()}
}
this.garbageCollectorActive=false}
},


store:function(id,data){
var that=this;
var tryAgain=function(){that.store(id,data)};

if(this.garbageCollectorActive){
setTimeout(tryAgain,100)}
else if(this.ramUsage()>this.garbageCollectorThreshold){
this.garbageCollector();
setTimeout(tryAgain,100)}
else if((this.ramUsage()+Object.toJSON(data).length)>this.garbageCollectorThreshold){
this.ram(id,Object.toJSON(data));
this.garbageCollector()}
else{
this.ram(id,Object.toJSON(data))}
},


load:function(id){
if(id){
var data=this.ram(id);
if(data){
return data.evalJSON()}
}
else{
return false}
},


add:function(id,data){
var that=this;
var tryAgain=function(){that.add(id,data)};
var newLocation=id;

if(Prototype.Browser.IE){
if(this.ignoreWait!=0){
setTimeout(tryAgain,100)}else{
that.ignoreWait=newLocation;
that.currentLocation=newLocation;
that.iframe.src="/gfx/blank.gif?"+newLocation;
this.store(id,data)}
}else{
window.location.hash=newLocation;
this.store(id,data);
that.ignoreLocationChange=true;
that.currentLocation=newLocation}
},


clone:function(o){
if(typeof(o)!='object'){
return o}
var n=new Object();
for(var i in o){
if(i.substr((i.length-2),2)=='[]'){
n[i]=o[i]}else{
n[i]=this.clone(o[i])}
}
return n},


setup:function(){
if(Prototype.Browser.IE){
this.iframe=$('ajaxHistoryFrame')}
var that=this;
var locationHandler=function(){that.checkLocation()};
var garbageCollector=function(){that.garbageCollector()};
setInterval(locationHandler,100);
setInterval(garbageCollector,this.garbageCollectorInterval)},


checkLocation:function(){
var hash=this.getCurrentHash();

if(parseInt(this.ignoreWait)!=0){
if(parseInt(hash)==parseInt(this.ignoreWait)){
this.ignoreWait=0}
return}

if(hash==this.currentLocation){
return}

if(this.ignoreLocationChange){
this.ignoreLocationChange=false;
return}

this.currentLocation=hash;
this.fireHistoryEvent(hash)},


removeHash:function(hashValue){
if(hashValue===null||hashValue===undefined){
return null}
else{
return hashValue.replace(/\#/g,'')}
},


createLock:function(){
this.garbageCollectorActive=true},


releaseLock:function(){
this.garbageCollectorActive=false},


log:function(data,color){
var date=new Date();
var h=(date.getHours()<10)?'0'+date.getHours():date.getHours();
var m=(date.getMinutes()<10)?'0'+date.getMinutes():date.getMinutes();
var s=(date.getSeconds()<10)?'0'+date.getSeconds():date.getSeconds();
if(data){
if($('footer')){
$('footer').innerHTML='['+h+':'+m+':'+s+'] <span style="background-color: '+color+'">'+data+'</span><br/>'+$('footer').innerHTML}
}
}
};

var jsAjaxHistoryDev=Class.create();
jsAjaxHistoryDev.prototype={
initialize:function(){
this.currentLocation='';
this.callback=null;
this.ignoreLocationChange=false;
this.ignoreWait=0;
this.iframe=null;
this.garbageCollectorThreshold=2000000;
this.garbageCollectorInterval=8000;
this.garbageCollectorActive=false;
this.ramLocked=false},

getCurrentHash:function(){
if(Prototype.Browser.IE){
if(window.frames['ajaxHistoryFrame']&&parseInt(window.frames['ajaxHistoryFrame'].location.toString().split('?')[1])>0&&window.frames['ajaxHistoryFrame'].location.toString().split('?')[1]!=window.location.href.toString().split('#')[1]){
window.location.hash=window.frames['ajaxHistoryFrame'].location.toString().split('?')[1];
return window.frames['ajaxHistoryFrame'].location.toString().split('?')[1]}else if(parseInt(window.location.href.toString().split('#')[1])>0){
return window.location.href.toString().split('#')[1]}
}else{
return window.location.href.toString().split('#')[1]}
},

registerCallback:function(callback){
this.callback=callback},

fireHistoryEvent:function(hash){
this.log("fireHistoryEvent (): history event");
var data=this.load(hash);
if(data){
this.log("fireHistoryEvent (): calling registered callback");
this.callback.call(null,hash,data)}
},

ram:function(k,v){
var that=this;
var tryAgain=function(){that.ram(k,v)};

if(this.ramLocked){
this.log("Ram (): ram is locked, waiting","#5FF3FF");
setTimeout(tryAgain,100)}else{
this.ramLocked=true;
var c=String.fromCharCode(1);
var f=function(k,v){
return v?k.toString().replace(/\x01\x01/g,c):k.toString().replace(/\x01/g,c+c)};
var p=".";
var w=window;
var r=w.name.split(k=p+c+p+f(k)+p+c+p);
this.ramLocked=false;
return arguments.length<2?f(r[1]||"",1):(w.name=[r[0],f(v),r[2]||""].join(k))&&v}
},

ramUsage:function(){
return window.name.length},

ramClear:function(){
window.name=''},

ramDump:function(){
this.log(window.name)},

ramSlice:function(){
var c=String.fromCharCode(1);
var p=".";
this.log("ramSlice (): slicing ram",'#FFAFAF');
window.name=window.name.split(p+c+p).slice(4).join(p+c+p)},

garbageCollector:function(){
this.log("garbageCollector (): Ram usage: "+this.ramUsage()+"bytes, threshold: "+this.garbageCollectorThreshold+"bytes");
if(!this.garbageCollectorActive){
this.log("garbageCollector (): acquired ram lock");
this.garbageCollectorActive=true;
if(this.ramUsage()>this.garbageCollectorThreshold){
while(this.ramUsage()>this.garbageCollectorThreshold){
this.log("garbageCollector (): calling ramSlice ()");
this.ramSlice();
this.log("garbageCollector (): Ram usage: "+this.ramUsage()+"bytes, threshold: "+this.garbageCollectorThreshold+"bytes")}
}
this.log("garbageCollector (): releasing ram lock");
this.garbageCollectorActive=false}else{
this.log("garbageCollector (): already running")}
},

store:function(id,data){
var that=this;
var tryAgain=function(){that.store(id,data)};

if(this.garbageCollectorActive){
setTimeout(tryAgain,100)}
else if(this.ramUsage()>this.garbageCollectorThreshold){
this.log("store (): Exceeded threshold, calling garbage collector, delaying store","#FFB257");
this.garbageCollector();
setTimeout(tryAgain,100)}
else if((this.ramUsage()+Object.toJSON(data).length)>this.garbageCollectorThreshold){
this.log("store (): Storing "+id+" will exceed threshold, calling garbage collector","#FFB257");
this.log("store (): Stored "+id+" in ram","#A4FF9F");
this.ram(id,Object.toJSON(data));
this.garbageCollector()}
else{
this.log("store (): Stored "+id+" in ram","#A4FF9F");
this.ram(id,Object.toJSON(data))}
},

load:function(id){
if(id){
this.log("load (): Loading id: "+id);
var data=this.ram(id);
if(data){
return data.evalJSON()}
}
else{
return false}
},

add:function(id,data){
var that=this;
var tryAgain=function(){that.add(id,data)};
var newLocation=id;
this.log("add (): New hash is: "+newLocation);

if(Prototype.Browser.IE){
if(this.ignoreWait!=0){
setTimeout(tryAgain,100)}else{
that.ignoreWait=newLocation;
that.currentLocation=newLocation;
that.iframe.src="/gfx/blank.gif?"+newLocation;
this.store(id,data)}
}else{
window.location.hash=newLocation;
this.store(id,data);
that.ignoreLocationChange=true;
that.currentLocation=newLocation}
},

clone:function(o){
if(typeof(o)!='object'){
return o}
var n=new Object();
for(var i in o){
if(i.substr((i.length-2),2)=='[]'){
n[i]=o[i]}else{
n[i]=this.clone(o[i])}
}
return n},

setup:function(){
this.log("setup (): Setting up");
if(Prototype.Browser.IE){
this.iframe=$('ajaxHistoryFrame')}
var that=this;
var locationHandler=function(){that.checkLocation()};
var garbageCollector=function(){that.garbageCollector()};
setInterval(locationHandler,100);
setInterval(garbageCollector,this.garbageCollectorInterval)},

checkLocation:function(){
var hash=this.getCurrentHash();

if(parseInt(this.ignoreWait)!=0){
if(parseInt(hash)==parseInt(this.ignoreWait)){
this.ignoreWait=0}
this.log("checkLocation (): Ignore wait, waiting for "+this.ignoreWait+" but current is: "+hash);
return}

if(hash==this.currentLocation){
return}

if(this.ignoreLocationChange){
this.log("checkLocation (): Ignoring location change, active: "+hash+" obj currentLocation: "+this.currentLocation);
this.ignoreLocationChange=false;
this.log("checkLocation (): Ignoring, changing currentLocation: "+this.currentLocation);
return}

this.log("checkLocation (): Url change detected, active: "+hash+" currentLocation: "+this.currentLocation);
this.currentLocation=hash;
this.fireHistoryEvent(hash)},

removeHash:function(hashValue){
this.log("removeHash (): removing existing hashes from string");
if(hashValue===null||hashValue===undefined){
return null}
else{
return hashValue.replace(/\#/g,'')}
},

log:function(data,color){
var date=new Date();
var h=(date.getHours()<10)?'0'+date.getHours():date.getHours();
var m=(date.getMinutes()<10)?'0'+date.getMinutes():date.getMinutes();
var s=(date.getSeconds()<10)?'0'+date.getSeconds():date.getSeconds();
if(data){
if($('footer')){
$('footer').innerHTML='['+h+':'+m+':'+s+'] <span style="background-color: '+color+'">'+data+'</span><br/>'+$('footer').innerHTML}else{
alert('no foter')}
}
},

createLock:function(){
this.garbageCollectorActive=true},

releaseLock:function(){
this.garbageCollectorActive=false},

saveMb:function(){
var kb='';
var mb='';
for(i=0;i<1024;i++){
kb+='.'}
for(i=0;i<1024;i++){
mb+=kb}
window.name+=mb;
this.log("Ram usage: "+(this.ramUsage()/1024/1024)+" MB")},

testBrowserStorage:function(){
var i;
var that=this;
this.ramClear();
var saveMb=function(){that.saveMb()};
this.garbageCollectorActive=true;
setInterval(saveMb,500)}
};

var ajaxHistory=new jsAjaxHistory();


Event.observe(window,'load',function(){
forms=$$('form');

if(forms&&forms.size()==1&&$('login')&&(!$('loginHeader')||$('loginHeader')&&$('loginHeader').visible())){
$('login').focus()}
});

Event.observe(window,'load',globalBlur);

function globalBlur(){
var elements=$$('a','button','input[type="submit"]','input[type="button"]');
elements.each(function(element){
Event.observe(element,'focus',myBlur)})}

function myBlur(event){
Event.element(event).blur()}


function fillTimezones(val){
var timezonesHash=$H(timezones);
var values=timezonesHash.get(val);
Form.selectUpdate('timezone2',values,true)}



function methodChange(maxMethodsAtOnce){
$$('div .methodBox').invoke('hide');
var methodId;

for(var i=1;i<=maxMethodsAtOnce;i++){
methodId=$('paymentMethodForPartner'+i).value;

if(methodId){
Element.show('method'+methodId+'box')}
}
}



function showStat(obj){
var map=$H({dataTab1:'statTableBasic',dataTab2:'statTableDetailed',dataTab3:'statPie',dataTab4:'statBar'});
var statBoxes=['statTableDetailed','statTableBasic','statPie','statBar'];
var statBoxName=map.get(obj.id);

map.each(function(pair){
if(pair.key==obj.id){
Element.addClassName($(pair.key),'tabActive');
Element.removeClassName($(pair.key),'tab')}

else{
Element.addClassName($(pair.key),'tab');
Element.removeClassName($(pair.key),'tabActive')}

if($(pair.value)){
$(pair.value).hide()}
});

if($(statBoxName)){
$(statBoxName).show()}

return false}


function statReload(baseUrl,liteBaseUrl,bannersPath,statId,grandId,parentId,factor,noDataMsg){
var cashFields=['firstDepositsAmount','depositsAmount','chargebacks','coupons','positiveCredits','netwin','revenue'];
var url=liteBaseUrl+'/charts/pie/statId/'+statId+'/grandId/'+grandId+'/parentId/'+parentId+'/factor/'+factor+'/returnAs/json';

new Ajax.Request(url,{
method:'get',

onSuccess:function(transport){
var data=eval(transport.responseText);

var output1='';
var output2='';

if(data.length>0){
data.each(
function(item,index){
if(statId=='banner'&&item.data)
item.name='<a href="#" onclick="return showInfoWindow (event, \''+bannersPath+item.data.storageFilename+'\', \''+item.data.casinoId+'\', \''+item.data.casinoName+'\', \''+item.data.width+'\', \''+item.data.height+'\', \''+item.data.type+'\', \''+item.data.landingPage+'\', \''+item.data.title+'\', \''+item.data.bannerText+'\')">'+item.name+'</a>';

output1+='<tr class="noHover"><td>'+item.name+'</td><td>'+item.value+'</td><td>'+item.percent+'%</td><td class="last" style="text-align:left"><div class="graphBar" style="width: '+(item.percent*3.5)+'px"></div></td></tr>';
output2+='<tr class="noHover" style="height: 25px"><td>'+item.name+'</td><td>'+item.value+'</td><td>'+item.percent+'%</td>'+(index==0?'<td id="chartDiv" class="last noPadding" rowspan="'+(data.length)+'"></td>':'')+'</tr>'}
);

$('statBarBody').update(output1);
$('statPieBody').update(output2);

chartReload(baseUrl,'Pie2D','pieChart','400','300',liteBaseUrl+'/charts/pie/statId/'+statId+'/grandId/'+grandId+'/parentId/'+parentId+'/factor/'+factor+'/returnAs/xml','chartDiv')}

else{
output1=output2='<tr class="noHover"><td colspan="4" style="padding: 50px 0" class="last">'+noDataMsg+'</td></tr>';
$('statBarBody').update(output1);
$('statPieBody').update(output2)}

$('pieSelect').value=$('barSelect').value=factor},

onException:function(req,e){
exceptionAlert('Error.',e)}
})}

function lineChartIds(baseUrl,liteBaseUrl,grandId,parentId,statId,statsType,id,value){
var url=liteBaseUrl+'/charts/lineChartIds/grandId/'+grandId+'/parentId/'+parentId+'/statId/'+statId+'/id/'+id+'/value/'+value;

new Ajax.Request(url,{
method:'get',

onSuccess:function(transport){
chartReload(baseUrl,'ScrollLine2D','lineChartFC','740','220',liteBaseUrl+'/charts/line/grandId/'+grandId+'/parentId/'+parentId+'/statId/'+statId+'/statsType/'+statsType,'lineChartDiv')},

onException:function(req,e){
exceptionAlert('Error.',e)}
})}


function lineChartFactors(baseUrl,liteBaseUrl,grandId,parentId,statId,statsType,itemId){
var numbersFields=['clicks','uniqueDownloads','downloads','signups','firstDeposits','deposits'];

var factors=new Hash();

var type=$('factorsType').value;

var checkboxes=document.getElementsByName('factors');
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked&&checkboxes[i].disabled==0){
if((type=='numbers'&&numbersFields.indexOf(checkboxes[i].value)>-1)||(type=='money'&&numbersFields.indexOf(checkboxes[i].value)==-1)){
factors.set(checkboxes[i].value,1)}
}
}

if(factors.size()==0){
alert('Please select at least one metric to graph.');
return}

factors.set('type',type);

var url=liteBaseUrl+'/charts/lineChartFactors/grandId/'+grandId+'/parentId/'+parentId+'/statId/'+statId;

new Ajax.Request(url,{
method:'post',
parameters:factors,

onSuccess:function(transport){
chartReload(baseUrl,'ScrollLine2D','lineChartFC','740','220',liteBaseUrl+'/charts/line/grandId/'+grandId+'/parentId/'+parentId+'/itemId/'+itemId+'/statId/'+statId+'/statsType/'+statsType+'/','lineChartDiv')},

onException:function(req,e){
exceptionAlert('Error.',e)}
})}

function chartReload(baseUrl,chart,chartName,chartWidth,chartHeight,dataUrl,chartDiv){
var chart=new FusionCharts(baseUrl+"/gfx/charts/"+chart+".swf",chartName,chartWidth,chartHeight,"0","1");
chart.setDataURL(dataUrl);
chart.render(chartDiv)}



function showInfoWindow(e,casinoId,casinoName,filename,width,height,bannerTypeName,bannerTypeLabel,landingPage,title,bannerText,description,htmlCode){
try{
var parentObj=Event.element(e);

if(filename){
var ext=filename.split('.')[(filename.split('.').length)-1].toLowerCase()}
Event.stop(e);

if($('bannerInfo')){
$('bannerInfo').remove()}
var so;
var infoBox=document.createElement('div');

var offset=Position.cumulativeOffset(parentObj);
infoBox.id='bannerInfo';

infoBox.style.top=offset[1]+'px';
infoBox.style.left=offset[0]+'px';
if(bannerTypeName=='progressives'){
var randomNumber=Math.ceil(1000000*Math.random());
htmlCode=htmlCode.replace(/true\">/,'true/'+randomNumber+'">');
htmlCode=htmlCode.replace('<div','<div id="progressiveDiv'+randomNumber+'"');
infoBox.innerHTML+='<div style="margin-bottom: 15px">'+htmlCode+'</div><br />'}
else if(ext=='gif'||ext=='png'||ext=='jpg'){
infoBox.innerHTML+='<div style="margin-bottom: 15px"><img src="'+filename+'" /></div><br />'}
else if(bannerTypeName=='landingPages'||bannerTypeName=='directDownload')
infoBox.innerHTML+='<div style="margin-bottom: 15px"><a href="#" title="'+title+'">'+bannerText+'</a></div><br />';
else if(bannerTypeName=='flashBanners'||(bannerTypeName=='topLayer'&&ext=='swf')){
infoBox.innerHTML+='<div style="margin-bottom: 15px" id="flashBanner"></div><br />';
so=new SWFObject(filename,"flashBanner",width,height,"8","#000000")}
else if(bannerTypeName=='feedBanners'){
infoBox.innerHTML+='<div style="margin-bottom: 15px">'+window.flashFeedPreviewCode+'</div><br />'}

if(casinoName)
infoBox.innerHTML+='<div class="label">Casino:</div><div>'+casinoName+'</div><br />';
if(bannerTypeName)
infoBox.innerHTML+='<div class="label">Banner Type:</div><div>'+bannerTypeLabel+'</div><br />';
if(width!=0&&height!=0)
infoBox.innerHTML+='<div class="label">Size:</div><div>'+width+' x '+height+' px</div><br />';
if(landingPage)
infoBox.innerHTML+='<div class="label">Landing page:</div><div><a href="'+landingPage+'" target="_blank">'+landingPage+'</a></div><br />';
if(title)
infoBox.innerHTML+='<div class="label">Title (html):</div><div>'+title+'</div><br />';
if(bannerText)
infoBox.innerHTML+='<div class="label">Banner text:</div><div>'+bannerText+'</div><br />';
if(description)
infoBox.innerHTML+='<div class="label">Description:</div><div>'+description+'</div><br />';

document.body.appendChild(infoBox);

Event.observe(
document.body,
'click',
function(){
if($('bannerInfo')){
$('bannerInfo').remove()}
}
);

if(so&&bannerTypeName=='flashBanners'&&$('flashBanner')){
so.addParam('flashvars','landingPage='+landingPage);
so.write('flashBanner')}
}

catch(e){
exceptionAlert('Error in function: showInfoWindow().',e)}

return false}



function popupCalendar(visibleObj,hiddenObj){
this.visibleObj=visibleObj;
this.hiddenObj=hiddenObj;
this.calendar=new CalendarDateSelect($(this.visibleObj),{popup:true,onchange:function(){
if($(this.hiddenObj)){
$(this.hiddenObj).value=DateSelect.dateParse(this.calendar.selected_date)}
}.bindAsEventListener(this)});

var calendarBoxes=document.getElementsByClassName('calendar_date_select');
var calendarBox=calendarBoxes[0];
calendarBox.setStyle({padding:'10px',backgroundColor:'#8e8e8e'})}



function clearDateFields(mainFieldId){
$(mainFieldId).clear();
$(mainFieldId+'Value').clear()}



function init(){
var arVersion=navigator.appVersion.split("MSIE");
var version=parseFloat(arVersion[1]);

if(version>=5.5&&version<7&&document.body.filters){
fixPNG()}

makePngVisible()}


function makePngVisible(){
for(var i=0;i<document.images.length;i++){
var img=document.images[i];
var imgName=img.src.toUpperCase();
if(imgName.substring(imgName.length-3,imgName.length)=="PNG"){
img.style.visibility='visible'}
}
}

function fixPNG(){}


function checkAffiliateExists(){
var affiliateTipSpan=$('affiliateTip');

if(!$('affiliateId').value){
$('affiliateId').removeClassName('formError');
affiliateTipSpan.removeChild(affiliateTipSpan.firstChild);
return false}

new Ajax.Request('/lite/checks/affiliateExists/affiliate/'+$('affiliateId').value,{
method:'get',
requestHeaders:{Accept:'application/json'},
onSuccess:function(transport){
var json=transport.responseText.evalJSON(true);

if(affiliateTipSpan.firstChild){
affiliateTipSpan.removeChild(affiliateTipSpan.firstChild)}

var affiliateFieldErrorContainer=document.createElement('span');
affiliateFieldErrorContainer.setAttribute('id','affiliateFieldErrorContainer');

if(json.result){
$('affiliateId').removeClassName('formError');
var affiliteFieldErrorMsg=document.createTextNode('OK');
affiliateFieldErrorContainer.appendChild(affiliteFieldErrorMsg);
affiliateFieldErrorContainer.setStyle({color:'#4D9E05'});
affiliateTipSpan.appendChild(affiliateFieldErrorContainer)}
else{
var affiliteFieldErrorMsg=document.createTextNode(json.errorMsg);
affiliateFieldErrorContainer.appendChild(affiliteFieldErrorMsg);
affiliateFieldErrorContainer.setStyle({color:'#AB2B2B'});
affiliateTipSpan.appendChild(affiliateFieldErrorContainer);
$('affiliateId').toggleClassName('formError')}
}
}
)}



Event.onDOMReady(function(){
$$('ul.dropdown li').each(function(elm){
elm.onmouseover=function(){
this.addClassName('hover');
var dir,ul;
if(dir=this.getElementsBySelector('.dir').first()){
dir.addClassName('open')}
if(ul=this.getElementsBySelector('ul').first()){
ul.setStyle({visibility:'visible'})}
};

elm.onmouseout=function(){
this.removeClassName('hover');
this.getElementsBySelector('.open').invoke('removeClassName','open');
var ul;
if(ul=this.getElementsBySelector('ul').first()){
ul.setStyle({visibility:'hidden'})}
}})});


Event.observe(window,'load',init);


var currentSearch=0;
var currentLimit=0;
var firstLoad=true;

var backButton=function(anchor,data){
if(anchor>0&&typeof(data)=='object'){
ajaxHistory.setAjaxInProgress(true);
var rid=new Date().valueOf().toString();
Wait.show((data.options.parameters.onSuccess)?data.options.parameters.onSuccess:data.id);
new Ajax.Updater(data.id,data.url,data.options)}else{
}
};

if(typeof ajaxHistory!='undefined'){
Event.observe(window,'load',function(){
ajaxHistory.registerCallback(backButton);
ajaxHistory.setup()});

Ajax.Responders.register({
onComplete:function(req){
ajaxHistory.setAjaxInProgress(false);
if(!req.options.parameters._history){
var id=new Date().valueOf().toString();
switch(req.url.split('/')[3]){
case"paging":
case"limit":
case"columns":
case"sort":
if(currentSearch>0){
var ps=ajaxHistory.clone(ajaxHistory.load(currentSearch));
ps.options.parameters._offset=(req.url.split('/')[3]=='paging')?req.url.split('/')[9]:0;
ps.options.parameters._limit=currentLimit=(req.url.split('/')[3]=='limit')?req.url.split('/')[9]:currentLimit;
ps.options.parameters._sort=currentSort=(req.url.split('/')[3]=='sort')?req.url.split('/')[9]:currentSort;
ps.options.parameters._relatedSearch=currentSearch}else{
var urlParts=req.url.split('/');
if(firstLoad){
firstLoad=false;
switch(urlParts[3]){
case'paging':
urlParts[9]=0;
break;
case'limit':
urlParts[9]=currentLimit;
break;
case'sort':
urlParts[9]=currentSort;
break}
var url=urlParts.join('/');
var psi=new Object();
psi.options=ajaxHistory.clone(req.options);
psi.options.parameters._history=1;
var cnt=0;
currentColumns.each(function(item){
psi.options.parameters["_columns["+cnt+"]"]=item;
cnt++});
psi.id=req.container.success;
psi.url=url;
ajaxHistory.add(id,psi);
id++;
var firstLoaded=true}
var ps=new Object();
ps.options=ajaxHistory.clone(req.options);
ps.options.parameters._history=1;
switch(urlParts[3]){
case'columns':
if(!firstLoad){
currentColumns=ajaxHistory.clone(req.options.parameters["_columns[]"])}
break;
case'sort':
currentSort=(req.url.split('/')[3]=='sort')?req.url.split('/')[9]:currentSort;
break}
var cnt=0;
currentColumns=$H(currentColumns).values();
currentColumns.each(function(item){
if(typeof(item)=='string'){
ps.options.parameters["_columns["+cnt+"]"]=item;
cnt++}
});
ps.options.parameters._sort=currentSort;
ps.id=req.container.success;
ps.url=req.url}
break;
case"showAll":
case"search":
var ps=new Object();
ps.options=ajaxHistory.clone(req.options);
ps.options.parameters._history=1;
ps.options.parameters._offset=0;
ps.options.parameters._sort=currentSort;
ps.options.parameters._limit=currentLimit;
ps.options.parameters._relatedSearch=currentSearch=id;
ps.id=req.container.success;
ps.url=req.url;
break}
if(ps){
ajaxHistory.add(id,ps)}
}else{
currentSearch=(req.options.parameters._relatedSearch)?req.options.parameters._relatedSearch:0}
}
})}



function errorHandler(msg,url,lineNo){
var currentLocation=document.location.href;
var urlParts=currentLocation.split("/");
var reportUrl=urlParts[0]+'//'+urlParts[2];
var parentWindowUrl='';

var requestUrl=reportUrl+'/lite/report/reportjs/msg/'+Base64.encode(msg)+'/url/'+Base64.encode(url)+'/lineNo/'+lineNo+'/location/'+Base64.encode(currentLocation);

if(self.parent.location.href&&currentLocation!=self.parent.location.href){
requestUrl=requestUrl+'/parentUrl/'+Base64.encode(self.parent.location.href)}

new Ajax.Request(requestUrl,
{
method:'get',
onSuccess:function(transport){
var response=transport.responseText||"no response text"},
onFailure:function(){}
}
);

return true}


onerror=errorHandler;
var Base64={

_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

encode:function(input){
var output="";
var chr1,chr2,chr3,enc1,enc2,enc3,enc4;
var i=0;

input=Base64._utf8_encode(input);

while(i<input.length){

chr1=input.charCodeAt(i++);
chr2=input.charCodeAt(i++);
chr3=input.charCodeAt(i++);

enc1=chr1>>2;
enc2=((chr1&3)<<4)|(chr2>>4);
enc3=((chr2&15)<<2)|(chr3>>6);
enc4=chr3&63;

if(isNaN(chr2)){
enc3=enc4=64}else if(isNaN(chr3)){
enc4=64}

output=output+
this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+
this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4)}

return output},

_utf8_encode:function(string){
string=string.replace(/\r\n/g,"\n");
var utftext="";

for(var n=0;n<string.length;n++){

var c=string.charCodeAt(n);

if(c<128){
utftext+=String.fromCharCode(c)}
else if((c>127)&&(c<2048)){
utftext+=String.fromCharCode((c>>6)|192);
utftext+=String.fromCharCode((c&63)|128)}
else{
utftext+=String.fromCharCode((c>>12)|224);
utftext+=String.fromCharCode(((c>>6)&63)|128);
utftext+=String.fromCharCode((c&63)|128)}

}

return utftext}
};




