var WMSlideshow=Class.create();WMSlideshow.prototype={initialize:function(windmillid,speed,duration,pause){this.windmillid=windmillid;this.speed=speed;this.duration=duration;this.pause=pause;this.slideshows={};},start:function(){var slideshows=[];$H(this.slideshows).each(function(slideshow){var cid=slideshow[0];var slideshow=slideshow[1];slideshow["cid"]=cid;slideshow["current"]=0;slideshows.push(slideshow);}.bind(this));this.slideshows=slideshows;Event.observe(window,"load",this.slide.bindAsEventListener(this));},changed:function(){document.location.reload();},doSlide:function(){this.time+=this.speed;var firstopacity=Math.cos((this.time/this.duration)*(Math.PI/2));var secondopacity=Math.pow((this.time/this.duration),8);this.slideshows.each(function(slideshow){this.setOpacity($(slideshow.cid+"_first_"+this.windmillid),firstopacity);this.setOpacity($(slideshow.cid+"_second_"+this.windmillid),secondopacity);}.bind(this));if(this.time<this.duration){this.doSlide.bind(this).delay(this.speed/1000);}
else{this.slideshows.each(function(slideshow){$(slideshow.cid+"_first_"+this.windmillid).innerHTML=$(slideshow.cid+"_second_"+this.windmillid).innerHTML;this.setOpacity($(slideshow.cid+"_first_"+this.windmillid),1);this.setOpacity($(slideshow.cid+"_second_"+this.windmillid),0);}.bind(this));this.slide.bind(this).delay(this.pause/1000);}},setOpacity:function(element,opacity){if(element.filters&&element.filters.alpha){element.filters.alpha.opacity=Math.round(opacity*100);}
else{element.style.opacity=opacity;}},slide:function(){this.time=0;this.slideshows.each(function(slideshow){this.setOpacity($(slideshow.cid+"_first_"+this.windmillid),1);this.setOpacity($(slideshow.cid+"_second_"+this.windmillid),0);if($(slideshow.cid+"_first_"+this.windmillid).innerHTML==""){$(slideshow.cid+"_first_"+this.windmillid).innerHTML=slideshow.images[0].html;}
slideshow["next"]=slideshow.current+1;if(slideshow.next==slideshow.images.length){slideshow.next=0;}
if(slideshow.next==slideshow.current){return;}
var nextimage=slideshow.images[slideshow.next];$(slideshow.cid+"_second_"+this.windmillid).innerHTML=nextimage.html;slideshow.current=slideshow.next;}.bind(this));this.doSlide();}};var WMImage=Class.create();WMImage.prototype={initialize:function(url){this.html=this.getHtml(url);},getHtml:function(url){var image=new Image();Event.observe(image,"error",this.imageError.bindAsEventListener(this),false);image.src=url;return"<img alt='' src='"+url+"'/>";},imageError:function(){this.html="<img alt='' src='/images/empty.gif'/>";}};var Scriptaculous={Version:'1.8.1',require:function(libraryName){document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');},REQUIRED_PROTOTYPE:'1.6.0',load:function(){function convertVersionString(versionString){var r=versionString.split('.');return parseInt(r[0])*100000+parseInt(r[1])*1000+parseInt(r[2]);}
if((typeof Prototype=='undefined')||(typeof Element=='undefined')||(typeof Element.Methods=='undefined')||(convertVersionString(Prototype.Version)<convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
throw("script.aculo.us requires the Prototype JavaScript framework >= "+
Scriptaculous.REQUIRED_PROTOTYPE);$A(document.getElementsByTagName("script")).findAll(function(s){return(s.src&&s.src.match(/scriptaculous\.js(\?.*)?$/))}).each(function(s){var path=s.src.replace(/scriptaculous\.js(\?.*)?$/,'');var includes=s.src.match(/\?.*load=([a-z,]*)/);(includes?includes[1]:'builder,effects,dragdrop,controls,slider,sound').split(',').each(function(include){Scriptaculous.require(path+include+'.js')});});}}
Scriptaculous.load();String.prototype.parseColor=function(){var color='#';if(this.slice(0,4)=='rgb('){var cols=this.slice(4,this.length-1).split(',');var i=0;do{color+=parseInt(cols[i]).toColorPart()}while(++i<3);}else{if(this.slice(0,1)=='#'){if(this.length==4)for(var i=1;i<4;i++)color+=(this.charAt(i)+this.charAt(i)).toLowerCase();if(this.length==7)color=this.toLowerCase();}}
return(color.length==7?color:(arguments[0]||this));};Element.collectTextNodes=function(element){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:(node.hasChildNodes()?Element.collectTextNodes(node):''));}).flatten().join('');};Element.collectTextNodesIgnoreClass=function(element,className){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:((node.hasChildNodes()&&!Element.hasClassName(node,className))?Element.collectTextNodesIgnoreClass(node,className):''));}).flatten().join('');};Element.setContentZoom=function(element,percent){element=$(element);element.setStyle({fontSize:(percent/100)+'em'});if(Prototype.Browser.WebKit)window.scrollBy(0,0);return element;};Element.getInlineOpacity=function(element){return $(element).style.opacity||'';};Element.forceRerendering=function(element){try{element=$(element);var n=document.createTextNode(' ');element.appendChild(n);element.removeChild(n);}catch(e){}};var Effect={_elementDoesNotExistError:{name:'ElementDoesNotExistError',message:'The specified DOM element does not exist, but is required for this effect to operate'},Transitions:{linear:Prototype.K,sinoidal:function(pos){return(-Math.cos(pos*Math.PI)/2)+0.5;},reverse:function(pos){return 1-pos;},flicker:function(pos){var pos=((-Math.cos(pos*Math.PI)/4)+0.75)+Math.random()/4;return pos>1?1:pos;},wobble:function(pos){return(-Math.cos(pos*Math.PI*(9*pos))/2)+0.5;},pulse:function(pos,pulses){pulses=pulses||5;return(((pos%(1/pulses))*pulses).round()==0?((pos*pulses*2)-(pos*pulses*2).floor()):1-((pos*pulses*2)-(pos*pulses*2).floor()));},spring:function(pos){return 1-(Math.cos(pos*4.5*Math.PI)*Math.exp(-pos*6));},none:function(pos){return 0;},full:function(pos){return 1;}},DefaultOptions:{duration:1.0,fps:100,sync:false,from:0.0,to:1.0,delay:0.0,queue:'parallel'},tagifyText:function(element){var tagifyStyle='position:relative';if(Prototype.Browser.IE)tagifyStyle+=';zoom:1';element=$(element);$A(element.childNodes).each(function(child){if(child.nodeType==3){child.nodeValue.toArray().each(function(character){element.insertBefore(new Element('span',{style:tagifyStyle}).update(character==' '?String.fromCharCode(160):character),child);});Element.remove(child);}});},multiple:function(element,effect){var elements;if(((typeof element=='object')||Object.isFunction(element))&&(element.length))
elements=element;else
elements=$(element).childNodes;var options=Object.extend({speed:0.1,delay:0.0},arguments[2]||{});var masterDelay=options.delay;$A(elements).each(function(element,index){new effect(element,Object.extend(options,{delay:index*options.speed+masterDelay}));});},PAIRS:{'slide':['SlideDown','SlideUp'],'blind':['BlindDown','BlindUp'],'appear':['Appear','Fade']},toggle:function(element,effect){element=$(element);effect=(effect||'appear').toLowerCase();var options=Object.extend({queue:{position:'end',scope:(element.id||'global'),limit:1}},arguments[2]||{});Effect[element.visible()?Effect.PAIRS[effect][1]:Effect.PAIRS[effect][0]](element,options);}};Effect.DefaultOptions.transition=Effect.Transitions.sinoidal;Effect.ScopedQueue=Class.create(Enumerable,{initialize:function(){this.effects=[];this.interval=null;},_each:function(iterator){this.effects._each(iterator);},add:function(effect){var timestamp=new Date().getTime();var position=Object.isString(effect.options.queue)?effect.options.queue:effect.options.queue.position;switch(position){case'front':this.effects.findAll(function(e){return e.state=='idle'}).each(function(e){e.startOn+=effect.finishOn;e.finishOn+=effect.finishOn;});break;case'with-last':timestamp=this.effects.pluck('startOn').max()||timestamp;break;case'end':timestamp=this.effects.pluck('finishOn').max()||timestamp;break;}
effect.startOn+=timestamp;effect.finishOn+=timestamp;if(!effect.options.queue.limit||(this.effects.length<effect.options.queue.limit))
this.effects.push(effect);if(!this.interval)
this.interval=setInterval(this.loop.bind(this),15);},remove:function(effect){this.effects=this.effects.reject(function(e){return e==effect});if(this.effects.length==0){clearInterval(this.interval);this.interval=null;}},loop:function(){var timePos=new Date().getTime();for(var i=0,len=this.effects.length;i<len;i++)
this.effects[i]&&this.effects[i].loop(timePos);}});Effect.Queues={instances:$H(),get:function(queueName){if(!Object.isString(queueName))return queueName;return this.instances.get(queueName)||this.instances.set(queueName,new Effect.ScopedQueue());}};Effect.Queue=Effect.Queues.get('global');Effect.Base=Class.create({position:null,start:function(options){function codeForEvent(options,eventName){return((options[eventName+'Internal']?'this.options.'+eventName+'Internal(this);':'')+
(options[eventName]?'this.options.'+eventName+'(this);':''));}
if(options&&options.transition===false)options.transition=Effect.Transitions.linear;this.options=Object.extend(Object.extend({},Effect.DefaultOptions),options||{});this.currentFrame=0;this.state='idle';this.startOn=this.options.delay*1000;this.finishOn=this.startOn+(this.options.duration*1000);this.fromToDelta=this.options.to-this.options.from;this.totalTime=this.finishOn-this.startOn;this.totalFrames=this.options.fps*this.options.duration;eval('this.render = function(pos){ '+
'if (this.state=="idle"){this.state="running";'+
codeForEvent(this.options,'beforeSetup')+
(this.setup?'this.setup();':'')+
codeForEvent(this.options,'afterSetup')+
'};if (this.state=="running"){'+
'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
'this.position=pos;'+
codeForEvent(this.options,'beforeUpdate')+
(this.update?'this.update(pos);':'')+
codeForEvent(this.options,'afterUpdate')+
'}}');this.event('beforeStart');if(!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).add(this);},loop:function(timePos){if(timePos>=this.startOn){if(timePos>=this.finishOn){this.render(1.0);this.cancel();this.event('beforeFinish');if(this.finish)this.finish();this.event('afterFinish');return;}
var pos=(timePos-this.startOn)/this.totalTime,frame=(pos*this.totalFrames).round();if(frame>this.currentFrame){this.render(pos);this.currentFrame=frame;}}},cancel:function(){if(!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).remove(this);this.state='finished';},event:function(eventName){if(this.options[eventName+'Internal'])this.options[eventName+'Internal'](this);if(this.options[eventName])this.options[eventName](this);},inspect:function(){var data=$H();for(property in this)
if(!Object.isFunction(this[property]))data.set(property,this[property]);return'#<Effect:'+data.inspect()+',options:'+$H(this.options).inspect()+'>';}});Effect.Parallel=Class.create(Effect.Base,{initialize:function(effects){this.effects=effects||[];this.start(arguments[1]);},update:function(position){this.effects.invoke('render',position);},finish:function(position){this.effects.each(function(effect){effect.render(1.0);effect.cancel();effect.event('beforeFinish');if(effect.finish)effect.finish(position);effect.event('afterFinish');});}});Effect.Tween=Class.create(Effect.Base,{initialize:function(object,from,to){object=Object.isString(object)?$(object):object;var args=$A(arguments),method=args.last(),options=args.length==5?args[3]:null;this.method=Object.isFunction(method)?method.bind(object):Object.isFunction(object[method])?object[method].bind(object):function(value){object[method]=value};this.start(Object.extend({from:from,to:to},options||{}));},update:function(position){this.method(position);}});Effect.Event=Class.create(Effect.Base,{initialize:function(){this.start(Object.extend({duration:0},arguments[0]||{}));},update:Prototype.emptyFunction});Effect.Opacity=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});var options=Object.extend({from:this.element.getOpacity()||0.0,to:1.0},arguments[1]||{});this.start(options);},update:function(position){this.element.setOpacity(position);}});Effect.Move=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({x:0,y:0,mode:'relative'},arguments[1]||{});this.start(options);},setup:function(){this.element.makePositioned();this.originalLeft=parseFloat(this.element.getStyle('left')||'0');this.originalTop=parseFloat(this.element.getStyle('top')||'0');if(this.options.mode=='absolute'){this.options.x=this.options.x-this.originalLeft;this.options.y=this.options.y-this.originalTop;}},update:function(position){this.element.setStyle({left:(this.options.x*position+this.originalLeft).round()+'px',top:(this.options.y*position+this.originalTop).round()+'px'});}});Effect.MoveBy=function(element,toTop,toLeft){return new Effect.Move(element,Object.extend({x:toLeft,y:toTop},arguments[3]||{}));};Effect.Scale=Class.create(Effect.Base,{initialize:function(element,percent){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({scaleX:true,scaleY:true,scaleContent:true,scaleFromCenter:false,scaleMode:'box',scaleFrom:100.0,scaleTo:percent},arguments[2]||{});this.start(options);},setup:function(){this.restoreAfterFinish=this.options.restoreAfterFinish||false;this.elementPositioning=this.element.getStyle('position');this.originalStyle={};['top','left','width','height','fontSize'].each(function(k){this.originalStyle[k]=this.element.style[k];}.bind(this));this.originalTop=this.element.offsetTop;this.originalLeft=this.element.offsetLeft;var fontSize=this.element.getStyle('font-size')||'100%';['em','px','%','pt'].each(function(fontSizeType){if(fontSize.indexOf(fontSizeType)>0){this.fontSize=parseFloat(fontSize);this.fontSizeType=fontSizeType;}}.bind(this));this.factor=(this.options.scaleTo-this.options.scaleFrom)/100;this.dims=null;if(this.options.scaleMode=='box')
this.dims=[this.element.offsetHeight,this.element.offsetWidth];if(/^content/.test(this.options.scaleMode))
this.dims=[this.element.scrollHeight,this.element.scrollWidth];if(!this.dims)
this.dims=[this.options.scaleMode.originalHeight,this.options.scaleMode.originalWidth];},update:function(position){var currentScale=(this.options.scaleFrom/100.0)+(this.factor*position);if(this.options.scaleContent&&this.fontSize)
this.element.setStyle({fontSize:this.fontSize*currentScale+this.fontSizeType});this.setDimensions(this.dims[0]*currentScale,this.dims[1]*currentScale);},finish:function(position){if(this.restoreAfterFinish)this.element.setStyle(this.originalStyle);},setDimensions:function(height,width){var d={};if(this.options.scaleX)d.width=width.round()+'px';if(this.options.scaleY)d.height=height.round()+'px';if(this.options.scaleFromCenter){var topd=(height-this.dims[0])/2;var leftd=(width-this.dims[1])/2;if(this.elementPositioning=='absolute'){if(this.options.scaleY)d.top=this.originalTop-topd+'px';if(this.options.scaleX)d.left=this.originalLeft-leftd+'px';}else{if(this.options.scaleY)d.top=-topd+'px';if(this.options.scaleX)d.left=-leftd+'px';}}
this.element.setStyle(d);}});Effect.Highlight=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({startcolor:'#ffff99'},arguments[1]||{});this.start(options);},setup:function(){if(this.element.getStyle('display')=='none'){this.cancel();return;}
this.oldStyle={};if(!this.options.keepBackgroundImage){this.oldStyle.backgroundImage=this.element.getStyle('background-image');this.element.setStyle({backgroundImage:'none'});}
if(!this.options.endcolor)
this.options.endcolor=this.element.getStyle('background-color').parseColor('#ffffff');if(!this.options.restorecolor)
this.options.restorecolor=this.element.getStyle('background-color');this._base=$R(0,2).map(function(i){return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16)}.bind(this));this._delta=$R(0,2).map(function(i){return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i]}.bind(this));},update:function(position){this.element.setStyle({backgroundColor:$R(0,2).inject('#',function(m,v,i){return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart());}.bind(this))});},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}));}});Effect.ScrollTo=function(element){var options=arguments[1]||{},scrollOffsets=document.viewport.getScrollOffsets(),elementOffsets=$(element).cumulativeOffset(),max=(window.height||document.body.scrollHeight)-document.viewport.getHeight();if(options.offset)elementOffsets[1]+=options.offset;return new Effect.Tween(null,scrollOffsets.top,elementOffsets[1]>max?max:elementOffsets[1],options,function(p){scrollTo(scrollOffsets.left,p.round())});};Effect.Fade=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();var options=Object.extend({from:element.getOpacity()||1.0,to:0.0,afterFinishInternal:function(effect){if(effect.options.to!=0)return;effect.element.hide().setStyle({opacity:oldOpacity});}},arguments[1]||{});return new Effect.Opacity(element,options);};Effect.Appear=function(element){element=$(element);var options=Object.extend({from:(element.getStyle('display')=='none'?0.0:element.getOpacity()||0.0),to:1.0,afterFinishInternal:function(effect){effect.element.forceRerendering();},beforeSetup:function(effect){effect.element.setOpacity(effect.options.from).show();}},arguments[1]||{});return new Effect.Opacity(element,options);};Effect.Puff=function(element){element=$(element);var oldStyle={opacity:element.getInlineOpacity(),position:element.getStyle('position'),top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};return new Effect.Parallel([new Effect.Scale(element,200,{sync:true,scaleFromCenter:true,scaleContent:true,restoreAfterFinish:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:1.0,beforeSetupInternal:function(effect){Position.absolutize(effect.effects[0].element)},afterFinishInternal:function(effect){effect.effects[0].element.hide().setStyle(oldStyle);}},arguments[1]||{}));};Effect.BlindUp=function(element){element=$(element);element.makeClipping();return new Effect.Scale(element,0,Object.extend({scaleContent:false,scaleX:false,restoreAfterFinish:true,afterFinishInternal:function(effect){effect.element.hide().undoClipping();}},arguments[1]||{}));};Effect.BlindDown=function(element){element=$(element);var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:0,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makeClipping().setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.element.undoClipping();}},arguments[1]||{}));};Effect.SwitchOff=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();return new Effect.Appear(element,Object.extend({duration:0.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(effect){new Effect.Scale(effect.element,1,{duration:0.3,scaleFromCenter:true,scaleX:false,scaleContent:false,restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned().setStyle({opacity:oldOpacity});}})}},arguments[1]||{}));};Effect.DropOut=function(element){element=$(element);var oldStyle={top:element.getStyle('top'),left:element.getStyle('left'),opacity:element.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(element,{x:0,y:100,sync:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:0.5,beforeSetup:function(effect){effect.effects[0].element.makePositioned();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);}},arguments[1]||{}));};Effect.Shake=function(element){element=$(element);var options=Object.extend({distance:20,duration:0.5},arguments[1]||{});var distance=parseFloat(options.distance);var split=parseFloat(options.duration)/10.0;var oldStyle={top:element.getStyle('top'),left:element.getStyle('left')};return new Effect.Move(element,{x:distance,y:0,duration:split,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance,y:0,duration:split,afterFinishInternal:function(effect){effect.element.undoPositioned().setStyle(oldStyle);}})}})}})}})}})}});};Effect.SlideDown=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().setStyle({height:'0px'}).show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));};Effect.SlideUp=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:'box',scaleFrom:100,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));};Effect.Squish=function(element){return new Effect.Scale(element,window.opera?1:0,{restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping();}});};Effect.Grow=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var initialMoveX,initialMoveY;var moveX,moveY;switch(options.direction){case'top-left':initialMoveX=initialMoveY=moveX=moveY=0;break;case'top-right':initialMoveX=dims.width;initialMoveY=moveY=0;moveX=-dims.width;break;case'bottom-left':initialMoveX=moveX=0;initialMoveY=dims.height;moveY=-dims.height;break;case'bottom-right':initialMoveX=dims.width;initialMoveY=dims.height;moveX=-dims.width;moveY=-dims.height;break;case'center':initialMoveX=dims.width/2;initialMoveY=dims.height/2;moveX=-dims.width/2;moveY=-dims.height/2;break;}
return new Effect.Move(element,{x:initialMoveX,y:initialMoveY,duration:0.01,beforeSetup:function(effect){effect.element.hide().makeClipping().makePositioned();},afterFinishInternal:function(effect){new Effect.Parallel([new Effect.Opacity(effect.element,{sync:true,to:1.0,from:0.0,transition:options.opacityTransition}),new Effect.Move(effect.element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition}),new Effect.Scale(effect.element,100,{scaleMode:{originalHeight:dims.height,originalWidth:dims.width},sync:true,scaleFrom:window.opera?1:0,transition:options.scaleTransition,restoreAfterFinish:true})],Object.extend({beforeSetup:function(effect){effect.effects[0].element.setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);}},options))}});};Effect.Shrink=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var moveX,moveY;switch(options.direction){case'top-left':moveX=moveY=0;break;case'top-right':moveX=dims.width;moveY=0;break;case'bottom-left':moveX=0;moveY=dims.height;break;case'bottom-right':moveX=dims.width;moveY=dims.height;break;case'center':moveX=dims.width/2;moveY=dims.height/2;break;}
return new Effect.Parallel([new Effect.Opacity(element,{sync:true,to:0.0,from:1.0,transition:options.opacityTransition}),new Effect.Scale(element,window.opera?1:0,{sync:true,transition:options.scaleTransition,restoreAfterFinish:true}),new Effect.Move(element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition})],Object.extend({beforeStartInternal:function(effect){effect.effects[0].element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle);}},options));};Effect.Pulsate=function(element){element=$(element);var options=arguments[1]||{};var oldOpacity=element.getInlineOpacity();var transition=options.transition||Effect.Transitions.sinoidal;var reverser=function(pos){return transition(1-Effect.Transitions.pulse(pos,options.pulses))};reverser.bind(transition);return new Effect.Opacity(element,Object.extend(Object.extend({duration:2.0,from:0,afterFinishInternal:function(effect){effect.element.setStyle({opacity:oldOpacity});}},options),{transition:reverser}));};Effect.Fold=function(element){element=$(element);var oldStyle={top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};element.makeClipping();return new Effect.Scale(element,5,Object.extend({scaleContent:false,scaleX:false,afterFinishInternal:function(effect){new Effect.Scale(element,1,{scaleContent:false,scaleY:false,afterFinishInternal:function(effect){effect.element.hide().undoClipping().setStyle(oldStyle);}});}},arguments[1]||{}));};Effect.Morph=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({style:{}},arguments[1]||{});if(!Object.isString(options.style))this.style=$H(options.style);else{if(options.style.include(':'))
this.style=options.style.parseStyle();else{this.element.addClassName(options.style);this.style=$H(this.element.getStyles());this.element.removeClassName(options.style);var css=this.element.getStyles();this.style=this.style.reject(function(style){return style.value==css[style.key];});options.afterFinishInternal=function(effect){effect.element.addClassName(effect.options.style);effect.transforms.each(function(transform){effect.element.style[transform.style]='';});}}}
this.start(options);},setup:function(){function parseColor(color){if(!color||['rgba(0, 0, 0, 0)','transparent'].include(color))color='#ffffff';color=color.parseColor();return $R(0,2).map(function(i){return parseInt(color.slice(i*2+1,i*2+3),16)});}
this.transforms=this.style.map(function(pair){var property=pair[0],value=pair[1],unit=null;if(value.parseColor('#zzzzzz')!='#zzzzzz'){value=value.parseColor();unit='color';}else if(property=='opacity'){value=parseFloat(value);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});}else if(Element.CSS_LENGTH.test(value)){var components=value.match(/^([\+\-]?[0-9\.]+)(.*)$/);value=parseFloat(components[1]);unit=(components.length==3)?components[2]:null;}
var originalValue=this.element.getStyle(property);return{style:property.camelize(),originalValue:unit=='color'?parseColor(originalValue):parseFloat(originalValue||0),targetValue:unit=='color'?parseColor(value):value,unit:unit};}.bind(this)).reject(function(transform){return((transform.originalValue==transform.targetValue)||(transform.unit!='color'&&(isNaN(transform.originalValue)||isNaN(transform.targetValue))))});},update:function(position){var style={},transform,i=this.transforms.length;while(i--)
style[(transform=this.transforms[i]).style]=transform.unit=='color'?'#'+
(Math.round(transform.originalValue[0]+
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart()+
(Math.round(transform.originalValue[1]+
(transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart()+
(Math.round(transform.originalValue[2]+
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart():(transform.originalValue+
(transform.targetValue-transform.originalValue)*position).toFixed(3)+
(transform.unit===null?'':transform.unit);this.element.setStyle(style,true);}});Effect.Transform=Class.create({initialize:function(tracks){this.tracks=[];this.options=arguments[1]||{};this.addTracks(tracks);},addTracks:function(tracks){tracks.each(function(track){track=$H(track);var data=track.values().first();this.tracks.push($H({ids:track.keys().first(),effect:Effect.Morph,options:{style:data}}));}.bind(this));return this;},play:function(){return new Effect.Parallel(this.tracks.map(function(track){var ids=track.get('ids'),effect=track.get('effect'),options=track.get('options');var elements=[$(ids)||$$(ids)].flatten();return elements.map(function(e){return new effect(e,Object.extend({sync:true},options))});}).flatten(),this.options);}});Element.CSS_PROPERTIES=$w('backgroundColor backgroundPosition borderBottomColor borderBottomStyle '+
'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth '+
'borderRightColor borderRightStyle borderRightWidth borderSpacing '+
'borderTopColor borderTopStyle borderTopWidth bottom clip color '+
'fontSize fontWeight height left letterSpacing lineHeight '+
'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
'maxWidth minHeight minWidth opacity outlineColor outlineOffset '+
'outlineWidth paddingBottom paddingLeft paddingRight paddingTop '+
'right textIndent top width wordSpacing zIndex');Element.CSS_LENGTH=/^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;String.__parseStyleElement=document.createElement('div');String.prototype.parseStyle=function(){var style,styleRules=$H();if(Prototype.Browser.WebKit)
style=new Element('div',{style:this}).style;else{String.__parseStyleElement.innerHTML='<div style="'+this+'"></div>';style=String.__parseStyleElement.childNodes[0].style;}
Element.CSS_PROPERTIES.each(function(property){if(style[property])styleRules.set(property,style[property]);});if(Prototype.Browser.IE&&this.include('opacity'))
styleRules.set('opacity',this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);return styleRules;};if(document.defaultView&&document.defaultView.getComputedStyle){Element.getStyles=function(element){var css=document.defaultView.getComputedStyle($(element),null);return Element.CSS_PROPERTIES.inject({},function(styles,property){styles[property]=css[property];return styles;});};}else{Element.getStyles=function(element){element=$(element);var css=element.currentStyle,styles;styles=Element.CSS_PROPERTIES.inject({},function(results,property){results[property]=css[property];return results;});if(!styles.opacity)styles.opacity=element.getOpacity();return styles;};};Effect.Methods={morph:function(element,style){element=$(element);new Effect.Morph(element,Object.extend({style:style},arguments[2]||{}));return element;},visualEffect:function(element,effect,options){element=$(element)
var s=effect.dasherize().camelize(),klass=s.charAt(0).toUpperCase()+s.substring(1);new Effect[klass](element,options);return element;},highlight:function(element,options){element=$(element);new Effect.Highlight(element,options);return element;}};$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
'pulsate shake puff squish switchOff dropOut').each(function(effect){Effect.Methods[effect]=function(element,options){element=$(element);Effect[effect.charAt(0).toUpperCase()+effect.substring(1)](element,options);return element;}});$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(function(f){Effect.Methods[f]=Element[f];});Element.addMethods(Effect.Methods);var Builder={NODEMAP:{AREA:'map',CAPTION:'table',COL:'table',COLGROUP:'table',LEGEND:'fieldset',OPTGROUP:'select',OPTION:'select',PARAM:'object',TBODY:'table',TD:'table',TFOOT:'table',TH:'table',THEAD:'table',TR:'table'},node:function(elementName){elementName=elementName.toUpperCase();var parentTag=this.NODEMAP[elementName]||'div';var parentElement=document.createElement(parentTag);try{parentElement.innerHTML="<"+elementName+"></"+elementName+">";}catch(e){}
var element=parentElement.firstChild||null;if(element&&(element.tagName.toUpperCase()!=elementName))
element=element.getElementsByTagName(elementName)[0];if(!element)element=document.createElement(elementName);if(!element)return;if(arguments[1])
if(this._isStringOrNumber(arguments[1])||(arguments[1]instanceof Array)||arguments[1].tagName){this._children(element,arguments[1]);}else{var attrs=this._attributes(arguments[1]);if(attrs.length){try{parentElement.innerHTML="<"+elementName+" "+
attrs+"></"+elementName+">";}catch(e){}
element=parentElement.firstChild||null;if(!element){element=document.createElement(elementName);for(attr in arguments[1])
element[attr=='class'?'className':attr]=arguments[1][attr];}
if(element.tagName.toUpperCase()!=elementName)
element=parentElement.getElementsByTagName(elementName)[0];}}
if(arguments[2])
this._children(element,arguments[2]);return element;},_text:function(text){return document.createTextNode(text);},ATTR_MAP:{'className':'class','htmlFor':'for'},_attributes:function(attributes){var attrs=[];for(attribute in attributes)
attrs.push((attribute in this.ATTR_MAP?this.ATTR_MAP[attribute]:attribute)+
'="'+attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;')+'"');return attrs.join(" ");},_children:function(element,children){if(children.tagName){element.appendChild(children);return;}
if(typeof children=='object'){children.flatten().each(function(e){if(typeof e=='object')
element.appendChild(e)
else
if(Builder._isStringOrNumber(e))
element.appendChild(Builder._text(e));});}else
if(Builder._isStringOrNumber(children))
element.appendChild(Builder._text(children));},_isStringOrNumber:function(param){return(typeof param=='string'||typeof param=='number');},build:function(html){var element=this.node('div');$(element).update(html.strip());return element.down();},dump:function(scope){if(typeof scope!='object'&&typeof scope!='function')scope=window;var tags=("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY "+
"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET "+
"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);tags.each(function(tag){scope[tag]=function(){return Builder.node.apply(Builder,[tag].concat($A(arguments)));}});}}
if(typeof Effect=='undefined')
throw("controls.js requires including script.aculo.us' effects.js library");var Autocompleter={}
Autocompleter.Base=Class.create({baseInitialize:function(element,update,options){element=$(element)
this.element=element;this.update=$(update);this.hasFocus=false;this.changed=false;this.active=false;this.index=0;this.entryCount=0;this.oldElementValue=this.element.value;if(this.setOptions)
this.setOptions(options);else
this.options=options||{};this.options.paramName=this.options.paramName||this.element.name;this.options.tokens=this.options.tokens||[];this.options.frequency=this.options.frequency||0.4;this.options.minChars=this.options.minChars||1;this.options.onShow=this.options.onShow||function(element,update){if(!update.style.position||update.style.position=='absolute'){update.style.position='absolute';Position.clone(element,update,{setHeight:false,offsetTop:element.offsetHeight});}
Effect.Appear(update,{duration:0.15});};this.options.onHide=this.options.onHide||function(element,update){new Effect.Fade(update,{duration:0.15})};if(typeof(this.options.tokens)=='string')
this.options.tokens=new Array(this.options.tokens);if(!this.options.tokens.include('\n'))
this.options.tokens.push('\n');this.observer=null;this.element.setAttribute('autocomplete','off');Element.hide(this.update);Event.observe(this.element,'blur',this.onBlur.bindAsEventListener(this));Event.observe(this.element,'keydown',this.onKeyPress.bindAsEventListener(this));},show:function(){if(Element.getStyle(this.update,'display')=='none')this.options.onShow(this.element,this.update);if(!this.iefix&&(Prototype.Browser.IE)&&(Element.getStyle(this.update,'position')=='absolute')){if($(this.update.id+'_iefix')){this.iefix=$(this.update.id+'_iefix');}
else{new Insertion.After(this.update,'<iframe id="'+this.update.id+'_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" '+
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');this.iefix=$(this.update.id+'_iefix');}}
if(this.iefix)setTimeout(this.fixIEOverlapping.bind(this),50);},fixIEOverlapping:function(){Position.clone(this.update,this.iefix,{setTop:(!this.update.style.height)});this.iefix.style.zIndex=1;this.update.style.zIndex=2;Element.show(this.iefix);},hide:function(){this.stopIndicator();if(Element.getStyle(this.update,'display')!='none')this.options.onHide(this.element,this.update);if(this.iefix)Element.hide(this.iefix);},startIndicator:function(){if(this.options.indicator)Element.show(this.options.indicator);},stopIndicator:function(){if(this.options.indicator)Element.hide(this.options.indicator);},onKeyPress:function(event){if(this.active)
switch(event.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:this.selectEntry();Event.stop(event);case Event.KEY_ESC:this.hide();this.active=false;Event.stop(event);return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:this.markPrevious();this.render();Event.stop(event);return;case Event.KEY_DOWN:this.markNext();this.render();Event.stop(event);return;}
else
if(event.keyCode==Event.KEY_TAB||event.keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&event.keyCode==0))return;this.changed=true;this.hasFocus=true;if(this.observer)clearTimeout(this.observer);this.observer=setTimeout(this.onObserverEvent.bind(this),this.options.frequency*1000);},activate:function(){this.changed=false;this.hasFocus=true;this.getUpdatedChoices();},onHover:function(event){var element=Event.findElement(event,'LI');if(this.index!=element.autocompleteIndex)
{this.index=element.autocompleteIndex;this.render();}
Event.stop(event);},onClick:function(event){var element=Event.findElement(event,'LI');this.index=element.autocompleteIndex;this.selectEntry();this.hide();},onBlur:function(event){setTimeout(this.hide.bind(this),250);this.hasFocus=false;this.active=false;},render:function(){if(this.entryCount>0){for(var i=0;i<this.entryCount;i++)
this.index==i?Element.addClassName(this.getEntry(i),"selected"):Element.removeClassName(this.getEntry(i),"selected");if(this.hasFocus){this.show();this.active=true;}}else{this.active=false;this.hide();}},markPrevious:function(){if(this.index>0)this.index--
else this.index=this.entryCount-1;this.getEntry(this.index).scrollIntoView(true);},markNext:function(){if(this.index<this.entryCount-1)this.index++
else this.index=0;this.getEntry(this.index).scrollIntoView(false);},getEntry:function(index){return this.update.firstChild.childNodes[index];},getCurrentEntry:function(){return this.getEntry(this.index);},selectEntry:function(){this.active=false;this.updateElement(this.getCurrentEntry());},updateElement:function(selectedElement){if(this.options.updateElement){this.options.updateElement(selectedElement);return;}
var value='';if(this.options.select){var nodes=$(selectedElement).select('.'+this.options.select)||[];if(nodes.length>0)value=Element.collectTextNodes(nodes[0],this.options.select);}else
value=Element.collectTextNodesIgnoreClass(selectedElement,'informal');var bounds=this.getTokenBounds();if(bounds[0]!=-1){var newValue=this.element.value.substr(0,bounds[0]);var whitespace=this.element.value.substr(bounds[0]).match(/^\s+/);if(whitespace)
newValue+=whitespace[0];this.element.value=newValue+value+this.element.value.substr(bounds[1]);}else{this.element.value=value;}
this.oldElementValue=this.element.value;this.element.focus();if(this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element,selectedElement);},updateChoices:function(choices){if(!this.changed&&this.hasFocus){this.update.innerHTML=choices;Element.cleanWhitespace(this.update);Element.cleanWhitespace(this.update.down());if(this.update.firstChild&&this.update.down().childNodes){this.entryCount=this.update.down().childNodes.length;for(var i=0;i<this.entryCount;i++){var entry=this.getEntry(i);entry.autocompleteIndex=i;this.addObservers(entry);}}else{this.entryCount=0;}
this.stopIndicator();this.index=0;if(this.entryCount==1&&this.options.autoSelect){this.selectEntry();this.hide();}else{this.render();}}},addObservers:function(element){Event.observe(element,"mouseover",this.onHover.bindAsEventListener(this));Event.observe(element,"click",this.onClick.bindAsEventListener(this));},onObserverEvent:function(){this.changed=false;this.tokenBounds=null;if(this.getToken().length>=this.options.minChars){this.getUpdatedChoices();}else{this.active=false;this.hide();}
this.oldElementValue=this.element.value;},getToken:function(){var bounds=this.getTokenBounds();return this.element.value.substring(bounds[0],bounds[1]).strip();},getTokenBounds:function(){if(null!=this.tokenBounds)return this.tokenBounds;var value=this.element.value;if(value.strip().empty())return[-1,0];var diff=arguments.callee.getFirstDifferencePos(value,this.oldElementValue);var offset=(diff==this.oldElementValue.length?1:0);var prevTokenPos=-1,nextTokenPos=value.length;var tp;for(var index=0,l=this.options.tokens.length;index<l;++index){tp=value.lastIndexOf(this.options.tokens[index],diff+offset-1);if(tp>prevTokenPos)prevTokenPos=tp;tp=value.indexOf(this.options.tokens[index],diff+offset);if(-1!=tp&&tp<nextTokenPos)nextTokenPos=tp;}
return(this.tokenBounds=[prevTokenPos+1,nextTokenPos]);}});Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos=function(newS,oldS){var boundary=Math.min(newS.length,oldS.length);for(var index=0;index<boundary;++index)
if(newS[index]!=oldS[index])
return index;return boundary;};Ajax.Autocompleter=Class.create(Autocompleter.Base,{initialize:function(element,update,url,options){this.baseInitialize(element,update,options);this.options.asynchronous=true;this.options.onComplete=this.onComplete.bind(this);this.options.defaultParams=this.options.parameters||null;this.url=url;},getUpdatedChoices:function(){this.startIndicator();var entry=encodeURIComponent(this.options.paramName)+'='+
encodeURIComponent(this.getToken());this.options.parameters=this.options.callback?this.options.callback(this.element,entry):entry;if(this.options.defaultParams)
this.options.parameters+='&'+this.options.defaultParams;new Ajax.Request(this.url,this.options);},onComplete:function(request){this.updateChoices(request.responseText);}});if(Prototype.Browser.IE&&"undefined"==typeof document.documentMode||Prototype.Browser.IE&&document.documentMode<8){Ajax.FixedAutocompleter=Class.create(Ajax.Autocompleter,{initialize:function($super,element,update,url,options){$super(element,update,url,options);this.clicked_outside=false;Event.observe(document,"click",this.onDocumentClick.bindAsEventListener(this));this.element.stopObserving("blur");this.element.observe("blur",this.onBlurOverride.bindAsEventListener(this));},onDocumentClick:function(event){if(this.element.id!=event.target.id){this.clicked_outside=true;}},onBlurOverride:function(event){var thisObject=this;var callback=function(){if(thisObject.clicked_outside){thisObject.clicked_outside=false;thisObject.onBlur(event);}
else{thisObject.element.focus();}}
setTimeout(callback,200);}});}
else{Ajax.FixedAutocompleter=Ajax.Autocompleter;}
Autocompleter.Local=Class.create(Autocompleter.Base,{initialize:function(element,update,array,options){this.baseInitialize(element,update,options);this.options.array=array;},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this));},setOptions:function(options){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,ignoreCase:true,fullSearch:false,selector:function(instance){var ret=[];var partial=[];var entry=instance.getToken();var count=0;for(var i=0;i<instance.options.array.length&&ret.length<instance.options.choices;i++){var elem=instance.options.array[i];var foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase()):elem.indexOf(entry);while(foundPos!=-1){if(foundPos==0&&elem.length!=entry.length){ret.push("<li><strong>"+elem.substr(0,entry.length)+"</strong>"+
elem.substr(entry.length)+"</li>");break;}else if(entry.length>=instance.options.partialChars&&instance.options.partialSearch&&foundPos!=-1){if(instance.options.fullSearch||/\s/.test(elem.substr(foundPos-1,1))){partial.push("<li>"+elem.substr(0,foundPos)+"<strong>"+
elem.substr(foundPos,entry.length)+"</strong>"+elem.substr(foundPos+entry.length)+"</li>");break;}}
foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase(),foundPos+1):elem.indexOf(entry,foundPos+1);}}
if(partial.length)
ret=ret.concat(partial.slice(0,instance.options.choices-ret.length))
return"<ul>"+ret.join('')+"</ul>";}},options||{});}});Field.scrollFreeActivate=function(field){setTimeout(function(){Field.activate(field);},1);}
Ajax.InPlaceEditor=Class.create({initialize:function(element,url,options){this.url=url;this.element=element=$(element);this.prepareOptions();this._controls={};arguments.callee.dealWithDeprecatedOptions(options);Object.extend(this.options,options||{});if(!this.options.formId&&this.element.id){this.options.formId=this.element.id+'-inplaceeditor';if($(this.options.formId))
this.options.formId='';}
if(this.options.externalControl)
this.options.externalControl=$(this.options.externalControl);if(!this.options.externalControl)
this.options.externalControlOnly=false;this._originalBackground=this.element.getStyle('background-color')||'transparent';this.element.title=this.options.clickToEditText;this._boundCancelHandler=this.handleFormCancellation.bind(this);this._boundComplete=(this.options.onComplete||Prototype.emptyFunction).bind(this);this._boundFailureHandler=this.handleAJAXFailure.bind(this);this._boundSubmitHandler=this.handleFormSubmission.bind(this);this._boundWrapperHandler=this.wrapUp.bind(this);this.registerListeners();},checkForEscapeOrReturn:function(e){if(!this._editing||e.ctrlKey||e.altKey||e.shiftKey)return;if(Event.KEY_ESC==e.keyCode)
this.handleFormCancellation(e);else if(Event.KEY_RETURN==e.keyCode)
this.handleFormSubmission(e);},createControl:function(mode,handler,extraClasses){var control=this.options[mode+'Control'];var text=this.options[mode+'Text'];if('button'==control){var btn=document.createElement('input');btn.type='submit';btn.value=text;btn.className='editor_'+mode+'_button';if('cancel'==mode)
btn.onclick=this._boundCancelHandler;this._form.appendChild(btn);this._controls[mode]=btn;}else if('link'==control){var link=document.createElement('a');link.href='#';link.appendChild(document.createTextNode(text));link.onclick='cancel'==mode?this._boundCancelHandler:this._boundSubmitHandler;link.className='editor_'+mode+'_link';if(extraClasses)
link.className+=' '+extraClasses;this._form.appendChild(link);this._controls[mode]=link;}},createEditField:function(){var text=(this.options.loadTextURL?this.options.loadingText:this.getText());var fld;if(1>=this.options.rows&&!/\r|\n/.test(this.getText())){fld=document.createElement('input');fld.type='text';var size=this.options.size||this.options.cols||0;if(0<size)fld.size=size;}else{fld=document.createElement('textarea');fld.rows=(1>=this.options.rows?this.options.autoRows:this.options.rows);fld.cols=this.options.cols||40;}
fld.name=this.options.paramName;fld.value=text;fld.className='editor_field';if(this.options.submitOnBlur)
fld.onblur=this._boundSubmitHandler;this._controls.editor=fld;if(this.options.loadTextURL)
this.loadExternalText();this._form.appendChild(this._controls.editor);},createForm:function(){var ipe=this;function addText(mode,condition){var text=ipe.options['text'+mode+'Controls'];if(!text||condition===false)return;ipe._form.appendChild(document.createTextNode(text));};this._form=$(document.createElement('form'));this._form.id=this.options.formId;this._form.addClassName(this.options.formClassName);this._form.onsubmit=this._boundSubmitHandler;this.createEditField();if('textarea'==this._controls.editor.tagName.toLowerCase())
this._form.appendChild(document.createElement('br'));if(this.options.onFormCustomization)
this.options.onFormCustomization(this,this._form);addText('Before',this.options.okControl||this.options.cancelControl);this.createControl('ok',this._boundSubmitHandler);addText('Between',this.options.okControl&&this.options.cancelControl);this.createControl('cancel',this._boundCancelHandler,'editor_cancel');addText('After',this.options.okControl||this.options.cancelControl);},destroy:function(){if(this._oldInnerHTML)
this.element.innerHTML=this._oldInnerHTML;this.leaveEditMode();this.unregisterListeners();},enterEditMode:function(e){if(this._saving||this._editing)return;this._editing=true;this.triggerCallback('onEnterEditMode');if(this.options.externalControl)
this.options.externalControl.hide();this.element.hide();this.createForm();this.element.parentNode.insertBefore(this._form,this.element);if(!this.options.loadTextURL)
this.postProcessEditField();if(e)Event.stop(e);},enterHover:function(e){if(this.options.hoverClassName)
this.element.addClassName(this.options.hoverClassName);if(this._saving)return;this.triggerCallback('onEnterHover');},getText:function(){return this.element.innerHTML;},handleAJAXFailure:function(transport){this.triggerCallback('onFailure',transport);if(this._oldInnerHTML){this.element.innerHTML=this._oldInnerHTML;this._oldInnerHTML=null;}},handleFormCancellation:function(e){this.wrapUp();if(e)Event.stop(e);},handleFormSubmission:function(e){var form=this._form;var value=$F(this._controls.editor);this.prepareSubmission();var params=this.options.callback(form,value)||'';if(Object.isString(params))
params=params.toQueryParams();params.editorId=this.element.id;if(this.options.htmlResponse){var options=Object.extend({evalScripts:true},this.options.ajaxOptions);Object.extend(options,{parameters:params,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Updater({success:this.element},this.url,options);}else{var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:params,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Request(this.url,options);}
if(e)Event.stop(e);},leaveEditMode:function(){this.element.removeClassName(this.options.savingClassName);this.removeForm();this.leaveHover();this.element.style.backgroundColor=this._originalBackground;this.element.show();if(this.options.externalControl)
this.options.externalControl.show();this._saving=false;this._editing=false;this._oldInnerHTML=null;this.triggerCallback('onLeaveEditMode');},leaveHover:function(e){if(this.options.hoverClassName)
this.element.removeClassName(this.options.hoverClassName);if(this._saving)return;this.triggerCallback('onLeaveHover');},loadExternalText:function(){this._form.addClassName(this.options.loadingClassName);this._controls.editor.disabled=true;var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){this._form.removeClassName(this.options.loadingClassName);var text=transport.responseText;if(this.options.stripLoadedTextTags)
text=text.stripTags();this._controls.editor.value=text;this._controls.editor.disabled=false;this.postProcessEditField();}.bind(this),onFailure:this._boundFailureHandler});new Ajax.Request(this.options.loadTextURL,options);},postProcessEditField:function(){var fpc=this.options.fieldPostCreation;if(fpc)
$(this._controls.editor)['focus'==fpc?'focus':'activate']();},prepareOptions:function(){this.options=Object.clone(Ajax.InPlaceEditor.DefaultOptions);Object.extend(this.options,Ajax.InPlaceEditor.DefaultCallbacks);[this._extraDefaultOptions].flatten().compact().each(function(defs){Object.extend(this.options,defs);}.bind(this));},prepareSubmission:function(){this._saving=true;this.removeForm();this.leaveHover();this.showSaving();},registerListeners:function(){this._listeners={};var listener;$H(Ajax.InPlaceEditor.Listeners).each(function(pair){listener=this[pair.value].bind(this);this._listeners[pair.key]=listener;if(!this.options.externalControlOnly)
this.element.observe(pair.key,listener);if(this.options.externalControl)
this.options.externalControl.observe(pair.key,listener);}.bind(this));},removeForm:function(){if(!this._form)return;this._form.remove();this._form=null;this._controls={};},showSaving:function(){this._oldInnerHTML=this.element.innerHTML;this.element.innerHTML=this.options.savingText;this.element.addClassName(this.options.savingClassName);this.element.style.backgroundColor=this._originalBackground;this.element.show();},triggerCallback:function(cbName,arg){if('function'==typeof this.options[cbName]){this.options[cbName](this,arg);}},unregisterListeners:function(){$H(this._listeners).each(function(pair){if(!this.options.externalControlOnly)
this.element.stopObserving(pair.key,pair.value);if(this.options.externalControl)
this.options.externalControl.stopObserving(pair.key,pair.value);}.bind(this));},wrapUp:function(transport){this.leaveEditMode();this._boundComplete(transport,this.element);}});Object.extend(Ajax.InPlaceEditor.prototype,{dispose:Ajax.InPlaceEditor.prototype.destroy});Ajax.InPlaceCollectionEditor=Class.create(Ajax.InPlaceEditor,{initialize:function($super,element,url,options){this._extraDefaultOptions=Ajax.InPlaceCollectionEditor.DefaultOptions;$super(element,url,options);},createEditField:function(){var list=document.createElement('select');list.name=this.options.paramName;list.size=1;this._controls.editor=list;this._collection=this.options.collection||[];if(this.options.loadCollectionURL)
this.loadCollection();else
this.checkForExternalText();this._form.appendChild(this._controls.editor);},loadCollection:function(){this._form.addClassName(this.options.loadingClassName);this.showLoadingText(this.options.loadingCollectionText);var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){var js=transport.responseText.strip();if(!/^\[.*\]$/.test(js))
throw'Server returned an invalid collection representation.';this._collection=eval(js);this.checkForExternalText();}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadCollectionURL,options);},showLoadingText:function(text){this._controls.editor.disabled=true;var tempOption=this._controls.editor.firstChild;if(!tempOption){tempOption=document.createElement('option');tempOption.value='';this._controls.editor.appendChild(tempOption);tempOption.selected=true;}
tempOption.update((text||'').stripScripts().stripTags());},checkForExternalText:function(){this._text=this.getText();if(this.options.loadTextURL)
this.loadExternalText();else
this.buildOptionList();},loadExternalText:function(){this.showLoadingText(this.options.loadingText);var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){this._text=transport.responseText.strip();this.buildOptionList();}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadTextURL,options);},buildOptionList:function(){this._form.removeClassName(this.options.loadingClassName);this._collection=this._collection.map(function(entry){return 2===entry.length?entry:[entry,entry].flatten();});var marker=('value'in this.options)?this.options.value:this._text;var textFound=this._collection.any(function(entry){return entry[0]==marker;}.bind(this));this._controls.editor.update('');var option;this._collection.each(function(entry,index){option=document.createElement('option');option.value=entry[0];option.selected=textFound?entry[0]==marker:0==index;option.appendChild(document.createTextNode(entry[1]));this._controls.editor.appendChild(option);}.bind(this));this._controls.editor.disabled=false;Field.scrollFreeActivate(this._controls.editor);}});Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions=function(options){if(!options)return;function fallback(name,expr){if(name in options||expr===undefined)return;options[name]=expr;};fallback('cancelControl',(options.cancelLink?'link':(options.cancelButton?'button':options.cancelLink==options.cancelButton==false?false:undefined)));fallback('okControl',(options.okLink?'link':(options.okButton?'button':options.okLink==options.okButton==false?false:undefined)));fallback('highlightColor',options.highlightcolor);fallback('highlightEndColor',options.highlightendcolor);};Object.extend(Ajax.InPlaceEditor,{DefaultOptions:{ajaxOptions:{},autoRows:3,cancelControl:'link',cancelText:'cancel',clickToEditText:'Click to edit',externalControl:null,externalControlOnly:false,fieldPostCreation:'activate',formClassName:'inplaceeditor-form',formId:null,highlightColor:'#ffff99',highlightEndColor:'#ffffff',hoverClassName:'',htmlResponse:true,loadingClassName:'inplaceeditor-loading',loadingText:'Loading...',okControl:'button',okText:'ok',paramName:'value',rows:1,savingClassName:'inplaceeditor-saving',savingText:'Saving...',size:0,stripLoadedTextTags:false,submitOnBlur:false,textAfterControls:'',textBeforeControls:'',textBetweenControls:''},DefaultCallbacks:{callback:function(form){return Form.serialize(form);},onComplete:function(transport,element){new Effect.Highlight(element,{startcolor:this.options.highlightColor,keepBackgroundImage:true});},onEnterEditMode:null,onEnterHover:function(ipe){ipe.element.style.backgroundColor=ipe.options.highlightColor;if(ipe._effect)
ipe._effect.cancel();},onFailure:function(transport,ipe){alert('Error communication with the server: '+transport.responseText.stripTags());},onFormCustomization:null,onLeaveEditMode:null,onLeaveHover:function(ipe){ipe._effect=new Effect.Highlight(ipe.element,{startcolor:ipe.options.highlightColor,endcolor:ipe.options.highlightEndColor,restorecolor:ipe._originalBackground,keepBackgroundImage:true});}},Listeners:{click:'enterEditMode',keydown:'checkForEscapeOrReturn',mouseover:'enterHover',mouseout:'leaveHover'}});Ajax.InPlaceCollectionEditor.DefaultOptions={loadingCollectionText:'Loading options...'};Form.Element.DelayedObserver=Class.create({initialize:function(element,delay,callback){this.delay=delay||0.5;this.element=$(element);this.callback=callback;this.timer=null;this.lastValue=$F(this.element);Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));},delayedListener:function(event){if(this.lastValue==$F(this.element))return;if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(this.onTimerEvent.bind(this),this.delay*1000);this.lastValue=$F(this.element);},onTimerEvent:function(){this.timer=null;this.callback(this.element,$F(this.element));}});if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");var Droppables={drops:[],remove:function(element){this.drops=this.drops.reject(function(d){return d.element==$(element)});},add:function(element){element=$(element);var options=Object.extend({greedy:true,hoverclass:null,tree:false,scrollid:null},arguments[1]||{});if(options.containment){options._containers=[];var containment=options.containment;if(Object.isArray(containment)){containment.each(function(c){options._containers.push($(c))});}else{options._containers.push($(containment));}}
if(options.accept)options.accept=[options.accept].flatten();Element.makePositioned(element);options.element=element;this.drops.push(options);},findDeepestChild:function(drops){deepest=drops[0];for(i=1;i<drops.length;++i)
if(Element.isParent(drops[i].element,deepest.element))
deepest=drops[i];return deepest;},isContained:function(element,drop){var containmentNode;if(drop.tree){containmentNode=element.treeNode;}else{containmentNode=element.parentNode;}
return drop._containers.detect(function(c){return containmentNode==c});},isAffected:function(point,element,drop){if(drop.scrollid){Position.includeScrollOffsets=true;scrolling_element=$(drop.scrollid)
var container_off=Element.cumulativeOffset(scrolling_element);if(point[1]<container_off[1]||point[1]>Element.getHeight(scrolling_element)+container_off[1])
{return false;}
else if(point[0]<container_off[0]||point[0]>Element.getWidth(scrolling_element)+container_off[0])
{return false;}}
return((drop.element!=element)&&((!drop._containers)||this.isContained(element,drop))&&((!drop.accept)||(Element.classNames(element).detect(function(v){return drop.accept.include(v)})))&&Position.within(drop.element,point[0],point[1]));},deactivate:function(drop){if(drop.hoverclass)
Element.removeClassName(drop.element,drop.hoverclass);this.last_active=null;},activate:function(drop){if(drop.hoverclass)
Element.addClassName(drop.element,drop.hoverclass);this.last_active=drop;},show:function(point,element){if(!this.drops.length)return;var drop,affected=[];this.drops.each(function(drop){if(Droppables.isAffected(point,element,drop))
affected.push(drop);});if(affected.length>0)
drop=Droppables.findDeepestChild(affected);if(this.last_active&&this.last_active!=drop)this.deactivate(this.last_active);if(drop){Position.within(drop.element,point[0],point[1]);if(drop.onHover)
drop.onHover(element,drop.element,Position.overlap(drop.overlap,drop.element));if(drop!=this.last_active)Droppables.activate(drop);}},fire:function(event,element){if(!this.last_active)return;Position.prepare();if(this.isAffected([Event.pointerX(event),Event.pointerY(event)],element,this.last_active))
if(this.last_active.onDrop){this.last_active.onDrop(element,this.last_active.element,event);return true;}},reset:function(){if(this.last_active)
this.deactivate(this.last_active);}}
var Draggables={drags:[],observers:[],register:function(draggable){if(this.drags.length==0){this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.updateDrag.bindAsEventListener(this);this.eventKeypress=this.keyPress.bindAsEventListener(this);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);Event.observe(document,"keypress",this.eventKeypress);}
this.drags.push(draggable);},unregister:function(draggable){this.drags=this.drags.reject(function(d){return d==draggable});if(this.drags.length==0){Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);Event.stopObserving(document,"keypress",this.eventKeypress);}},activate:function(draggable){if(draggable.options.delay){this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=draggable;}.bind(this),draggable.options.delay);}else{window.focus();this.activeDraggable=draggable;}},deactivate:function(){this.activeDraggable=null;},updateDrag:function(event){if(!this.activeDraggable)return;var pointer=[Event.pointerX(event),Event.pointerY(event)];if(this._lastPointer&&(this._lastPointer.inspect()==pointer.inspect()))return;this._lastPointer=pointer;this.activeDraggable.updateDrag(event,pointer);},endDrag:function(event){if(this._timeout){clearTimeout(this._timeout);this._timeout=null;}
if(!this.activeDraggable)return;this._lastPointer=null;this.activeDraggable.endDrag(event);this.activeDraggable=null;},keyPress:function(event){if(this.activeDraggable)
this.activeDraggable.keyPress(event);},addObserver:function(observer){this.observers.push(observer);this._cacheObserverCallbacks();},removeObserver:function(element){this.observers=this.observers.reject(function(o){return o.element==element});this._cacheObserverCallbacks();},notify:function(eventName,draggable,event){if(this[eventName+'Count']>0)
this.observers.each(function(o){if(o[eventName])o[eventName](eventName,draggable,event);});if(draggable.options[eventName])draggable.options[eventName](draggable,event);},_cacheObserverCallbacks:function(){['onStart','onEnd','onDrag'].each(function(eventName){Draggables[eventName+'Count']=Draggables.observers.select(function(o){return o[eventName];}).length;});}}
var Draggable=Class.create({initialize:function(element){var defaults={handle:false,reverteffect:function(element,top_offset,left_offset){var dur=Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:dur,queue:{scope:'_draggable',position:'end'}});},endeffect:function(element){var toOpacity=Object.isNumber(element._opacity)?element._opacity:1.0;new Effect.Opacity(element,{duration:0.2,from:0.7,to:toOpacity,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[element]=false}});},zindex:1000,revert:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults,{starteffect:function(element){element._opacity=Element.getOpacity(element);Draggable._dragging[element]=true;new Effect.Opacity(element,{duration:0.2,from:element._opacity,to:0.7});}});var options=Object.extend(defaults,arguments[1]||{});this.element=$(element);if(options.handle&&Object.isString(options.handle))
this.handle=this.element.down('.'+options.handle,0);if(!this.handle)this.handle=$(options.handle);if(!this.handle)this.handle=this.element;if(options.scroll&&!options.scroll.scrollTo&&!options.scroll.outerHTML){options.scroll=$(options.scroll);this._isScrollChild=Element.childOf(this.element,options.scroll);}
Element.makePositioned(this.element);this.options=options;this.dragging=false;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this);},destroy:function(){Event.stopObserving(this.handle,"mousedown",this.eventMouseDown);Draggables.unregister(this);},currentDelta:function(){return([parseInt(Element.getStyle(this.element,'left')||'0'),parseInt(Element.getStyle(this.element,'top')||'0')]);},initDrag:function(event){if(!Object.isUndefined(Draggable._dragging[this.element])&&Draggable._dragging[this.element])return;if(Event.isLeftClick(event)){var src=Event.element(event);if((tag_name=src.tagName.toUpperCase())&&(tag_name=='INPUT'||tag_name=='SELECT'||tag_name=='OPTION'||tag_name=='BUTTON'||tag_name=='TEXTAREA'))return;var pointer=[Event.pointerX(event),Event.pointerY(event)];var pos=Position.cumulativeOffset(this.element);this.offset=[0,1].map(function(i){return(pointer[i]-pos[i])});Draggables.activate(this);Event.stop(event);}},startDrag:function(event){this.dragging=true;if(!this.delta)
this.delta=this.currentDelta();if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,'z-index')||0);this.element.style.zIndex=this.options.zindex;}
if(this.options.ghosting){this._clone=this.element.cloneNode(true);this.element._originallyAbsolute=(this.element.getStyle('position')=='absolute');if(!this.element._originallyAbsolute)
Position.absolutize(this.element);this.element.parentNode.insertBefore(this._clone,this.element);}
if(this.options.scroll){if(this.options.scroll==window){var where=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=where.left;this.originalScrollTop=where.top;}else{this.originalScrollLeft=this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop;}}
Draggables.notify('onStart',this,event);if(this.options.starteffect)this.options.starteffect(this.element);},updateDrag:function(event,pointer){if(!this.dragging)this.startDrag(event);if(!this.options.quiet){Position.prepare();Droppables.show(pointer,this.element);}
Draggables.notify('onDrag',this,event);this.draw(pointer);if(this.options.change)this.options.change(this);if(this.options.scroll){this.stopScrolling();var p;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){p=[left,top,left+width,top+height];}}else{p=Position.page(this.options.scroll);p[0]+=this.options.scroll.scrollLeft+Position.deltaX;p[1]+=this.options.scroll.scrollTop+Position.deltaY;p.push(p[0]+this.options.scroll.offsetWidth);p.push(p[1]+this.options.scroll.offsetHeight);}
var speed=[0,0];if(pointer[0]<(p[0]+this.options.scrollSensitivity))speed[0]=pointer[0]-(p[0]+this.options.scrollSensitivity);if(pointer[1]<(p[1]+this.options.scrollSensitivity))speed[1]=pointer[1]-(p[1]+this.options.scrollSensitivity);if(pointer[0]>(p[2]-this.options.scrollSensitivity))speed[0]=pointer[0]-(p[2]-this.options.scrollSensitivity);if(pointer[1]>(p[3]-this.options.scrollSensitivity))speed[1]=pointer[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(speed);}
if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);},finishDrag:function(event,success){this.dragging=false;if(this.options.quiet){Position.prepare();var pointer=[Event.pointerX(event),Event.pointerY(event)];Droppables.show(pointer,this.element);}
if(this.options.ghosting){if(!this.element._originallyAbsolute)
Position.relativize(this.element);delete this.element._originallyAbsolute;Element.remove(this._clone);this._clone=null;}
var dropped=false;if(success){dropped=Droppables.fire(event,this.element);if(!dropped)dropped=false;}
if(dropped&&this.options.onDropped)this.options.onDropped(this.element);Draggables.notify('onEnd',this,event);var revert=this.options.revert;if(revert&&Object.isFunction(revert))revert=revert(this.element);var d=this.currentDelta();if(revert&&this.options.reverteffect){if(dropped==0||revert!='failure')
this.options.reverteffect(this.element,d[1]-this.delta[1],d[0]-this.delta[0]);}else{this.delta=d;}
if(this.options.zindex)
this.element.style.zIndex=this.originalZ;if(this.options.endeffect)
this.options.endeffect(this.element);Draggables.deactivate(this);Droppables.reset();},keyPress:function(event){if(event.keyCode!=Event.KEY_ESC)return;this.finishDrag(event,false);Event.stop(event);},endDrag:function(event){if(!this.dragging)return;this.stopScrolling();this.finishDrag(event,true);Event.stop(event);},draw:function(point){var pos=Position.cumulativeOffset(this.element);if(this.options.ghosting){var r=Position.realOffset(this.element);pos[0]+=r[0]-Position.deltaX;pos[1]+=r[1]-Position.deltaY;}
var d=this.currentDelta();pos[0]-=d[0];pos[1]-=d[1];if(this.options.scroll&&(this.options.scroll!=window&&this._isScrollChild)){pos[0]-=this.options.scroll.scrollLeft-this.originalScrollLeft;pos[1]-=this.options.scroll.scrollTop-this.originalScrollTop;}
var p=[0,1].map(function(i){return(point[i]-pos[i]-this.offset[i])}.bind(this));if(this.options.snap){if(Object.isFunction(this.options.snap)){p=this.options.snap(p[0],p[1],this);}else{if(Object.isArray(this.options.snap)){p=p.map(function(v,i){return(v/this.options.snap[i]).round()*this.options.snap[i]}.bind(this))}else{p=p.map(function(v){return(v/this.options.snap).round()*this.options.snap}.bind(this))}}}
var style=this.element.style;if((!this.options.constraint)||(this.options.constraint=='horizontal'))
style.left=p[0]+"px";if((!this.options.constraint)||(this.options.constraint=='vertical'))
style.top=p[1]+"px";if(style.visibility=="hidden")style.visibility="";},stopScrolling:function(){if(this.scrollInterval){clearInterval(this.scrollInterval);this.scrollInterval=null;Draggables._lastScrollPointer=null;}},startScrolling:function(speed){if(!(speed[0]||speed[1]))return;this.scrollSpeed=[speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];this.lastScrolled=new Date();this.scrollInterval=setInterval(this.scroll.bind(this),10);},scroll:function(){var current=new Date();var delta=current-this.lastScrolled;this.lastScrolled=current;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){if(this.scrollSpeed[0]||this.scrollSpeed[1]){var d=delta/1000;this.options.scroll.scrollTo(left+d*this.scrollSpeed[0],top+d*this.scrollSpeed[1]);}}}else{this.options.scroll.scrollLeft+=this.scrollSpeed[0]*delta/1000;this.options.scroll.scrollTop+=this.scrollSpeed[1]*delta/1000;}
Position.prepare();Droppables.show(Draggables._lastPointer,this.element);Draggables.notify('onDrag',this);if(this._isScrollChild){Draggables._lastScrollPointer=Draggables._lastScrollPointer||$A(Draggables._lastPointer);Draggables._lastScrollPointer[0]+=this.scrollSpeed[0]*delta/1000;Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*delta/1000;if(Draggables._lastScrollPointer[0]<0)
Draggables._lastScrollPointer[0]=0;if(Draggables._lastScrollPointer[1]<0)
Draggables._lastScrollPointer[1]=0;this.draw(Draggables._lastScrollPointer);}
if(this.options.change)this.options.change(this);},_getWindowScroll:function(w){var T,L,W,H;with(w.document){if(w.document.documentElement&&documentElement.scrollTop){T=documentElement.scrollTop;L=documentElement.scrollLeft;}else if(w.document.body){T=body.scrollTop;L=body.scrollLeft;}
if(w.innerWidth){W=w.innerWidth;H=w.innerHeight;}else if(w.document.documentElement&&documentElement.clientWidth){W=documentElement.clientWidth;H=documentElement.clientHeight;}else{W=body.offsetWidth;H=body.offsetHeight}}
return{top:T,left:L,width:W,height:H};}});Draggable._dragging={};var SortableObserver=Class.create({initialize:function(element,observer){this.element=$(element);this.observer=observer;this.lastValue=Sortable.serialize(this.element);},onStart:function(){this.lastValue=Sortable.serialize(this.element);},onEnd:function(){Sortable.unmark();if(this.lastValue!=Sortable.serialize(this.element))
this.observer(this.element)}});var Sortable={SERIALIZE_RULE:/^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,sortables:{},_findRootElement:function(element){while(element.tagName.toUpperCase()!="BODY"){if(element.id&&Sortable.sortables[element.id])return element;element=element.parentNode;}},options:function(element){element=Sortable._findRootElement($(element));if(!element)return;return Sortable.sortables[element.id];},destroy:function(element){var s=Sortable.options(element);if(s){Draggables.removeObserver(s.element);s.droppables.each(function(d){Droppables.remove(d)});s.draggables.invoke('destroy');delete Sortable.sortables[s.element.id];}},create:function(element){element=$(element);var options=Object.extend({element:element,tag:'li',dropOnEmpty:false,tree:false,treeTag:'ul',overlap:'vertical',constraint:'vertical',containment:element,handle:false,only:false,delay:0,hoverclass:null,ghosting:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,format:this.SERIALIZE_RULE,elements:false,handles:false,onChange:Prototype.emptyFunction,onUpdate:Prototype.emptyFunction},arguments[1]||{});this.destroy(element);var options_for_draggable={revert:true,quiet:options.quiet,scroll:options.scroll,scrollSpeed:options.scrollSpeed,scrollSensitivity:options.scrollSensitivity,delay:options.delay,ghosting:options.ghosting,constraint:options.constraint,handle:options.handle};if(options.starteffect)
options_for_draggable.starteffect=options.starteffect;if(options.reverteffect)
options_for_draggable.reverteffect=options.reverteffect;else
if(options.ghosting)options_for_draggable.reverteffect=function(element){element.style.top=0;element.style.left=0;};if(options.endeffect)
options_for_draggable.endeffect=options.endeffect;if(options.zindex)
options_for_draggable.zindex=options.zindex;var options_for_droppable={overlap:options.overlap,containment:options.containment,tree:options.tree,hoverclass:options.hoverclass,onHover:Sortable.onHover}
var options_for_tree={onHover:Sortable.onEmptyHover,overlap:options.overlap,containment:options.containment,hoverclass:options.hoverclass}
Element.cleanWhitespace(element);options.draggables=[];options.droppables=[];if(options.dropOnEmpty||options.tree){Droppables.add(element,options_for_tree);options.droppables.push(element);}
(options.elements||this.findElements(element,options)||[]).each(function(e,i){var handle=options.handles?$(options.handles[i]):(options.handle?$(e).select('.'+options.handle)[0]:e);options.draggables.push(new Draggable(e,Object.extend(options_for_draggable,{handle:handle})));Droppables.add(e,options_for_droppable);if(options.tree)e.treeNode=element;options.droppables.push(e);});if(options.tree){(Sortable.findTreeElements(element,options)||[]).each(function(e){Droppables.add(e,options_for_tree);e.treeNode=element;options.droppables.push(e);});}
this.sortables[element.id]=options;Draggables.addObserver(new SortableObserver(element,options.onUpdate));},findElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.tag);},findTreeElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.treeTag);},onHover:function(element,dropon,overlap){if(Element.isParent(dropon,element))return;if(overlap>.33&&overlap<.66&&Sortable.options(dropon).tree){return;}else if(overlap>0.5){Sortable.mark(dropon,'before');if(dropon.previousSibling!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,dropon);if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);Sortable.options(dropon.parentNode).onChange(element);}}else{Sortable.mark(dropon,'after');var nextElement=dropon.nextSibling||null;if(nextElement!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,nextElement);if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);Sortable.options(dropon.parentNode).onChange(element);}}},onEmptyHover:function(element,dropon,overlap){var oldParentNode=element.parentNode;var droponOptions=Sortable.options(dropon);if(!Element.isParent(dropon,element)){var index;var children=Sortable.findElements(dropon,{tag:droponOptions.tag,only:droponOptions.only});var child=null;if(children){var offset=Element.offsetSize(dropon,droponOptions.overlap)*(1.0-overlap);for(index=0;index<children.length;index+=1){if(offset-Element.offsetSize(children[index],droponOptions.overlap)>=0){offset-=Element.offsetSize(children[index],droponOptions.overlap);}else if(offset-(Element.offsetSize(children[index],droponOptions.overlap)/2)>=0){child=index+1<children.length?children[index+1]:null;break;}else{child=children[index];break;}}}
dropon.insertBefore(element,child);Sortable.options(oldParentNode).onChange(element);droponOptions.onChange(element);}},unmark:function(){if(Sortable._marker)Sortable._marker.hide();},mark:function(dropon,position){var sortable=Sortable.options(dropon.parentNode);if(sortable&&!sortable.ghosting)return;if(!Sortable._marker){Sortable._marker=($('dropmarker')||Element.extend(document.createElement('DIV'))).hide().addClassName('dropmarker').setStyle({position:'absolute'});document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);}
var offsets=Position.cumulativeOffset(dropon);Sortable._marker.setStyle({left:offsets[0]+'px',top:offsets[1]+'px'});if(position=='after')
if(sortable.overlap=='horizontal')
Sortable._marker.setStyle({left:(offsets[0]+dropon.clientWidth)+'px'});else
Sortable._marker.setStyle({top:(offsets[1]+dropon.clientHeight)+'px'});Sortable._marker.show();},_tree:function(element,options,parent){var children=Sortable.findElements(element,options)||[];for(var i=0;i<children.length;++i){var match=children[i].id.match(options.format);if(!match)continue;var child={id:encodeURIComponent(match?match[1]:null),element:element,parent:parent,children:[],position:parent.children.length,container:$(children[i]).down(options.treeTag)}
if(child.container)
this._tree(child.container,options,child)
parent.children.push(child);}
return parent;},tree:function(element){element=$(element);var sortableOptions=this.options(element);var options=Object.extend({tag:sortableOptions.tag,treeTag:sortableOptions.treeTag,only:sortableOptions.only,name:element.id,format:sortableOptions.format},arguments[1]||{});var root={id:null,parent:null,children:[],container:element,position:0}
return Sortable._tree(element,options,root);},_constructIndex:function(node){var index='';do{if(node.id)index='['+node.position+']'+index;}while((node=node.parent)!=null);return index;},sequence:function(element){element=$(element);var options=Object.extend(this.options(element),arguments[1]||{});return $(this.findElements(element,options)||[]).map(function(item){return item.id.match(options.format)?item.id.match(options.format)[1]:'';});},setSequence:function(element,new_sequence){element=$(element);var options=Object.extend(this.options(element),arguments[2]||{});var nodeMap={};this.findElements(element,options).each(function(n){if(n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]]=[n,n.parentNode];n.parentNode.removeChild(n);});new_sequence.each(function(ident){var n=nodeMap[ident];if(n){n[1].appendChild(n[0]);delete nodeMap[ident];}});},serialize:function(element){element=$(element);var options=Object.extend(Sortable.options(element),arguments[1]||{});var name=encodeURIComponent((arguments[1]&&arguments[1].name)?arguments[1].name:element.id);if(options.tree){return Sortable.tree(element,arguments[1]).children.map(function(item){return[name+Sortable._constructIndex(item)+"[id]="+
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));}).flatten().join('&');}else{return Sortable.sequence(element,arguments[1]).map(function(item){return name+"[]="+encodeURIComponent(item);}).join('&');}}}
Element.isParent=function(child,element){if(!child.parentNode||child==element)return false;if(child.parentNode==element)return true;return Element.isParent(child.parentNode,element);}
Element.findChildren=function(element,only,recursive,tagName){if(!element.hasChildNodes())return null;tagName=tagName.toUpperCase();if(only)only=[only].flatten();var elements=[];$A(element.childNodes).each(function(e){if(e.tagName&&e.tagName.toUpperCase()==tagName&&(!only||(Element.classNames(e).detect(function(v){return only.include(v)}))))
elements.push(e);if(recursive){var grandchildren=Element.findChildren(e,only,recursive,tagName);if(grandchildren)elements.push(grandchildren);}});return(elements.length>0?elements.flatten():[]);}
Element.offsetSize=function(element,type){return element['offset'+((type=='vertical'||type=='height')?'Height':'Width')];}
if(!Control)var Control={};Control.Slider=Class.create({initialize:function(handle,track,options){var slider=this;if(Object.isArray(handle)){this.handles=handle.collect(function(e){return $(e)});}else{this.handles=[$(handle)];}
this.track=$(track);this.options=options||{};this.axis=this.options.axis||'horizontal';this.increment=this.options.increment||1;this.step=parseInt(this.options.step||'1');this.range=this.options.range||$R(0,1);this.value=0;this.values=this.handles.map(function(){return 0});this.spans=this.options.spans?this.options.spans.map(function(s){return $(s)}):false;this.options.startSpan=$(this.options.startSpan||null);this.options.endSpan=$(this.options.endSpan||null);this.restricted=this.options.restricted||false;this.maximum=this.options.maximum||this.range.end;this.minimum=this.options.minimum||this.range.start;this.alignX=parseInt(this.options.alignX||'0');this.alignY=parseInt(this.options.alignY||'0');this.trackLength=this.maximumOffset()-this.minimumOffset();this.handleLength=this.isVertical()?(this.handles[0].offsetHeight!=0?this.handles[0].offsetHeight:this.handles[0].style.height.replace(/px$/,"")):(this.handles[0].offsetWidth!=0?this.handles[0].offsetWidth:this.handles[0].style.width.replace(/px$/,""));this.active=false;this.dragging=false;this.disabled=false;if(this.options.disabled)this.setDisabled();this.allowedValues=this.options.values?this.options.values.sortBy(Prototype.K):false;if(this.allowedValues){this.minimum=this.allowedValues.min();this.maximum=this.allowedValues.max();}
this.eventMouseDown=this.startDrag.bindAsEventListener(this);this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);this.handles.each(function(h,i){i=slider.handles.length-1-i;slider.setValue(parseFloat((Object.isArray(slider.options.sliderValue)?slider.options.sliderValue[i]:slider.options.sliderValue)||slider.range.start),i);h.makePositioned().observe("mousedown",slider.eventMouseDown);});this.track.observe("mousedown",this.eventMouseDown);document.observe("mouseup",this.eventMouseUp);document.observe("mousemove",this.eventMouseMove);this.initialized=true;},dispose:function(){var slider=this;Event.stopObserving(this.track,"mousedown",this.eventMouseDown);Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);this.handles.each(function(h){Event.stopObserving(h,"mousedown",slider.eventMouseDown);});},setDisabled:function(){this.disabled=true;},setEnabled:function(){this.disabled=false;},getNearestValue:function(value){if(this.allowedValues){if(value>=this.allowedValues.max())return(this.allowedValues.max());if(value<=this.allowedValues.min())return(this.allowedValues.min());var offset=Math.abs(this.allowedValues[0]-value);var newValue=this.allowedValues[0];this.allowedValues.each(function(v){var currentOffset=Math.abs(v-value);if(currentOffset<=offset){newValue=v;offset=currentOffset;}});return newValue;}
if(value>this.range.end)return this.range.end;if(value<this.range.start)return this.range.start;return value;},setValue:function(sliderValue,handleIdx){if(!this.active){this.activeHandleIdx=handleIdx||0;this.activeHandle=this.handles[this.activeHandleIdx];this.updateStyles();}
handleIdx=handleIdx||this.activeHandleIdx||0;if(this.initialized&&this.restricted){if((handleIdx>0)&&(sliderValue<this.values[handleIdx-1]))
sliderValue=this.values[handleIdx-1];if((handleIdx<(this.handles.length-1))&&(sliderValue>this.values[handleIdx+1]))
sliderValue=this.values[handleIdx+1];}
sliderValue=this.getNearestValue(sliderValue);this.values[handleIdx]=sliderValue;this.value=this.values[0];this.handles[handleIdx].style[this.isVertical()?'top':'left']=this.translateToPx(sliderValue);this.drawSpans();if(!this.dragging||!this.event)this.updateFinished();},setValueBy:function(delta,handleIdx){this.setValue(this.values[handleIdx||this.activeHandleIdx||0]+delta,handleIdx||this.activeHandleIdx||0);},translateToPx:function(value){return Math.round(((this.trackLength-this.handleLength)/(this.range.end-this.range.start))*(value-this.range.start))+"px";},translateToValue:function(offset){return((offset/(this.trackLength-this.handleLength)*(this.range.end-this.range.start))+this.range.start);},getRange:function(range){var v=this.values.sortBy(Prototype.K);range=range||0;return $R(v[range],v[range+1]);},minimumOffset:function(){return(this.isVertical()?this.alignY:this.alignX);},maximumOffset:function(){return(this.isVertical()?(this.track.offsetHeight!=0?this.track.offsetHeight:this.track.style.height.replace(/px$/,""))-this.alignY:(this.track.offsetWidth!=0?this.track.offsetWidth:this.track.style.width.replace(/px$/,""))-this.alignX);},isVertical:function(){return(this.axis=='vertical');},drawSpans:function(){var slider=this;if(this.spans)
$R(0,this.spans.length-1).each(function(r){slider.setSpan(slider.spans[r],slider.getRange(r))});if(this.options.startSpan)
this.setSpan(this.options.startSpan,$R(0,this.values.length>1?this.getRange(0).min():this.value));if(this.options.endSpan)
this.setSpan(this.options.endSpan,$R(this.values.length>1?this.getRange(this.spans.length-1).max():this.value,this.maximum));},setSpan:function(span,range){if(this.isVertical()){span.style.top=this.translateToPx(range.start);span.style.height=this.translateToPx(range.end-range.start+this.range.start);}else{span.style.left=this.translateToPx(range.start);span.style.width=this.translateToPx(range.end-range.start+this.range.start);}},updateStyles:function(){this.handles.each(function(h){Element.removeClassName(h,'selected')});Element.addClassName(this.activeHandle,'selected');},startDrag:function(event){if(Event.isLeftClick(event)){if(!this.disabled){this.active=true;var handle=Event.element(event);var pointer=[Event.pointerX(event),Event.pointerY(event)];var track=handle;if(track==this.track){var offsets=Position.cumulativeOffset(this.track);this.event=event;this.setValue(this.translateToValue((this.isVertical()?pointer[1]-offsets[1]:pointer[0]-offsets[0])-(this.handleLength/2)));var offsets=Position.cumulativeOffset(this.activeHandle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);}else{while((this.handles.indexOf(handle)==-1)&&handle.parentNode)
handle=handle.parentNode;if(this.handles.indexOf(handle)!=-1){this.activeHandle=handle;this.activeHandleIdx=this.handles.indexOf(this.activeHandle);this.updateStyles();var offsets=Position.cumulativeOffset(this.activeHandle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);}}}
Event.stop(event);}},update:function(event){if(this.active){if(!this.dragging)this.dragging=true;this.draw(event);if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);}},draw:function(event){var pointer=[Event.pointerX(event),Event.pointerY(event)];var offsets=Position.cumulativeOffset(this.track);pointer[0]-=this.offsetX+offsets[0];pointer[1]-=this.offsetY+offsets[1];this.event=event;this.setValue(this.translateToValue(this.isVertical()?pointer[1]:pointer[0]));if(this.initialized&&this.options.onSlide)
this.options.onSlide(this.values.length>1?this.values:this.value,this);},endDrag:function(event){if(this.active&&this.dragging){this.finishDrag(event,true);Event.stop(event);}
this.active=false;this.dragging=false;},finishDrag:function(event,success){this.active=false;this.dragging=false;this.updateFinished();},updateFinished:function(){if(this.initialized&&this.options.onChange)
this.options.onChange(this.values.length>1?this.values:this.value,this);this.event=null;}});Sound={tracks:{},_enabled:true,template:new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),enable:function(){Sound._enabled=true;},disable:function(){Sound._enabled=false;},play:function(url){if(!Sound._enabled)return;var options=Object.extend({track:'global',url:url,replace:false},arguments[1]||{});if(options.replace&&this.tracks[options.track]){$R(0,this.tracks[options.track].id).each(function(id){var sound=$('sound_'+options.track+'_'+id);sound.Stop&&sound.Stop();sound.remove();})
this.tracks[options.track]=null;}
if(!this.tracks[options.track])
this.tracks[options.track]={id:0}
else
this.tracks[options.track].id++;options.id=this.tracks[options.track].id;$$('body')[0].insert(Prototype.Browser.IE?new Element('bgsound',{id:'sound_'+options.track+'_'+options.id,src:options.url,loop:1,autostart:true}):Sound.template.evaluate(options));}};if(Prototype.Browser.Gecko&&navigator.userAgent.indexOf("Win")>0){if(navigator.plugins&&$A(navigator.plugins).detect(function(p){return p.name.indexOf('QuickTime')!=-1}))
Sound.template=new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>')
else
Sound.play=function(){}}
Event.simulateMouse=function(element,eventName){var options=Object.extend({pointerX:0,pointerY:0,buttons:0,ctrlKey:false,altKey:false,shiftKey:false,metaKey:false},arguments[2]||{});var oEvent=document.createEvent("MouseEvents");oEvent.initMouseEvent(eventName,true,true,document.defaultView,options.buttons,options.pointerX,options.pointerY,options.pointerX,options.pointerY,options.ctrlKey,options.altKey,options.shiftKey,options.metaKey,0,$(element));if(this.mark)Element.remove(this.mark);this.mark=document.createElement('div');this.mark.appendChild(document.createTextNode(" "));document.body.appendChild(this.mark);this.mark.style.position='absolute';this.mark.style.top=options.pointerY+"px";this.mark.style.left=options.pointerX+"px";this.mark.style.width="5px";this.mark.style.height="5px;";this.mark.style.borderTop="1px solid red;"
this.mark.style.borderLeft="1px solid red;"
if(this.step)
alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));$(element).dispatchEvent(oEvent);};Event.simulateKey=function(element,eventName){var options=Object.extend({ctrlKey:false,altKey:false,shiftKey:false,metaKey:false,keyCode:0,charCode:0},arguments[2]||{});var oEvent=document.createEvent("KeyEvents");oEvent.initKeyEvent(eventName,true,true,window,options.ctrlKey,options.altKey,options.shiftKey,options.metaKey,options.keyCode,options.charCode);$(element).dispatchEvent(oEvent);};Event.simulateKeys=function(element,command){for(var i=0;i<command.length;i++){Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});}};var Test={}
Test.Unit={};Test.Unit.inspect=Object.inspect;Test.Unit.Logger=Class.create();Test.Unit.Logger.prototype={initialize:function(log){this.log=$(log);if(this.log){this._createLogTable();}},start:function(testName){if(!this.log)return;this.testName=testName;this.lastLogLine=document.createElement('tr');this.statusCell=document.createElement('td');this.nameCell=document.createElement('td');this.nameCell.className="nameCell";this.nameCell.appendChild(document.createTextNode(testName));this.messageCell=document.createElement('td');this.lastLogLine.appendChild(this.statusCell);this.lastLogLine.appendChild(this.nameCell);this.lastLogLine.appendChild(this.messageCell);this.loglines.appendChild(this.lastLogLine);},finish:function(status,summary){if(!this.log)return;this.lastLogLine.className=status;this.statusCell.innerHTML=status;this.messageCell.innerHTML=this._toHTML(summary);this.addLinksToResults();},message:function(message){if(!this.log)return;this.messageCell.innerHTML=this._toHTML(message);},summary:function(summary){if(!this.log)return;this.logsummary.innerHTML=this._toHTML(summary);},_createLogTable:function(){this.log.innerHTML='<div id="logsummary"></div>'+
'<table id="logtable">'+
'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>'+
'<tbody id="loglines"></tbody>'+
'</table>';this.logsummary=$('logsummary')
this.loglines=$('loglines');},_toHTML:function(txt){return txt.escapeHTML().replace(/\n/g,"<br/>");},addLinksToResults:function(){$$("tr.failed .nameCell").each(function(td){td.title="Run only this test"
Event.observe(td,'click',function(){window.location.search="?tests="+td.innerHTML;});});$$("tr.passed .nameCell").each(function(td){td.title="Run all tests"
Event.observe(td,'click',function(){window.location.search="";});});}}
Test.Unit.Runner=Class.create();Test.Unit.Runner.prototype={initialize:function(testcases){this.options=Object.extend({testLog:'testlog'},arguments[1]||{});this.options.resultsURL=this.parseResultsURLQueryParameter();this.options.tests=this.parseTestsQueryParameter();if(this.options.testLog){this.options.testLog=$(this.options.testLog)||null;}
if(this.options.tests){this.tests=[];for(var i=0;i<this.options.tests.length;i++){if(/^test/.test(this.options.tests[i])){this.tests.push(new Test.Unit.Testcase(this.options.tests[i],testcases[this.options.tests[i]],testcases["setup"],testcases["teardown"]));}}}else{if(this.options.test){this.tests=[new Test.Unit.Testcase(this.options.test,testcases[this.options.test],testcases["setup"],testcases["teardown"])];}else{this.tests=[];for(var testcase in testcases){if(/^test/.test(testcase)){this.tests.push(new Test.Unit.Testcase(this.options.context?' -> '+this.options.titles[testcase]:testcase,testcases[testcase],testcases["setup"],testcases["teardown"]));}}}}
this.currentTest=0;this.logger=new Test.Unit.Logger(this.options.testLog);setTimeout(this.runTests.bind(this),1000);},parseResultsURLQueryParameter:function(){return window.location.search.parseQuery()["resultsURL"];},parseTestsQueryParameter:function(){if(window.location.search.parseQuery()["tests"]){return window.location.search.parseQuery()["tests"].split(',');};},getResult:function(){var hasFailure=false;for(var i=0;i<this.tests.length;i++){if(this.tests[i].errors>0){return"ERROR";}
if(this.tests[i].failures>0){hasFailure=true;}}
if(hasFailure){return"FAILURE";}else{return"SUCCESS";}},postResults:function(){if(this.options.resultsURL){new Ajax.Request(this.options.resultsURL,{method:'get',parameters:'result='+this.getResult(),asynchronous:false});}},runTests:function(){var test=this.tests[this.currentTest];if(!test){this.postResults();this.logger.summary(this.summary());return;}
if(!test.isWaiting){this.logger.start(test.name);}
test.run();if(test.isWaiting){this.logger.message("Waiting for "+test.timeToWait+"ms");setTimeout(this.runTests.bind(this),test.timeToWait||1000);}else{this.logger.finish(test.status(),test.summary());this.currentTest++;this.runTests();}},summary:function(){var assertions=0;var failures=0;var errors=0;var messages=[];for(var i=0;i<this.tests.length;i++){assertions+=this.tests[i].assertions;failures+=this.tests[i].failures;errors+=this.tests[i].errors;}
return((this.options.context?this.options.context+': ':'')+
this.tests.length+" tests, "+
assertions+" assertions, "+
failures+" failures, "+
errors+" errors");}}
Test.Unit.Assertions=Class.create();Test.Unit.Assertions.prototype={initialize:function(){this.assertions=0;this.failures=0;this.errors=0;this.messages=[];},summary:function(){return(this.assertions+" assertions, "+
this.failures+" failures, "+
this.errors+" errors"+"\n"+
this.messages.join("\n"));},pass:function(){this.assertions++;},fail:function(message){this.failures++;this.messages.push("Failure: "+message);},info:function(message){this.messages.push("Info: "+message);},error:function(error){this.errors++;this.messages.push(error.name+": "+error.message+"("+Test.Unit.inspect(error)+")");},status:function(){if(this.failures>0)return'failed';if(this.errors>0)return'error';return'passed';},assert:function(expression){var message=arguments[1]||'assert: got "'+Test.Unit.inspect(expression)+'"';try{expression?this.pass():this.fail(message);}
catch(e){this.error(e);}},assertEqual:function(expected,actual){var message=arguments[2]||"assertEqual";try{(expected==actual)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+
'", actual "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertInspect:function(expected,actual){var message=arguments[2]||"assertInspect";try{(expected==actual.inspect())?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+
'", actual "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertEnumEqual:function(expected,actual){var message=arguments[2]||"assertEnumEqual";try{$A(expected).length==$A(actual).length&&expected.zip(actual).all(function(pair){return pair[0]==pair[1]})?this.pass():this.fail(message+': expected '+Test.Unit.inspect(expected)+
', actual '+Test.Unit.inspect(actual));}
catch(e){this.error(e);}},assertNotEqual:function(expected,actual){var message=arguments[2]||"assertNotEqual";try{(expected!=actual)?this.pass():this.fail(message+': got "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertIdentical:function(expected,actual){var message=arguments[2]||"assertIdentical";try{(expected===actual)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+
'", actual "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertNotIdentical:function(expected,actual){var message=arguments[2]||"assertNotIdentical";try{!(expected===actual)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+
'", actual "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertNull:function(obj){var message=arguments[1]||'assertNull'
try{(obj==null)?this.pass():this.fail(message+': got "'+Test.Unit.inspect(obj)+'"');}
catch(e){this.error(e);}},assertMatch:function(expected,actual){var message=arguments[2]||'assertMatch';var regex=new RegExp(expected);try{(regex.exec(actual))?this.pass():this.fail(message+' : regex: "'+Test.Unit.inspect(expected)+' did not match: '+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertHidden:function(element){var message=arguments[1]||'assertHidden';this.assertEqual("none",element.style.display,message);},assertNotNull:function(object){var message=arguments[1]||'assertNotNull';this.assert(object!=null,message);},assertType:function(expected,actual){var message=arguments[2]||'assertType';try{(actual.constructor==expected)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+
'", actual "'+(actual.constructor)+'"');}
catch(e){this.error(e);}},assertNotOfType:function(expected,actual){var message=arguments[2]||'assertNotOfType';try{(actual.constructor!=expected)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+
'", actual "'+(actual.constructor)+'"');}
catch(e){this.error(e);}},assertInstanceOf:function(expected,actual){var message=arguments[2]||'assertInstanceOf';try{(actual instanceof expected)?this.pass():this.fail(message+": object was not an instance of the expected type");}
catch(e){this.error(e);}},assertNotInstanceOf:function(expected,actual){var message=arguments[2]||'assertNotInstanceOf';try{!(actual instanceof expected)?this.pass():this.fail(message+": object was an instance of the not expected type");}
catch(e){this.error(e);}},assertRespondsTo:function(method,obj){var message=arguments[2]||'assertRespondsTo';try{(obj[method]&&typeof obj[method]=='function')?this.pass():this.fail(message+": object doesn't respond to ["+method+"]");}
catch(e){this.error(e);}},assertReturnsTrue:function(method,obj){var message=arguments[2]||'assertReturnsTrue';try{var m=obj[method];if(!m)m=obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];m()?this.pass():this.fail(message+": method returned false");}
catch(e){this.error(e);}},assertReturnsFalse:function(method,obj){var message=arguments[2]||'assertReturnsFalse';try{var m=obj[method];if(!m)m=obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];!m()?this.pass():this.fail(message+": method returned true");}
catch(e){this.error(e);}},assertRaise:function(exceptionName,method){var message=arguments[2]||'assertRaise';try{method();this.fail(message+": exception expected but none was raised");}
catch(e){((exceptionName==null)||(e.name==exceptionName))?this.pass():this.error(e);}},assertElementsMatch:function(){var expressions=$A(arguments),elements=$A(expressions.shift());if(elements.length!=expressions.length){this.fail('assertElementsMatch: size mismatch: '+elements.length+' elements, '+expressions.length+' expressions');return false;}
elements.zip(expressions).all(function(pair,index){var element=$(pair.first()),expression=pair.last();if(element.match(expression))return true;this.fail('assertElementsMatch: (in index '+index+') expected '+expression.inspect()+' but got '+element.inspect());}.bind(this))&&this.pass();},assertElementMatches:function(element,expression){this.assertElementsMatch([element],expression);},benchmark:function(operation,iterations){var startAt=new Date();(iterations||1).times(operation);var timeTaken=((new Date())-startAt);this.info((arguments[2]||'Operation')+' finished '+
iterations+' iterations in '+(timeTaken/1000)+'s');return timeTaken;},_isVisible:function(element){element=$(element);if(!element.parentNode)return true;this.assertNotNull(element);if(element.style&&Element.getStyle(element,'display')=='none')
return false;return this._isVisible(element.parentNode);},assertNotVisible:function(element){this.assert(!this._isVisible(element),Test.Unit.inspect(element)+" was not hidden and didn't have a hidden parent either. "+(""||arguments[1]));},assertVisible:function(element){this.assert(this._isVisible(element),Test.Unit.inspect(element)+" was not visible. "+(""||arguments[1]));},benchmark:function(operation,iterations){var startAt=new Date();(iterations||1).times(operation);var timeTaken=((new Date())-startAt);this.info((arguments[2]||'Operation')+' finished '+
iterations+' iterations in '+(timeTaken/1000)+'s');return timeTaken;}}
Test.Unit.Testcase=Class.create();Object.extend(Object.extend(Test.Unit.Testcase.prototype,Test.Unit.Assertions.prototype),{initialize:function(name,test,setup,teardown){Test.Unit.Assertions.prototype.initialize.bind(this)();this.name=name;if(typeof test=='string'){test=test.gsub(/(\.should[^\(]+\()/,'#{0}this,');test=test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');this.test=function(){eval('with(this){'+test+'}');}}else{this.test=test||function(){};}
this.setup=setup||function(){};this.teardown=teardown||function(){};this.isWaiting=false;this.timeToWait=1000;},wait:function(time,nextPart){this.isWaiting=true;this.test=nextPart;this.timeToWait=time;},run:function(){try{try{if(!this.isWaiting)this.setup.bind(this)();this.isWaiting=false;this.test.bind(this)();}finally{if(!this.isWaiting){this.teardown.bind(this)();}}}
catch(e){this.error(e);}}});Test.setupBDDExtensionMethods=function(){var METHODMAP={shouldEqual:'assertEqual',shouldNotEqual:'assertNotEqual',shouldEqualEnum:'assertEnumEqual',shouldBeA:'assertType',shouldNotBeA:'assertNotOfType',shouldBeAn:'assertType',shouldNotBeAn:'assertNotOfType',shouldBeNull:'assertNull',shouldNotBeNull:'assertNotNull',shouldBe:'assertReturnsTrue',shouldNotBe:'assertReturnsFalse',shouldRespondTo:'assertRespondsTo'};var makeAssertion=function(assertion,args,object){this[assertion].apply(this,(args||[]).concat([object]));}
Test.BDDMethods={};$H(METHODMAP).each(function(pair){Test.BDDMethods[pair.key]=function(){var args=$A(arguments);var scope=args.shift();makeAssertion.apply(scope,[pair.value,args,this]);};});[Array.prototype,String.prototype,Number.prototype,Boolean.prototype].each(function(p){Object.extend(p,Test.BDDMethods)});}
Test.context=function(name,spec,log){Test.setupBDDExtensionMethods();var compiledSpec={};var titles={};for(specName in spec){switch(specName){case"setup":case"teardown":compiledSpec[specName]=spec[specName];break;default:var testName='test'+specName.gsub(/\s+/,'-').camelize();var body=spec[specName].toString().split('\n').slice(1);if(/^\{/.test(body[0]))body=body.slice(1);body.pop();body=body.map(function(statement){return statement.strip()});compiledSpec[testName]=body.join('\n');titles[testName]=specName;}}
new Test.Unit.Runner(compiledSpec,{titles:titles,testLog:log||'testlog',context:name});};var WJComponent=Class.create({initialize:function(id){this.id=id;this.value=null;this.componentType="WJComponent";this.components=new Array();this.label=null;this.group=false;},setHtmlelement:function(element){this.htmlelement=element;if(this.htmlelement.value){this.value=this.htmlelement.value;}
else if($("hidden_"+this.htmlelement.id)){this.value=$("hidden_"+this.htmlelement.id).value;}},observe:function(event,callback){if(Object.isArray(this.htmlelement)){this.htmlelement.each(function(s){s.observe(event,callback);});}
else if(this.htmlelement){this.htmlelement.observe(event,callback);}},addComponent:function(comp){WJDebugger.log(WJDebugger.DEBUG,"Adding component to "+this.componentType+" "+this.id,comp);this.components.push(comp);},getComponents:function(){return this.components;},valueChanged:function(){var oldValue=this.value;this.getValue();var changed=(oldValue==null&&this.value==null)?false:(oldValue!=this.getValue());this.value=oldValue;return changed;},getValue:function(nochange){var usesDijit=(typeof(dijit)!="undefined")?true:false;var nochange=nochange||false;var oldvalue=this.value;if(this.htmlelement&&usesDijit&&dijit.byId(this.htmlelement.id)&&dijit.byId(this.htmlelement.id).getValue){this.value=dijit.byId(this.htmlelement.id).attr("value");}
else if(this.htmlelement&&(this.htmlelement.value!=null)){this.value=this.htmlelement.value;}
if(nochange){var newval=this.value;this.value=oldvalue;return newval;}
else{return this.value;}},setValue:function(value){var usesDijit=(typeof(dijit)!="undefined")?true:false;this.value=value;if(this.htmlelement&&usesDijit&&dijit.byId(this.htmlelement.id)&&dijit.byId(this.htmlelement.id).setValue){dijit.byId(this.htmlelement.id).setValue(this.value);}
else if(this.htmlelement&&this.htmlelement.value){this.htmlelement.value=this.value;}},getId:function(){return this.id;},toString:function(){if(this.componentType===null){return"Uninitialized WJComponent";}
return this.componentType+" instance '"+this.id+"'";}});var WJRestrictedInput=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJRestrictedInput";}});var WJSinglevalueInput=Class.create(WJRestrictedInput,{initialize:function($super,id){$super(id);this.componentType="WJSinglevalueInput";}});var WJMultivalueInput=Class.create(WJRestrictedInput,{initialize:function($super,id){$super(id);this.componentType="WJMultivalueInput";}});WJGroup=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJGroup";this.region="center";this.group=true;},setRegion:function(region){this.region=region;}});var WJText=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJText";}});WJLabel=Class.create(WJComponent,{initialize:function($super,id,text,image){$super(id);this.componentType="WJLabel",this.text=text;this.image=image;}});var WJTab=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJTab";},setTitle:function(title){if(this.htmlelement&&this.htmlelement["class"]=="dijitContentPane"){this.htmlelement.controlButton.containerNode.innerHTML=title;}},setHtmlelement:function($super,element){$super(element);if(this.htmlelement.down("input")){this.value=this.htmlelement.down("input").value;}}});var WJFileSelector=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJFileSelector";this.changed=false;},_section:0,valueChanged:function(){return this.changed;},selectFile:function(file,path,section){this.changed=true;this.setValue("/var/mediamanager/"+WJMediamanagerInterface.getSectionDir(section)+"/"+path+"/"+file);this.showThumbnail();this.showFilepath();},getThumbnailPath:function(){return this.getValue();},showThumbnail:function(){var thumb=$(this.htmlelement.id+"_thumbnail")||$(this.htmlelement.id.replace(/([^-]*)-.*/,"$1")+"_thumbnail");if(thumb){var src=thumb.src;var basepath=src.match(/(\/images\/thumbs(\/__[^\/]*)*)\/?/);if(basepath){thumb.src="/index.php?ct=wmdynamic&module=Wmmediamanager&mode=thumbnail&orig_uri="+basepath[1]+this.getThumbnailPath();}
else{thumb.src="/images/thumbs/__lw50h50"+this.getThumbnailPath();}
if(thumb.up(".aeroplane_nothumb")){thumb.up(".aeroplane_nothumb").removeClassName("aeroplane_nothumb");}}},showFilepath:function(){var pathwrapper=$(this.htmlelement.id+"_filepath")||$(this.htmlelement.id.replace(/([^-]*)-.*/,"$1")+"_filepath");if(pathwrapper){pathwrapper.update(this.getThumbnailPath());if(pathwrapper.up(".aeroplane_nofilepath")){pathwrapper.up(".aeroplane_nofilepath").removeClassName("aeroplane_nofilepath");}
if(this.getValue()==""&&pathwrapper.up(".aeroplane_mediamanagerfilepath")){pathwrapper.up(".aeroplane_mediamanagerfilepath").addClassName("aeroplane_nofilepath");}}},setValue:function(val){this.value=val;if(this.htmlelement.type=="hidden"){this.htmlelement.value=this.value;}},getValue:function(){if(this.htmlelement){if(this.htmlelement.type=="file"){try{var body=this.htmlelement.up().previous("iframe").contentWindow.document.body;if(!body){return this.value;}
if(body.textContent){var obj=body.textContent.evalJSON(true);}
else{var obj=body.innerHTML.stripTags().replace(/\r\n/g,"").evalJSON(true);}
if(obj.newname){this.value=obj.newname;}
else if(obj[0]&&obj[0].newname){this.value="/var/mediamanager/"+WJMediamanagerInterface.getSectionDir(this._section)+"/"+document.forms[this.id+"_form"]["path"].value+"/"+obj[0].newname;}}
catch(e){if(e.name!="SyntaxError"){throw e;}}}
else if(this.htmlelement.type=="hidden"){this.value=this.htmlelement.value;}}
return this.value;},uploadSingleFile:function(event){if(this.htmlelement.up().previous("iframe")){this._loadObserver=this.handleResponse.bindAsEventListener(this);this.htmlelement.up().previous("iframe").observe("load",this._loadObserver);}
document.forms[this.id+"_form"].submit();},handleResponse:function(event){this.changed=true;this.htmlelement.up().previous("iframe").stopObserving("load",this._loadObserver);var img=this.htmlelement.previous("img");if(!img){var img=new Image();$(img);this.htmlelement.up().insertBefore(img,this.htmlelement);this.htmlelement.up().insertBefore(new Element("br"),this.htmlelement);}
img.src="/images/thumbs/__lw50h50"+this.getThumbnailPath();img.show();try{this.htmlelement.value="";}
catch(e){}},clearItem:function(event){this.setValue("");this.changed=true;this.showThumbnail();this.showFilepath();},_activateSelectOptions:function(){if($("clear_"+this.htmlelement.id)){$("clear_"+this.htmlelement.id).observe("click",this.clearItem.bind(this));}
if($("upload_"+this.htmlelement.id)){$("upload_"+this.htmlelement.id).observe("change",this.directUpload.bind(this));}
if($("downloadbutton_"+this.htmlelement.id)){$("downloadbutton_"+this.htmlelement.id).observe("click",this.directDownload.bind(this));}
if(dijit.byId("mediamanager_"+this.htmlelement.id)){dijit.byId("mediamanager_"+this.htmlelement.id).setObserver(function(){aeroplane.openApplication("Mediamanager",this.selectFile.bind(this),{section:this._section,path:this.getFilePath()});}.bind(this));}},getFilePath:function(){var curFile=this.getValue();if(curFile){var pieces=curFile.split("/");return"./"+pieces.slice(4,pieces.length-1).join("/");}
else{return".";}},directDownload:function(){var fileurl=$("download_"+this.htmlelement.id).value;if(fileurl==""){WJWindow.alert("Please supply an URL to download the file from.",function(){},aeroplane.translateGui);}
else{var url=new WJUrl({},"/index.php");url.setCt("wmdynamic");url.addParameter("module","Wmmediamanager");url.addParameter("type","json");url.addParameter("uploadsection",this._section);var spin=new WJSpin();aeroplane.progressnotifier.show(this,"Your file is being uploaded and processed, please be patient, this can take a while.");spin.update(url,"Wmmediamanager","directdownload",{fileurl:fileurl},[this.directDownloadResponse.bind(this)]);}},directDownloadResponse:function(response){aeroplane.progressnotifier.hide(this,"Your file is being uploaded and processed, please be patient, this can take a while.");this.setValue(response[0]);this.changed=true;this.showThumbnail();this.showFilepath();$("frame_"+this.htmlelement.id).stopObserving("load",this._loadObserver);},directUploadResponse:function(){aeroplane.progressnotifier.hide(this,"Your file is being uploaded and processed, please be patient, this can take a while.");var iframedoc=($("frame_"+this.htmlelement.id).contentDocument||$("frame_"+this.htmlelement.id).contentWindow.document);if(iframedoc.body.textContent){var data=iframedoc.body.textContent.evalJSON(true);}
else{var data=iframedoc.body.innerHTML.stripTags().replace(/\r\n/g,"").evalJSON(true);}
this.setValue(data[0]);this.changed=true;this.showThumbnail();this.showFilepath();},directUpload:function(){if($("frame_"+this.htmlelement.id)){aeroplane.progressnotifier.show(this,"Your file is being uploaded and processed, please be patient, this can take a while.");this._loadObserver=this.directUploadResponse.bindAsEventListener(this);$("frame_"+this.htmlelement.id).observe("load",this._loadObserver);$("upload_"+this.htmlelement.id).up("form").submit();}},setHtmlelement:function($super,elem){if(dijit.byId("mediamanager_"+elem.id)){$super(elem);this._activateSelectOptions();}
else if(elem.type=="file"){$super(elem);this.htmlelement.observe("change",this.uploadSingleFile.bindAsEventListener(this));}
else if($("hidden_"+elem.id)){$super(elem);}
else{this.setHtmlelement.bind(this,elem).delay(0.1);}}});var WJFile=Class.create(WJFileSelector,{initialize:function($super,id){$super(id);this.componentType="WJFile";},_section:2200});var WJImage=Class.create(WJFileSelector,{initialize:function($super,id){$super(id);this.componentType="WJImage";},_section:2100,showThumbnail:function($super){$super();if($(this.htmlelement.id+"_thumbnail")){var testVal=this.getValue();if(Object.isString(testVal)&&(testVal!="")){new Ajax.Request($(this.htmlelement.id+"_thumbnail").src,{onFailure:function(response){if(response.transport.status==500){WJWindow.alert("De afbeelding die je hebt geselecteerd is niet bruikbaar. Gebruik a.u.b. een afbeelding in het jpg, png of gif formaat.",function(){},aeroplane.translateGui);}}});}}}});var WJFlash=Class.create(WJFile,{initialize:function($super,id){$super(id);this.componentType="WJFlash";this.changed=false;},_section:2500});var WJFlashVideo=Class.create(WJFileSelector,{initialize:function($super,id){$super(id);this.componentType="WJFlashVideo";},_section:2300,getThumbnailPath:function($super){return $super()+".png";}});var WJButtonComponent=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJButtonComponent";},disable:function(){if(dijit.byId(this.htmlelement.id)){dijit.byId(this.htmlelement.id).button.disable();}
else{this.disable.bind(this).delay(0.25);}},enable:function(){if(dijit.byId(this.htmlelement.id)){dijit.byId(this.htmlelement.id).button.enable();}
else{this.disable.bind(this).delay(0.25);}}});var WJAccordion=Class.create(WJTab,{initialize:function($super,id){$super(id);this.componentType="WJAccordion";}});var WJAlbumComponent=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJAlbumComponent";this.value={};this.counter=0;},getValue:function(){var entries=this.htmlelement.select(".wjalbumcomponententry");var value=new Array();entries.each(function(entry){if(entry.id!="wjalbumcomponententry_template"){var inputs=entry.select("input");var title="";for(var i=0;i<inputs.length;i++){if($(inputs[i]).readAttribute("name")&&$(inputs[i]).readAttribute("name").endsWith("title")){title=$(inputs[i]).getValue();}}
var albumimage={imgsrc:entry.down("img").src,title:title,description:tinymce.EditorManager.get(entry.down("textarea").id).getContent()};this.push(albumimage);}}.bind(value));return value;},addAlbumImage:function(components){var albumimage=[]
components.each(function(component,s){if((s.id=="user")||(s.id=="added")){s.componentType="WJComponent";}
s.id=s.id+"_"+component.counter;this.push(s);}.bind(albumimage,this));this.value["albumimage_"+this.counter]=albumimage;this.counter++;},setHtmlelement:function($super,element){$super(element);element.select(".aeroplane_wjalbumcomponent_removebutton").each(function(button){this.addRemoveButtonListener(button);}.bind(this));element.select("textarea").each(function(area){tinyMCE.execCommand("mceAddControl",true,area.id);});this.addAddButtonListener("addbutton_"+element.id);},addAddButtonListener:function(buttonid){if(dijit.byId(buttonid)){dijit.byId(buttonid).setObserver(this.openMediamanager.bind(this));}
else{this.addAddButtonListener.bind(this,buttonid).delay(0.1);}},openMediamanager:function(){aeroplane.openApplication("Mediamanager",this.selectMedia.bind(this),{multiple:true});},selectMedia:function(media){var counter=this.htmlelement.select(".wjalbumcomponententry").length+1;for(var i=0;i<media.length;i++){var mediaElem=$("wjalbumcomponententry_template").cloneNode(true);var fileaddition=(WJMediamanagerInterface.getSectionDir(media[i].section)=="videos")?".png":"";mediaElem.id=null;mediaElem.down("img").src=mediaElem.down("img").src+"/var/mediamanager/"+WJMediamanagerInterface.getSectionDir(media[i].section)+"/"+media[i].path+"/"+media[i].file+fileaddition;mediaElem.setStyle({"display":"block"});mediaElem.down(".aeroplane_wjalbumcomponent_removebutton").setAttribute("dojoType","aeroplanedijit.WJButton");mediaElem.down(".aeroplane_wjtext").down("input").setAttribute("dojoType","dijit.form.TextBox");mediaElem.down("textarea").addClassName("aeroplane_wjrichtext");mediaElem.down("textarea").id="wjrichtext_"+counter;this.htmlelement.insert({top:mediaElem});dojo.parser.parse(mediaElem);tinymce.EditorManager.execCommand("mceAddControl",false,"wjrichtext_"+counter);counter++;}},addRemoveButtonListener:function(button){if(dijit.byId(button.id)){dijit.byId(button.id).setObserver(function(e){button.up(".wjalbumcomponententry").remove();}.bindAsEventListener(button));}
else{this.addRemoveButtonListener.bind(this,button).delay(0.1);}}});var WJCheckbox=Class.create(WJMultivalueInput,{initialize:function($super,id){$super(id);this.componentType="WJCheckbox";},getValue:function($super){if(this.htmlelement.tagName.toUpperCase()=="INPUT"){if(this.htmlelement.checked){return $super();}}
else{var checkboxes=this.htmlelement.select("input");this.value=[];for(var i=0;i<checkboxes.length;i++){if(checkboxes[i].checked){this.value.push(checkboxes[i].value);}}
return this.value;}}});var WJCloseableTab=Class.create(WJTab,{initialize:function($super,id){$super(id);this.componentType="WJCloseableTab";}});WJConditionalGroup=Class.create(WJGroup,{initialize:function($super,id,testid,testvalue){$super(id);this.componentType="WJConditionalGroup";this.testId=testid;this.testValue=testvalue;},setHtmlelement:function($super,element,gui){$super(element);this.gui=gui;this.updateDisplay.bind(this).defer();this.addChangeObserverToTestId.bind(this).defer();},addChangeObserverToTestId:function(){this.gui.getComponentForField(this.testId).observe("change",this.updateDisplay.bind(this));},getValue:function($super){if(this.gui){return this.gui.getComponentForField(this.testId).getValue(true);}
else{return $super();}},updateDisplay:function(){if(this.getValue()==this.testValue){this.htmlelement.setStyle({display:"block"});}
else{this.htmlelement.setStyle({display:"none"});}}});var WJDate=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJDate";},getValue:function($super){var value=$super();if(value){this.value=value.toString();}
else{this.value="";}
return this.value;}});var WJDir=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJDir";this.changed=false;},setHtmlelement:function($super,elem){$super(elem);if(dijit.byId("mediamanager_"+this.htmlelement.id)){dijit.byId("mediamanager_"+this.htmlelement.id).setObserver(function(){aeroplane.openApplication("Mediamanager",this.selectDir.bind(this),{section:WJMediamanagerInterface.IMAGES,path:this.getParentDir(),type:"dir"});}.bind(this));}},getParentDir:function(){var curFile=this.getValue();if(curFile){var pieces=curFile.split("/").compact().without("",".");return"./"+pieces.slice(3,pieces.length-1).join("/");}
else{return".";}},valueChanged:function(){return this.changed;},selectDir:function(dir,section){if(section==WJMediamanagerInterface.IMAGES){dir="/var/mediamanager/images/"+dir;}
else if(section==WJMediamanagerInterface.FILES){dir="/var/mediamanager/files/"+dir;}
else if(section==WJMediamanagerInterface.VIDEOS){dir="/var/mediamanager/videos/"+dir;}
this.changed=true;this.value=dir;this.htmlelement.up().down("label").update(this.value);this.htmlelement.value=this.value;}});WJExtendibleGroup=Class.create(WJGroup,{initialize:function($super,id){$super(id);this.componentType="WJExtendibleGroup";},setHtmlelement:function($super,element){$super(element);this._addRemoveListeners();this._addAddListener();this._toggleRemoveButtons();},_addRemoveListeners:function(removebuttons){var removebuttons=$A(removebuttons||this.htmlelement.select("div.aeroplane_removewjextendiblegroupcomponent")).compact();removebuttons.invoke("observe","click",this.removeItem.bindAsEventListener(this));},_addAddListener:function(){this.htmlelement.down("div.aeroplane_addwjextendiblegroupcomponent").observe("click",this.addItem.bindAsEventListener(this));},removeItem:function(event){var element=event.element();var item=element.up("div.aeroplane_wjextendiblegroup_component").remove();this._toggleRemoveButtons();return item;},addItem:function(event){var addbutton=this.htmlelement.down("div.aeroplane_addwjextendiblegroupcomponent");var item=addbutton.previous("div.aeroplane_wjextendiblegroup_component");var selectedradios=item.select("input[type=radio]").select(function(input){return input.checked});var newItem=$(addbutton.up().insertBefore(item.cloneNode(true),addbutton));selectedradios.each(function(input){input.checked=true;});this._resetFields(newItem);this._addRemoveListeners([newItem.down("div.aeroplane_removewjextendiblegroupcomponent")]);this._toggleRemoveButtons();addbutton.scrollIntoView();return newItem;},_resetFields:function(element){WJExtendibleGroup.cloneCounter++;element.select("label").each(function(label){if(label.htmlFor){label.htmlFor="";}
else if(label["for"]){label["for"]="";}});element.select("input, select, textarea").each(function(el){el.name=el.name.replace(/^([^\[]*\[)[^\]]*(\].*)$/,"$1"+"new"+WJExtendibleGroup.cloneCounter+"$2");el.id+="new"+WJExtendibleGroup.cloneCounter;switch(el.tagName.toLowerCase()){case"input":switch(el.type.toLowerCase()){case"text":el.clear();break;case"checkbox":case"radio":el.checked=false;break;}
break;case"select":el.selectedIndex=0;break;case"textarea":el.update("");break;}});},_toggleRemoveButtons:function(){var removebuttons=this.htmlelement.select("div.aeroplane_removewjextendiblegroupcomponent");removebuttons.invoke("setStyle",{"visibility":(removebuttons.length==1?"hidden":"visible")});},getValue:function(){this.value=this.htmlelement.select("input, select, textarea").inject({},function(result,el){var name=el.name;if(name==""){name=el.id;}
if(el.type=="checkbox"&&name.endsWith("[]")){var wrapper=el.up("div");if(wrapper.retrieve("index")==null){wrapper.store("index",0);}
name=name.replace(/\[\]$/,"["+wrapper.retrieve("index")+"]");wrapper.store("index",wrapper.retrieve("index")+1);}
if(el.type=="radio"){if(!result[name]){result[name]=null;}
if(el.checked){result[name]=el.value;}}
else if(el.type=="checkbox"){if(el.checked){result[name]=el.value;}}
else{result[name]=el.getValue();}
return result;});return this.value;}});WJExtendibleGroup.cloneCounter=0;var WJFileUploader=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJFileUploader";this._totalSize=0;},_initUploaderWidget:function(){window.uploaderEvent=this.eventHandler.bind(this);this.uploader=new SWFObject("uploaderObject","/lib/plugin/aeroplane/flash/uploader.swf","100%","100%","transparent",{settings:Object.toJSON({eventHandler:"uploaderEvent",allowMultipleFiles:true,buttonImage:"/lib/wjgui/skins/lucid/images/contentbuttons.png",buttonText:"Bestanden zoeken",buttonTextStyle:{font:"Arial",fontSize:"12",color:"F40D75",fontWeight:"bold"}})});swfloader.loadSWFObject(this.htmlelement,this.uploader);},eventHandler:function(reference,event){switch(event.type){case"resize":this.htmlelement.setStyle({width:event.width,height:event.height});break;case"fileSelect":this.fileSelect(event);break;case"uploadCompleteData":this.markUploadComplete(event);break;case"uploadError":case"uploadCancel":this.markUploadCancel(event);break;}},setNextButton:function(button){this.nextbutton=button;this.nextbutton.disable();},markUploadCancel:function(e){$(e.id+"_inforow").down(".aeroplane_uploadcancelled").show();$(e.id+"_inforow").down(".aeroplane_uploadcancelled").title="De upload werd geannulleerd";$(e.id+"_inforow").down("a.aeroplane_delete").hide();this.handleUploadCompleted(e.id);},handleUploadCompleted:function(id){delete this.files[id];if($H(this.files).size()==0){this.componentdiv.down(".aeroplane_fileselector").down("div").hide();this.componentdiv.down(".aeroplane_fileselector").insert(new Element("h2").update("De upload is voltooid"));this.componentdiv.down("thead").down(".aeroplane_delete").firstDescendant().hide();this.uploadbutton.getButton().setStyle({visibility:"hidden"});aeroplane.loadingCursor(false);}},markUploadComplete:function(e){$(e.id+"_inforow").down("a.aeroplane_delete").hide();var finfo=e.data.evalJSON()[0];WJDebugger.log(WJDebugger.NOTICE,"Marking '%s' as uploaded",e.id,finfo);if(finfo.error==0){$(e.id+"_inforow").down(".aeroplane_complete").show();if(finfo.errormessage){$(e.id+"_inforow").down(".aeroplane_complete").title=finfo.errormessage;}
if(this.nextbutton){this.nextbutton.enable();}}
else{$(e.id+"_inforow").down(".aeroplane_error").show();if(finfo.errormessage){$(e.id+"_inforow").down(".aeroplane_error").title=finfo.errormessage;}}
this.handleUploadCompleted(e.id);},fileSelect:function(e){this._updateListing(e.fileList);},_updateListing:function(files){this.componentdiv.down("thead").hide();if(this.uploadbutton){this.uploadbutton.getButton().setStyle({visibility:"visible"});}
this.componentdiv.down("tbody").update("");this.componentdiv.down(".aeroplane_wjfileuploader_tablewrapper").setStyle({"height":($(this.componentdiv.parentNode).getHeight()-100)+"px","overflow-y":"auto"});this.componentdiv.down(".aeroplane_total").update("");aeroplane.windowmanager.cleanUpDijitWidgets();this._totalSize=0;this.files=files;var filescollection=[];for(var file in this.files){filescollection.push(file);}
if(filescollection.length===0){this.componentdiv.down(".aeroplane_wjfileuploader_tablewrapper").setStyle({"height":0});}
filescollection.reverse().each(function(file){this._handleFileSelect(this.files[file]);}.bind(this));if($H(this.files).size()>0){this.componentdiv.siblings().invoke("remove");this.componentdiv.down(".aeroplane_total").update("Totaal"+": <strong>"+this._formatFileSize(this._totalSize)+"</strong>");this.componentdiv.down("thead").show();$(this.uploader.getAttribute("swfname")).setTextStyle(Object.toJSON({font:"Arial",fontSize:"12",color:"01A1C1",fontWeight:"normal",textDecoration:"underline",cursor:"pointer"}));$(this.uploader.getAttribute("swfname")).setText("Bestanden toevoegen");$(this.uploader.getAttribute("swfname")).hideButtonImage();this._showUploadButton();}
else{if(this.uploader){$(this.uploader.getAttribute("swfname")).setTextStyle(Object.toJSON({font:"Arial",fontSize:"12",color:"F40D75",fontWeight:"bold",textDecoration:"none",cursor:"default"}));$(this.uploader.getAttribute("swfname")).setText("Bestanden zoeken");$(this.uploader.getAttribute("swfname")).showButtonImage();this.uploadbutton.getButton().setStyle({visibility:"hidden"});}}},removeFile:function(fileID){WJDebugger.log(WJDebugger.NOTICE,"Removing file '%s'",fileID);var files={};for(var id in this.files){if(id!=fileID){files[id]=this.files[id];}}
$(this.uploader.getAttribute("swfname")).removeFile(fileID);this._updateListing(files);},_showUploadButton:function(){if(!this.uploadbutton){this.uploadbutton=new WJButton("Upload starten",this.startUpload.bind(this),false,this.componentdiv.down("div.aeroplane_start"));}
this.uploadbutton.getButton().setStyle({visibility:"visible"});},startUpload:function(){aeroplane.loadingCursor(true);var cookie=new WJCookie();var sessionid=cookie.get("PHPSESSID",false);this.uploadInfo["PHPSESSID"]=sessionid;WJDebugger.log(WJDebugger.INFO,"Upload files",this.uploadInfo,this.files);$(this.uploader.getAttribute("swfname")).uploadAll("/index.php","POST",this.uploadInfo);},setUploadInformation:function(info){this.uploadInfo=info;},_handleFileSelect:function(file){WJDebugger.log(WJDebugger.NOTICE,"Selecting file",file);if(!this.pastetable){this.pastetable=new Element("table");}
var info=info={id:file.id,file:file.name,size:this._formatFileSize(file.size)};this.pastetable.update(this.rowtemplate.evaluate(info));$A(this.pastetable.rows).each(function(row){this.componentdiv.down("tbody").appendChild(row);},this);this.componentdiv.select("a.aeroplane_delete").last().observe("click",function(event,fileID){this.removeFile(fileID);}.bindAsEventListener(this,file.id));dojo.parser.parse(this.componentdiv);this._totalSize+=file.size;},_formatFileSize:function(bytesize){if(bytesize>=1073741824){bytesize=(Math.round((bytesize*100)/1073741824)/100)+" "+"GB";}
else if(bytesize>=1048576){bytesize=(Math.round((bytesize*100)/1048576)/100)+" "+"MB";}
else if(bytesize>=1024){bytesize=(Math.round((bytesize*100)/1024)/100)+" "+"KB";}
else{bytesize=bytesize+" "+"b";}
return bytesize;},alternativeUpload:function(){this.alternativeUploader.form.submit();$(this.alternativeUploader.form.target).observe("load",function(){this.nextbutton.enable();this.componentdiv.down(".aeroplane_fileselector").down("div").hide();this.componentdiv.down(".aeroplane_fileselector").insert(new Element("h2").update("De upload is voltooid"));}.bind(this));},setHtmlelement:function($super,element){$super(element);this.componentdiv=this.htmlelement.up(".aeroplane_wjfileuploader")
var templaterows=this.componentdiv.select("tr.aeroplane_listingtemplate");this.rowtemplate=new Template(templaterows.collect(function(row){return"<tr id='"+row.id+"row' class='"+row.className+"'>"+row.innerHTML+"</tr>";}).join(""));templaterows.invoke("remove");this._updateListing({});this._initUploaderWidget();if($("alternative_"+element.id)){this.alternativeUploader=$("alternative_"+element.id);this.alternativeUploader.observe("change",this.alternativeUpload.bind(this));if($("alternativelink_"+element.id)){$("alternativelink_"+element.id).observe("click",function(){$("alternativediv_"+element.id).setStyle({"display":"block"});});}}}});var WJHtml=Class.create(WJGroup,{initialize:function($super,id){$super(id);this.componentType="WJHtml";this.group=0;}});var WJLinkButton=Class.create(WJButtonComponent,{initialize:function($super,id){$super(id);this.componentType="WJLinkButton";}});var WJLink=Class.create(WJGroup,{initialize:function($super,id){$super(id);this.componentType="WJLink";this.region="top";this.group=0;}});var WJListbox=Class.create(WJMultivalueInput,{initialize:function($super,id){$super(id);this.componentType="WJListbox";}});var WJList=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJList";}});var WJLongText=Class.create(WJText,{initialize:function($super,id){$super(id);this.componentType="WJLongText";}});var WJNormalButton=Class.create(WJButtonComponent,{initialize:function($super,id){$super(id);this.componentType="WJNormalButton";}});var WJOptionGroup=Class.create({initialize:function(){this.options=new Array();this.componentType="WJOptionGroup";},getOptions:function(){return this.options;},addOption:function(option){this.options.push(option);}});var WJOption=Class.create({initialize:function(value,label){this.label=label;this.value=value;this.componentType="WJOption";}});var WJPassword=Class.create(WJText,{initialize:function($super,id){$super(id);this.componentType="WJPassword";}});var WJRadio=Class.create(WJSinglevalueInput,{initialize:function($super,id){$super(id);this.componentType="WJRadio";this.htmlelement=[];},setHtmlelement:function(element){this.htmlelement.push(element);},getValue:function(nochange){var nochange=nochange||false;var oldvalue=this.value;for(var i=0;i<this.htmlelement.length;i++){if(this.htmlelement[i]&&dijit.byId(this.htmlelement[i].id)&&dijit.byId(this.htmlelement[i].id).getValue){if(dijit.byId(this.htmlelement[i].id).checked){this.value=dijit.byId(this.htmlelement[i].id).getValue();}}
else if(this.htmlelement[i]){if(this.htmlelement[i].checked){this.value=this.htmlelement[i].getAttribute("value");}}}
if(nochange){var newval=this.value;this.value=oldvalue;return newval;}
else{return this.value;}}});var WJReview=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJReview";}});var WJRichtext=Class.create(WJText,{initialize:function($super,id){$super(id);this.componentType="WJRichtext";},setHtmlelement:function($super,element){$super(element);if(tinyMCE.editors[this.htmlelement.id]){tinyMCE.execCommand("mceRemoveControl",false,this.htmlelement.id);}
tinyMCE.execCommand("mceAddControl",true,this.htmlelement.id);this.originalContent=null;tinymce.EditorManager.get(this.htmlelement.id).onInit.add(function(){if(!this.originalContent){this.originalContent=tinymce.EditorManager.get(this.htmlelement.id).getContent();}}.bind(this));},valueChanged:function($super){var usesTinyMCE=(typeof(tinyMCE)!="undefined")?true:false;if(this.htmlelement&&usesTinyMCE&&tinymce.EditorManager.get(this.htmlelement.id)&&tinymce.EditorManager.get(this.htmlelement.id).getContent){if(this.originalContent==null){return false;}
else{return tinymce.EditorManager.get(this.htmlelement.id).getContent()!=this.originalContent;}}
else{return $super();}},getValue:function($super){var usesTinyMCE=(typeof(tinyMCE)!="undefined")?true:false;if(this.htmlelement&&usesTinyMCE&&tinymce.EditorManager.get(this.htmlelement.id)&&tinymce.EditorManager.get(this.htmlelement.id).getContent){this.value=tinymce.EditorManager.get(this.htmlelement.id).getContent();}
else{this.value=$super();}
return this.value;}});WJRichtextLabel=Class.create(WJLabel,{initialize:function($super,id,html){$super(id);this.componentType="WJRichtextLabel",this.html=html;},setLabel:function($super,label,force){var force=force||false;if(force){$super(label);}}});var WJSelect=Class.create(WJSinglevalueInput,{initialize:function($super,id){$super(id);this.componentType="WJSelect";},getValue:function($super,nochange){var nochange=nochange||false;var oldvalue=this.value;if(this.htmlelement.options){this.value=this.htmlelement.options[this.htmlelement.selectedIndex].value;this.htmlelement.value=this.value;if(nochange){var newval=this.value;this.value=oldvalue;return newval;}
else{return this.value;}}
return $super(nochange);}});var WJSlider=Class.create(WJSinglevalueInput,{initialize:function($super,id){$super(id);this.componentType="WJSlider";}});WJTabGroup=Class.create(WJGroup,{initialize:function($super,id){$super(id);this.componentType="WJTabGroup";}});var WJTagCloud=Class.create(WJText,{initialize:function($super,id){$super(id);this.componentType="WJTagCloud";}});var WJThumbnail=Class.create(WJImage,{initialize:function($super,id){$super(id);this.componentType="WJThumbnail";}});var WJTime=Class.create(WJComponent,{initialize:function($super,id){$super(id);this.componentType="WJTime";}});var WJTree=Class.create(WJLabel,{initialize:function($super,id){$super(id);this.componentType="WJTree";}});var WJUrltext=Class.create(WJText,{initialize:function($super,id){$super(id);this.componentType="WJUrltext";}});var WJCBAction=Class.create({initialize:function(name,func,properties){this.name=name;this.cbfunc=func;this.components=[];this.properties=properties||{update:true};},execute:function(data){var spin=new WJSpin();var url=new WJUrl({ct:"wmdynamic",dt:"wmcontentblock",module:"Wmcb",id:this.cbfunc.getId(),action:this.name,"wmtrigger[]":["requestufts"],"uft[]":["contentblock"]});this.components.each(function(s){this.addParameter("args["+s.getId()+"]",s.getValue());}.bind(url));for(var key in data){url.addParameter(key,data[key]);}
$(document.body).setStyle({"cursor":"wait"});if(this.properties.update){var elem=this.cbfunc.getElement();elem.ajaxUpdateType=this.cbfunc.getUpdateMethod();spin.content(url,[elem,function(){$(document.body).setStyle({"cursor":"default"});}],{"406":this.handleNotAcceptable.bind(this)});}
else{spin.content(url,[function(){$(document.body).setStyle({"cursor":"default"});}],{"406":this.handleNotAcceptable.bind(this)});}},handleNotAcceptable:function(){$(document.body).setStyle({"cursor":"auto"});if(this.cbfunc.specifics){this.cbfunc.specifics.handleNotAcceptable();}},addComponent:function(comptype,compname,compgroup){comptype=comptype.substr(0,3).toUpperCase()+comptype.substr(3);if(!window[comptype]){comptype="WJComponent";}
var id=compname;if(!$(id)){id=compname+"_"+this.cbfunc.getId();}
if(!$(id)&&compgroup!=undefined){id=compgroup+"_"+compname+"_"+this.cbfunc.getId();compname=compgroup+"_"+compname;}
if($(id)){var comp=new window[comptype](compname);comp.setHtmlelement($(id));this.components.push(comp);}}});var WJCBFunctionalityHistoryManager=Class.create({initialize:function(func){this.func=func;if(!ProtoHistoryManager){WJDebugger.log(WJDebugger.WARNING,"Unable to use history manager functionality without prototype.historyManager, will continue without");}
else{this.historyKey=this.func.cb+"-"+this.func.id;this.historyManager=new ProtoHistoryManager();this.history=this.historyManager.register(this.historyKey,[""],function(values){this.recallAction(values[0]);}.bind(this),function(values){if(Object.isString(values[0])){return this.historyKey+"-"+values[0];}
else{return this.historyKey+"-"+$H(values[0]).toQueryString();}}.bind(this),this.historyKey+'-(.+)');this.historyManager.start.bind(this.historyManager).delay(1.5);}},recallAction:function(query){if(query==""){return;}
var query=query.toQueryParams();var action=query.action;delete query.action;this.func.callAction(action,query);},callAction:function(action,data){if(this.history){data.action=action;this.history.setValue(0,data);}}});var WJCBFunctionality=Class.create({initialize:function(id,cb,htmlid,cbdata,collection){this.id=id;this.element=$(htmlid);this.cb=cb;this.actions={};this.cbdata=cbdata;this.collection=collection;this.updateMethod="replaceElement";},createSpecifics:function(){if(window["WJCBFunctionality"+this.cb]){this.specifics=new window["WJCBFunctionality"+this.cb](this);}},getUpdateMethod:function(){return this.updateMethod;},getData:function(key){return this.cbdata[key];},setData:function(key,value){this.cbdata[key]=value;},callAction:function(action,data){var data=data||{};if(data.isTrusted||Object.isFunction(data.stop)){data={};}
if(this.actions[action]){this.actions[action].execute(data);}
if(this.specifics&&this.specifics.callAction){this.specifics.callAction(action,data);}},getId:function(){return this.id;},getElement:function(){return this.element;},addAction:function(name,action){this.actions[name]=action;}});var WJAlbumCB=Class.create({initialize:function(func,properties){this.albumimages=new Array();this.current="";this.effect=null;this.func=func;this.properties=properties||{};if(this.properties.slide){this.viewNextAlbumImage.bind(this).repeat(properties.slide);}},setTransitionEffect:function(effect,properties){var properties=properties||{};this.effect=effect;this.mediaTransition=new WJMediaTransition(properties);this.mediaTransition.setFromElement($(document.body).down(".contentblockalbum_view").down());this.effect.init(this.mediaTransition,{});},registerImage:function(url,title,user,extrainfo){this.albumimages.push({type:"image",url:url,title:title,user:user,extrainfo:extrainfo});},registerVideo:function(url,title,user,extrainfo){this.albumimages.push({type:"video",url:url,title:title,user:user,extrainfo:extrainfo});},setCurrentAlbumimage:function(url){this.current=url;for(var i=0;i<this.albumimages.length;i++){if(this.albumimages[i].url==this.current){for(var id in this.properties.update){if($(id)){$(id).update(this.albumimages[i][this.properties.update[id]]);}}}}},viewAlbumimage:function(url){this.mediaTransition.setToImage(url);this.effect.transit();this.setCurrentAlbumimage(url);if(this.func.specifics.history){this.func.specifics.history.setValue(0,{action:"details","args[thumbsrc]":url});}},viewNextAlbumImage:function(){if(this.effect){for(var i=0;i<this.albumimages.length-1;i++){if(this.albumimages[i].url==this.current){this.viewAlbumimage(this.albumimages[i+1].url);return;}}
this.viewAlbumimage(this.albumimages[0].url);}},viewPreviousAlbumImage:function(){for(var i=1;i<this.albumimages.length;i++){if(this.albumimages[i].url==this.current){this.viewAlbumimage(this.albumimages[i-1].url);return;}}
this.viewAlbumimage(this.albumimages[this.albumimages.length-1].url);}});var WJCBFunctionalityalbum=Class.create(WJCBFunctionalityHistoryManager,{initialize:function($super,func){func.element=$(func.collection+"_container");func.updateMethod="replaceContent";$super(func);}});var WJCBFunctionalityform=Class.create({initialize:function(func){this.func=func;},handleNotAcceptable:function(){if($(this.func.id+"_missing")){$(this.func.id+"_missing").setStyle({"display":"block"});}}});var WJCBFunctionalitynewsletter=Class.create({initialize:function(func){this.func=func;},handleNotAcceptable:function(){if($(this.func.id+"_missing")){$(this.func.id+"_missing").setStyle({"display":"block"});}}});var WJCBFunctionalityrating=Class.create({initialize:function(func){this.func=func;if(this.func.getElement()){this._attachObservers();this._setDefaults();}},_attachObservers:function(){var fullbar=this._getBar("fullbar")
this._voteObserver=this.vote.bindAsEventListener(this);fullbar.observe("click",this._voteObserver);this._moveObserver=this.mouseMove.bindAsEventListener(this);fullbar.observe("mousemove",this._moveObserver);this._outObserver=this.restoreWidth.bindAsEventListener(this);fullbar.observe("mouseout",this._outObserver);},_getBar:function(className){return this.func.getElement().select("."+className).first();},mouseMove:function(e){var bar=this._getBar("percentage");if(bar){if(this._originalWidth==null){this._originalWidth=bar.getStyle("width");}
var elemloc=bar.cumulativeOffset();var relmouseloc={x:e.pointerX()-elemloc[0],y:e.pointerY()-elemloc[1]};if(relmouseloc.x<this._getBar("fullbar").getWidth()){bar.setStyle({width:relmouseloc.x+"px"});}}},restoreWidth:function(e){var bar=this._getBar("percentage");if(bar&&this._originalWidth!=null){bar.setStyle({width:this._originalWidth});}},_setDefaults:function(){this.func.setData("boundaries",{x:0,y:0,width:this._getBar("fullbar").getWidth(),height:this._getBar("fullbar").getHeight()});},vote:function(e){var elemloc=this._getBar("fullbar").cumulativeOffset();var relclickloc={x:e.pointerX()-elemloc[0],y:e.pointerY()-elemloc[1]};var boundaries=this.func.getData("boundaries");if((relclickloc.x>boundaries.x)&&(relclickloc.x<(boundaries.x+boundaries.width))&&(relclickloc.y>boundaries.y)&&(relclickloc.y<(boundaries.y+boundaries.height))){var limits={min:parseInt(this.func.getData("min")),max:parseInt(this.func.getData("max"))};var stepwidth=boundaries.width/(1+limits.max-limits.min);var vote=Math.ceil((relclickloc.x-boundaries.x)/stepwidth);$("vote_"+this.func.getId()).value=vote;this.func.callAction("vote");this._getBar("fullbar").stopObserving("click",this._voteObserver);this._getBar("fullbar").stopObserving("mousemove",this._moveObserver);this._getBar("fullbar").stopObserving("mouseout",this._outObserver);}}});var WJCBFunctionalityreview=Class.create({initialize:function(func){this.func=func;},handleNotAcceptable:function(){if($(this.func.id+"_missing")){$(this.func.id+"_missing").setStyle({"display":"block"});}}});var WJCBFunctionalitysend=Class.create({initialize:function(func){this.func=func;},handleNotAcceptable:function(){if($(this.func.id+"_missing")){$(this.func.id+"_missing").setStyle({"display":"block"});}}});var WJCBGooglemapsdirections=Class.create({initialize:function(elementid,settings){this._settings=new Hash(settings);$(this._settings.get("from")).hide();$(this._settings.get("submit")).up().hide();this._routeelement=$(elementid);this._mapcanvas=this._routeelement.down(".googlemapscanvas");this._maperrors=this._routeelement.appendChild(new Element("div",{"class":"googlemapsdirectionserror"})).hide();this._printbutton=this._routeelement.appendChild(new Element("a",{"href":"#"})).hide().update(this._settings.get("printlabel")).observe("click",this.print.bindAsEventListener(this));this._mapdirections=this._routeelement.appendChild(new Element("div",{"class":"googlemapsdirections"})).hide();this._map=new GMap2(this._mapcanvas);this._geocoder=new GClientGeocoder();this._geocoder.getLatLng(this._settings.get("to"),this.centerMap.bind(this));this._directions=new GDirections(this._map,this._mapdirections);GEvent.addListener(this._directions,"error",this._displayError.bindAsEventListener(this));GEvent.addListener(this._directions,"load",this._displayDirections.bindAsEventListener(this));this._addControls();this._addPlanObserver();},_displayError:function(){this._maperrors.update(this._settings.get("errortext")).show();this._mapdirections.hide();this._printbutton.hide();},_addPlanObserver:function(){$(this._settings.get("submit")).observe("click",this.planRoute.bindAsEventListener(this));},planRoute:function(event){this._maperrors.update("");var from=$(this._settings.get("from")).down("input").value;this._directions.load("from: "+from+" to: "+this._glatlng.lat()+","+this._glatlng.lng(),this._mapdirections);},_displayDirections:function(event){this._mapdirections.show();},centerMap:function(glatlng){if(glatlng){this._glatlng=glatlng;this._map.setCenter(this._glatlng,parseInt(this._settings.get("zoom")));this._tomarker=new GMarker(this._glatlng);this._map.addOverlay(this._tomarker);this._tomarker.openInfoWindowHtml(this._settings.get("text")+"<div id='searchfields' class='searchfields'>&#160;</div>");GEvent.addListener(this._tomarker,"infowindowopen",function(){$("searchfields").appendChild($(this._settings.get("from"))).show();$("searchfields").appendChild($(this._settings.get("submit")).up()).show();$("searchfields").id=null;}.bindAsEventListener(this));return true;}
return false;},_addControls:function(){this._map.addControl(new GSmallZoomControl());this._map.addControl(new GMapTypeControl());},print:function(event){var from=$(this._settings.get("from")).down("input").value;var directions="from: "+from+" to: "+this._glatlng.lat()+","+this._glatlng.lng();var scriptsrc="<script language='JavaScript' type='text/javascript' src='"+this._settings.get("jssrc")+"'> </script>";var src="<html><head><title>"+this._settings.get("to")+"</title>"+scriptsrc+"</head><body><div id='canvas' style='height: "+this._mapcanvas.getHeight()+"px; width: "+this._mapcanvas.getWidth()+"px;'>&#160;</div><div id='directions'>&#160;</div></body></html>";var script="<script language='JavaScript' type='text/javascript'>";script+="map = new GMap2(document.getElementById('canvas') );";script+="map.setCenter(new GLatLng("+this._glatlng.lat()+","+this._glatlng.lng()+"), "+parseInt(this._settings.get("zoom"))+" );";script+="directions = new GDirections(map, document.getElementById('directions') );";script+="GEvent.addListener(directions, 'load', function() {window.print();});";script+="directions.load('"+directions+"');";script+="</script>";var printwindow=window.open("about:blank","printdialog","scrollbars=yes,height="+(this._mapcanvas.getHeight()+150)+",width="+(this._mapcanvas.getWidth()+40));printwindow.document.write(src);printwindow.document.close()}});var WJCBGooglemaps=Class.create({_overlays:new Hash(),_forms:new Hash(),_filterlists:new Hash(),_selectobservers:new Hash(),_loader:null,initialize:function(elementid,latitude,longitude,zoom,sitename){this._mapelement=$(elementid);this._mapelement.style.backgroundImage="";this._center=new GLatLng(latitude,longitude);this._zoom=zoom;this._sitename=sitename;this._zoomtobounds=false;this._bounds=new GLatLngBounds();this._addpositioncontrol=true;this._positioncontrol=(this._mapelement.getHeight()<300)?new GSmallMapControl:new GLargeMapControl();this._map=new GMap2(this._mapelement);this._map.addMapType(G_PHYSICAL_MAP);var hierarchy=new GHierarchicalMapTypeControl();hierarchy.addRelationship(G_SATELLITE_MAP,G_HYBRID_MAP,null,true);this._addtypecontrol=true;this._typecontrol=hierarchy;this._enabledoubleclickzoom=true;this._enablecontinuouszoom=true;this.currentrequests=0;this.requests=new Array();},setLoader:function(element){this._loader=element;},getLoader:function(){return this._loader;},loaderShowHide:function(){if(this.getLoader()&&Object.isElement(this.getLoader())){if(this.currentrequests>0){this.getLoader().addClassName("maploadershow");}
else{this.getLoader().removeClassName.bind(this.getLoader()).defer("maploadershow");}}},changeSettings:function(settings){for(key in settings){this[key]=settings[key];}},applySettings:function(){this._map.setCenter(this._center,this._zoom);if(this._enabledoubleclickzoom){this._map.enableDoubleClickZoom();}
if(this._enablecontinuouszoom){this._map.enableContinuousZoom();}
if(this._addpositioncontrol){this._map.addControl(this._positioncontrol);}
if(this._addtypecontrol){this._map.addControl(this._typecontrol);}
this._addZoomListener();},_addZoomListener:function(){GEvent.addListener(this._map,"zoomend",function(){this._overlays.findAll(function(overlay){return(typeof(overlay.value.infowindow)!="undefined"&&overlay.value.infowindow.isVisible());}).each(function(overlay){this.positionInfowindowRelativeToMarker(overlay.value);}.bind(this));}.bind(this));},pushOverlay:function(key,overlay,active,parser,filterable,checkable){var active=(active==1)?true:false;this.setOverlay(key,{"baseurl":overlay,"url":overlay,"active":active,"parser":parser,"filterable":filterable,"checkable":checkable});},setOverlay:function(key,value){this._overlays.set(key,value);},getOverlay:function(key){return this._overlays.get(key);},addOverlays:function(readform){var readform=(readform!==false);if(readform){this._fillFormsValues();}
this._overlays.each(function(overlay){if(typeof(overlay.value.geoxml)=="undefined"){this.getNewGeoXml(overlay);}
else if(overlay.value.active){this.addOverlay(overlay)}}.bind(this));},addOverlay:function(overlay){this._map.addOverlay(overlay.value.geoxml);overlay.value.lasturl=overlay.value.url;},getNewGeoXml:function(overlay){if(overlay.value.active){if(overlay.value.parser=="GGeoXml"){overlay.value.geoxml=new GGeoXml(overlay.value.url);this.addOverlay(overlay);}
else{this.parseOverlay(overlay);var handle=GEvent.addListener(overlay.value.geoxml,"parsed",function(overlay){if(overlay.value.active){this.addOverlay(overlay);}
this.currentrequests--;this.loaderShowHide();this.zoomToBounds();GEvent.removeListener(handle);}.bind(this,overlay));}}},hideInfoWindows:function(){this._overlays.findAll(function(overlay){return(typeof(overlay.value.infowindow)!="undefined");}).each(function(overlay){overlay.value.infowindow.hide();});},createInfoWindow:function(overlay,map){var callback=function(wjwindow,event,answer){wjwindow.hide();event.stop();};var infowindow=new WJWindowGooglemaps(new WJWindow(callback,$(map.getPane(G_MAP_FLOAT_PANE))),overlay.key,this._sitename);var infowindowelement=infowindow.getWindowElement();var stopInfowindowEvents=function(event,evtype){var eventelem=Event.findElement(event);if(evtype=="mousedown"){switch(eventelem.tagName.toLowerCase()){case"input":eventelem.focus();case"a":break;default:Event.stop(event);break;}}
else{Event.stop(event);}}
GEvent.bindDom(infowindowelement,"mousedown",this,stopInfowindowEvents.bindAsEventListener(infowindowelement,"mousedown"));GEvent.bindDom(infowindowelement,"dblclick",this,stopInfowindowEvents.bindAsEventListener(infowindowelement,"dblclick"));return infowindow;},removeOverlays:function(){this._overlays.each(function(overlay){if(typeof(overlay.value.geoxml)!="undefined"&&overlay.value.filterable){if(typeof(overlay.value.infowindow)!="undefined"){overlay.value.infowindow.hide();}
this._map.removeOverlay(overlay.value.geoxml);}
if(overlay.value.lasturl!=overlay.value.url&&overlay.value.filterable){this.getNewGeoXml(overlay);}}.bind(this));},removeOverlay:function(key){var overlay=this._overlays.get(key);if(overlay.active){overlay.active=false;this._map.removeOverlay(overlay.geoxml);}},zoomToBounds:function(){if(this._zoomtobounds&&!(this.currentrequests>0)){this._bounds=new GLatLngBounds();this._overlays.each(function(overlay){if(overlay.value.active==true){if(typeof(overlay.value.data.gmarkers)!="undefined"){overlay.value.data.gmarkers.each(function(gmarker){this._bounds.extend(gmarker.getLatLng());}.bind(this));}
if(typeof(overlay.value.data.gpolygons)!="undefined"){overlay.value.data.gpolygons.each(function(gpolygon){var bounds=gpolygon.getBounds();this._bounds.extend(bounds.getNorthEast());this._bounds.extend(bounds.getSouthWest());}.bind(this));}}}.bind(this));if(!this._bounds.isEmpty()){this._map.setZoom(this._map.getBoundsZoomLevel(this._bounds));this._map.setCenter(this._bounds.getCenter());}}},addMainFormObserver:function(elementid){var mainform=$(elementid);mainform.getInputs().each(function(element){$(element).observe("click",function(event){this._handleMainFormChange(event);}.bind(this));}.bind(this));this._mainform=mainform;},addFormObserver:function(formname){var additionalform=$(document.forms[formname]);if(Object.isElement(additionalform)){additionalform.getElements().each(function(element){if(element.tagName.toLowerCase()=="select"){this._selectobservers.set(element.name,Form.Element.getValue(element));}
$(element).observe("click",function(event){var eventelement=Event.findElement(event,"select");if(eventelement!=document&&eventelement){var value=Form.Element.getValue(eventelement);if(value!=this._selectobservers.get(eventelement.name)){this._selectobservers.set(eventelement.name,value);this._handleChange(event);}}
else{this._handleChange(event);}}.bind(this));}.bind(this));Event.observe(additionalform,"submit",this._handleSubmit.bind(this));this.setForm(additionalform.name,additionalform);}},addFilterlistObservers:function(filterlistwrappersid,id,module){var filterwrapper=$(filterlistwrappersid+"_filters");if(filterwrapper){filterwrapper.observe("click",this._handleFilterChange.bindAsEventListener(this));}
var activefilterwrapper=$(filterlistwrappersid+"_activefilters");if(activefilterwrapper){activefilterwrapper.observe("click",this._handleFilterChange.bindAsEventListener(this));}
this._filterlists.set(id,new Hash({filterwrapper:filterwrapper,activefilterwrapper:activefilterwrapper,module:module}));},_handleFilterChange:function(event){if(this.currentrequests>0){this._handleFilterChange.bind(this,event).delay(1);event.stop();}
else{var link=event.findElement("a");if(link){var list=[link.up("ul.filter_filter"),link.up("ul.filter_activefilters")].compact().first();if(list){var filter=Object.toQueryString(link.href.toQueryParams());this._applyFilter(filter);this.redrawOverlays(false);this._updateFilterLists(filter);event.stop();link.fire("filter:changed",{cbgooglemaps:this});}}}},_updateFilterLists:function(filter){this._filterlists.values().each(function(filter,filterinfo){var query=Object.extend({ct:"wmdynamic",dt:"filter",contenttype:"xml","__type":"xml",module:filterinfo.get("module"),"wmtrigger[]":"requestufts",savecriteria:"true","count":1},filter.toQueryParams());new WJSpin().content(new WJUrl(query,"/index.php"),[this._updateFilterListElements.bind(this,filterinfo)]);}.curry(filter),this);},_updateFilterListElements:function(filterinfo,response){filterinfo.get("activefilterwrapper").update("");filterinfo.get("filterwrapper").update("");$A(response.documentElement.childNodes).each(function(listwrapper){if(listwrapper.getAttribute("id")=="activefilters"){if(listwrapper.childNodes[0]){$A(listwrapper.childNodes[0].childNodes).each(function(filtercontent){if(filterinfo.get("activefilterwrapper").ownerDocument.importNode){filtercontent=filterinfo.get("activefilterwrapper").ownerDocument.importNode(filtercontent,true);filterinfo.get("activefilterwrapper").appendChild(filtercontent);}
else if(filtercontent.xml){filterinfo.get("activefilterwrapper").update(filterinfo.get("activefilterwrapper").innerHTML+filtercontent.xml);}
else{filterinfo.get("activefilterwrapper").appendChild(filtercontent);}});}}
else if(listwrapper.getAttribute("id")=="filters"){if(listwrapper.childNodes[0]){$A(listwrapper.childNodes[0].childNodes).each(function(filtercontent){if(filterinfo.get("filterwrapper").ownerDocument.importNode){filtercontent=filterinfo.get("filterwrapper").ownerDocument.importNode(filtercontent,true);filterinfo.get("filterwrapper").appendChild(filtercontent);}
else if(filtercontent.xml){filterinfo.get("filterwrapper").update(filterinfo.get("filterwrapper").innerHTML+filtercontent.xml);}
else{filterinfo.get("filterwrapper").appendChild(filtercontent);}});}}});filterinfo.get("filterwrapper").innerHTML=filterinfo.get("filterwrapper").innerHTML;filterinfo.get("activefilterwrapper").innerHTML=filterinfo.get("activefilterwrapper").innerHTML;},_handleSubmit:function(event){this._handleChange(event);Event.stop(event);},_handleChange:function(event){if(this.currentrequests>0){this._handleChange.bind(this).delay(1,event);}
else{this._fillFormsValues();this.redrawOverlays();}},_fillFormsValues:function(){var filter=this._forms.values().invoke("serialize").join("&");this._applyFilter(filter);},_applyFilter:function(filter){this._overlays.values().each(function(filter,overlay){if(overlay.filterable&&filter!=""){overlay.url=overlay.baseurl+((overlay.baseurl.indexOf("?")==-1)?"?":"&")+filter;}
else{overlay.url=overlay.baseurl;}}.bind(this,filter));},redrawOverlays:function(readform){this.removeOverlays();this.addOverlays(readform);},_handleMainFormChange:function(event){var checkbox=Event.element(event);this.hideInfoWindows();this._overlays.each(function(checkbox,overlay){if(checkbox.name==overlay.key){if(checkbox.checked){overlay.value.active=true;if(typeof(overlay.value.geoxml)=="undefined"){this.getNewGeoXml(overlay);}
else if((overlay.value.url!=overlay.value.lasturl)&&overlay.value.filterable){this.removeOverlay(checkbox.name);this.getNewGeoXml(overlay);}
else{this.addOverlay(overlay);}}
else{this.removeOverlay(checkbox.name);overlay.value.active=false;}}}.bind(this,checkbox));},setForm:function(key,value){this._forms.set(key,value);},getForm:function(key){return this._forms.get(key);},parseOverlay:function(overlay){overlay.value.data={};overlay.value.styles={};overlay.value.geoxml={};overlay.value.geoxml.prototype=new GOverlay();overlay.value.geoxml.initialize=this.addOverlayToMap.bind(this,overlay);overlay.value.geoxml.remove=this.removeOverlayFromMap.bind(this,overlay);overlay.value.geoxml.redraw=this.redrawOverlayOnMap.bind(this,overlay);overlay.value.geoxml.copy=this.copyOverlayOfMap.bind(this,overlay);this.currentrequests++;this.loaderShowHide();this.zoomToBounds();this.stackRequest(overlay);if(this.currentrequests==1){this.downloadKML();}},stackRequest:function(overlay){this.requests.push(overlay);},downloadKML:function(){var overlay=this.requests.shift();if(typeof(overlay)!="undefined"){GDownloadUrl(overlay.value.url,this.handleKMLRequest.bind(this,overlay));}},showInfowindow:function(m,overlayvalue,name,desc,url){overlayvalue.infowindow.setContent(desc);if(m.chkmlClassName!=""){overlayvalue.infowindow.setTheme(m.chkmlClassName);}
overlayvalue.lastmarker=m;if(m.chkmlDirections!=false){this.handleDirections(m,overlayvalue);}
if(typeof(url)!="undefined"){var spincomplete=function(overlayvalue,content){overlayvalue.infowindow.setContent(content);overlayvalue.infowindow.setLoading(false);overlayvalue.infowindow.setHeight(450);var point=this.positionInfowindowRelativeToMarker(overlayvalue);this._map.panTo(this._map.fromDivPixelToLatLng(point));};var spin=new WJSpin();overlayvalue.infowindow.setLoading(true);spin.content(url,[spincomplete.bind(this,overlayvalue)]);}
overlayvalue.infowindow.setHeight("auto");overlayvalue.infowindow.show();var point=this.positionInfowindowRelativeToMarker(overlayvalue);if(typeof(url)=="undefined"){this._map.panTo(this._map.fromDivPixelToLatLng(point));}},handleDirections:function(m,overlayvalue){if(!this._directions){this.createDirections();}
if(typeof(overlayvalue.infowindow.getContentElement("directions"))!="undefined"){overlayvalue.infowindow.removeWindowRow("directions");}
if(m.chkmlDirections!=false){var directionsrow=overlayvalue.infowindow.insertWindowRowBefore("bottom","directions");var directionsrowcontent=overlayvalue.infowindow.getContentElement("directions");directionsrowcontent.update(m.chkmlDirections.getHtml());var formelement=directionsrowcontent.down("form");if(m.chkmlDirections.addTo===false&&m.chkmlDirections.addFrom===true){this._directionsdirection="from";}
else{this._directionsdirection="to";}
formelement.addClassName("infowindowdirection_"+this._directionsdirection);formelement.addClassName("infowindowdirection_hidden");formelement.observe("submit",function(event,formelement,overlayvalue){var formvalues=formelement.serialize(true);var latlng=overlayvalue.lastmarker.getLatLng().toUrlValue();if(this._directionsdirection=="to"){var searchstring="from: "+formvalues.address+" to: "+latlng;}
else{var searchstring="from: "+latlng+" to: "+formvalues.address;}
this._directions.load(searchstring,this._mapdirections);Event.stop(event);}.bindAsEventListener(this,formelement,overlayvalue));formelement.select("a").each(function(formelement,element,key){element.observe("click",function(event,formelement){var eventelem=Event.element(event);if(eventelem.hasClassName("back")){formelement.addClassName("infowindowdirection_hidden");var point=this.positionInfowindowRelativeToMarker(overlayvalue);this._map.panTo(this._map.fromDivPixelToLatLng(point));}
else if(eventelem.hasClassName("link_to")){this._directionsdirection="to";formelement.removeClassName("infowindowdirection_from");formelement.addClassName("infowindowdirection_to");}
else if(eventelem.hasClassName("link_from")){this._directionsdirection="from";formelement.removeClassName("infowindowdirection_to");formelement.addClassName("infowindowdirection_from");}
else if(eventelem.hasClassName("directionsactivator")){formelement.removeClassName("infowindowdirection_hidden");var point=this.positionInfowindowRelativeToMarker(overlayvalue);this._map.panTo(this._map.fromDivPixelToLatLng(point));}}.bindAsEventListener(this,formelement));}.bind(this,formelement));}},createDirections:function(){this._mapdirections=this._mapelement.up().appendChild(new Element("div",{"class":"googlemapsdirections"})).hide();if(Object.isElement($("googlemapsdirectionserror"))){this._directionerrors=$("googlemapsdirectionserror");}
else{this._directionerrors=this._mapelement.up().appendChild(new Element("div",{"class":"googlemapsdirectionserror"}));}
this._directionerrors.hide();this._directions=new GDirections(this._map,this._mapdirections);GEvent.addListener(this._directions,"error",this._displayDirectionsError.bindAsEventListener(this));GEvent.addListener(this._directions,"load",this._displayDirections.bindAsEventListener(this));},_displayDirections:function(event){if(Object.isElement($("googlemapsdirectionserror"))){$("googlemapsdirectionserror").hide();}
else{this._directionerrors.update("");}
this.hideInfoWindows();this._mapdirections.show();},_displayDirectionsError:function(){if(Object.isElement($("googlemapsdirectionserror"))){$("googlemapsdirectionserror").show();}
else{this._directionerrors.update("Route could not be found").show();}
this._mapdirections.hide();},addOverlayToMap:function(overlay,map){WJDebugger.log(WJDebugger.NOTICE,"Adding overlay "+overlay[0],overlay[1]);var data=overlay.value.data;if(typeof(overlay.value.infowindow)=="undefined"){overlay.value.infowindow=this.createInfoWindow(overlay,map);}
this.removeOverlayFromMap(overlay);data.gpolygons=[];data.gpolylines=[];data.gmarkers=[];if(typeof(data.polylines)!="undefined"){data.polylines.each(function(map,overlay,polyline,key){this.createPolyline(polyline,overlay);}.bind(this,map,overlay));}
if(typeof(data.polygons)!="undefined"){data.polygons.each(function(map,overlay,polygon,key){this.createPolygon(polygon,overlay);}.bind(this,map,overlay));}
if(typeof(data.markers)!="undefined"){data.markers.each(function(map,overlay,marker,key){this.createMarker(marker,overlay);}.bind(this,map,overlay));}},removeOverlayFromMap:function(overlay){var data=overlay.value.data;if(typeof(data.gpolylines)!="undefined"){data.gpolylines.each(function(polyline,key){this._map.removeOverlay(polyline);}.bind(this));}
if(typeof(data.gpolygons)!="undefined"){data.gpolygons.each(function(polygon,key){this._map.removeOverlay(polygon);}.bind(this));}
if(typeof(data.gmarkers)!="undefined"){data.gmarkers.each(function(marker,key){this._map.removeOverlay(marker);}.bind(this));}},redrawOverlayOnMap:function(overlay,force){},copyOverlayOfMap:function(){},createMarker:function(data,overlay){var overlayvalue=overlay.value;var point=data.point;var name=data.name;var desc=data.desc;var style=data.styleInfo;var url;if(data.spin!=""){url=new WJUrl(data.spin.toQueryParams(),"/index.php");}
var icon=overlayvalue.styles[style];var marker=new GMarker(point,icon);marker.chkmlClassName=data.chkmlClassName;marker.chkmlDirections=data.chkmlDirections;if(name!=""&&desc!=""){GEvent.addListener(marker,"click",function(m,overlayvalue,name,desc,url){if(m==overlayvalue.lastmarker){overlayvalue.infowindow.show();var point=this.positionInfowindowRelativeToMarker(overlayvalue);this._map.panTo(this._map.fromDivPixelToLatLng(point));}
else{this.hideInfoWindows();overlayvalue.infowindow.setBaseTitle("");overlayvalue.infowindow.setContent("");overlayvalue.infowindow.setBaseTitle(name);var wrapper=new Element("div").update(desc);var contentimages=wrapper.select("img");overlayvalue.infowindow.contentimagescounter=contentimages.size();if(overlayvalue.infowindow.contentimagescounter>0){var countdown=function(event,m,html,iwoptions,name,desc,url){overlayvalue.infowindow.contentimagescounter--;if(overlayvalue.infowindow.contentimagescounter==0){this.showInfowindow(m,overlayvalue,name,wrapper,url);}}.bindAsEventListener(this,m,overlayvalue,name,wrapper,url);contentimages.invoke("observe","load",countdown).invoke("observe","error",countdown);}
else{this.showInfowindow(m,overlayvalue,name,desc,url);}}}.bind(this,marker,overlayvalue,name,desc,url));}
this._map.addOverlay(marker);overlayvalue.data.gmarkers.push(marker);},createPolyline:function(data,overlay){var overlayvalue=overlay.value;var points=data.points;var color=data.color;var width=data.width;var opacity=data.opacity;var pbounds=data.pbounds;var name=data.name;var desc=data.desc;var p=new GPolyline(points,color,width,opacity);this._map.addOverlay(p);overlayvalue.data.gpolylines.push(p);},createPolygon:function(data,overlay){var overlayvalue=overlay.value;var pbounds=data.pbounds;var name=data.name;var desc=data.desc;var p=new GPolygon(data.points,data.color,data.width,data.opacity,data.fillcolor,data.fillopacity);if(name!=""&&desc!=""){GEvent.addListener(p,"click",function(p,pbounds,overlayvalue,name,desc,clicked){this.hideInfoWindows();overlayvalue.infowindow.setBaseTitle("");overlayvalue.infowindow.setContent("");overlayvalue.infowindow.setBaseTitle(name);var wrapper=new Element("div").update(desc);var contentimages=wrapper.select("img");overlayvalue.infowindow.contentimagescounter=contentimages.size();if(overlayvalue.infowindow.contentimagescounter>0){var countdown=function(event,p,pbounds,overlayvalue,name,desc){overlayvalue.infowindow.contentimagescounter--;if(overlayvalue.infowindow.contentimagescounter==0){this.positionInfowindowRelativeToPoint(overlayvalue,clicked);overlayvalue.infowindow.setContent(wrapper);overlayvalue.infowindow.show();this._map.panTo(clicked);}}.bindAsEventListener(this,p,pbounds,overlayvalue,name,wrapper);contentimages.invoke("observe","load",countdown).invoke("observe","error",countdown);}
else{this.positionInfowindowRelativeToPoint(overlayvalue,clicked);overlayvalue.infowindow.setContent(wrapper);overlayvalue.infowindow.show();this._map.panTo(clicked);}}.bind(this,p,pbounds,overlayvalue,name,desc));}
overlayvalue.data.gpolygons.push(p);this._map.addOverlay(p);},handleKMLRequest:function(overlay,doc,responseCode){if(responseCode==200){this.processKML(GXml.parse(doc),overlay);}else if(responseCode==-1){WJDebugger.log(WJDebugger.ERROR,"Data request timed out. Please try later.");}else{WJDebugger.log(WJDebugger.ERROR,"Request resulted in error. Check XML file is retrievable.");}
this.downloadKML();},processKML:function(xmlDoc,overlay){if(xmlDoc.text!=""){WJDebugger.log(WJDebugger.NOTICE,"Processing "+overlay[0]+" overlay");overlay.value.styles=this.readStyles(xmlDoc.documentElement.getElementsByTagName("Style"));overlay.value.data=this.readData(xmlDoc.documentElement.getElementsByTagName("Placemark"),overlay.value.styles);overlay.value.groundoverlays=this.readGroundOverlays(xmlDoc.documentElement.getElementsByTagName("GroundOverlay"));GEvent.trigger(overlay.value.geoxml,"parsed");WJDebugger.log(WJDebugger.NOTICE,"Processed "+overlay[0]+" overlay");}},readData:function(placemarks,styles){var data={};data.polylines=[];data.polygons=[];data.markers=[];for(var i=0;i<placemarks.length;i++){var chkmlClassName="";var name=this.readKMLValue(placemarks[i].getElementsByTagName("name")[0]);var desc=this.readKMLValue(placemarks[i].getElementsByTagName("description")[0]);if(typeof(placemarks[i].getElementsByTagNameNS)!="undefined"){var spin=this.readKMLValue(placemarks[i].getElementsByTagNameNS("http://www.connectholland.nl/kml/","spin")[0]);}
else{var spin=this.readKMLValue(placemarks[i].getElementsByTagName("chkml:spin").item(0));}
var style=this.readKMLValue(placemarks[i].getElementsByTagName("styleUrl")[0]);var coords=GXml.value(placemarks[i].getElementsByTagName("coordinates")[0]);coords=coords.replace(/\s+/g," ");coords=coords.replace(/^ /,"");coords=coords.replace(/ $/,"");coords=coords.replace(/, /,",");var path=coords.split(" ");if(path.length>1){var points=[];var pbounds=new GLatLngBounds();for(var p=0;p<path.length-1;p++){var bits=path[p].split(",");if(bits[1]!=""){var point=new GLatLng(parseFloat(bits[1]),parseFloat(bits[0]));points.push(point);this._bounds.extend(point);pbounds.extend(point);}}
var linestring=placemarks[i].getElementsByTagName("LineString");if(linestring.length){if(!!styles[style]){var chkmlClassName=styles[style].chkmlClassName;var width=styles[style].width;var color=styles[style].color;var opacity=styles[style].opacity;}else{var width=5;var color="#0000ff";var opacity=0.45;}
data.polylines.push({points:points,width:width,color:color,opacity:opacity,pbounds:pbounds,name:name,desc:desc,chkmlClassName:chkmlClassName});}
var polygons=placemarks[i].getElementsByTagName("Polygon");if(polygons.length){if(!!styles[style]){var chkmlClassName=styles[style].chkmlClassName;var width=styles[style].width;var color=styles[style].color;var opacity=styles[style].opacity;var fillopacity=styles[style].fillopacity;var fillcolor=styles[style].fillcolor;}else{var width=5;var color="#0000ff";var opacity=0.45;var fillopacity=0.25;var fillcolor="#0055ff";}
data.polygons.push({points:points,color:color,width:width,opacity:opacity,fillcolor:fillcolor,fillopacity:fillopacity,pbounds:pbounds,name:name,desc:desc,chkmlClassName:chkmlClassName});}}else{var bits=path[0].split(",");if(!!styles[style]){var chkmlClassName=styles[style].chkmlClassName;}
var chkmlDirections=this.readDirections(placemarks[i]);if(bits[1]!=""&&typeof(bits[1])!="undefined"){var point=new GLatLng(parseFloat(bits[1]),parseFloat(bits[0]));this._bounds.extend(point);data.markers.push({point:point,name:name,desc:desc,styleInfo:style,spin:spin,chkmlClassName:chkmlClassName,chkmlDirections:chkmlDirections});}}}
return data;},readDirections:function(placemark){if(typeof(placemark.getElementsByTagNameNS)!="undefined"){var directionsnode=placemark.getElementsByTagNameNS("http://www.connectholland.nl/kml/","directions")[0];}
else{var directionsnode=placemark.getElementsByTagName("chkml:directions").item(0);}
if(!directionsnode){return false;}
var html=this.readKMLValue(directionsnode);var addTo=(directionsnode.getAttribute("to")=="true");var addFrom=(directionsnode.getAttribute("from")=="true");return{getHtml:function(){return html;},addTo:addTo,addFrom:addFrom}},readGroundOverlays:function(grounds){var parsedGroundOverlays=[];for(var i=0;i<grounds.length;i++){var url=this.readKMLValue(grounds[i].getElementsByTagName("href")[0]);var north=parseFloat(this.readKMLValue(grounds[i].getElementsByTagName("north")[0]));var south=parseFloat(this.readKMLValue(grounds[i].getElementsByTagName("south")[0]));var east=parseFloat(this.readKMLValue(grounds[i].getElementsByTagName("east")[0]));var west=parseFloat(this.readKMLValue(grounds[i].getElementsByTagName("west")[0]));var sw=new GLatLng(south,west);var ne=new GLatLng(north,east);var ground=new GGroundOverlay(url,new GLatLngBounds(sw,ne));this._bounds.extend(sw);this._bounds.extend(ne);parsedGroundOverlays.push(ground);}
return parsedGroundOverlays;},readStyles:function(styles){var parsedStyles={};for(var i=0;i<styles.length;i++){var styleID=styles[i].getAttribute("id");var iconstyle=styles[i].getElementsByTagName("IconStyle");var iconsizeX=32;var iconsizeY=32;var shadowWidth=59;var scale=1;if(iconstyle.length>0){var scalestyle=iconstyle[0].getElementsByTagName("scale");if(scalestyle.length>0){var scale=this.readKMLValue(scalestyle[0]);var iconsizeX=iconsizeX*scale;var iconsizeY=iconsizeY*scale;var shadowWidth=shadowWidth*scale;}
var anchorX=iconsizeX*0.5;var anchorY=iconsizeY;var iwanchorX=iconsizeX*0.5;var iwanchorY=0;var hotspot=iconstyle[0].getElementsByTagName("hotSpot");if(hotspot.length>0){var hotspotpos=this.calculateHotSpot(hotspot[0],iconsizeX,iconsizeY,anchorX,anchorY);anchorX=hotspotpos.x;anchorY=hotspotpos.y;}
if(typeof(iconstyle[0].getElementsByTagNameNS)!="undefined"){var iwhotspot=iconstyle[0].getElementsByTagNameNS("http://www.connectholland.nl/kml/","infowindowHotSpot");var chkmlClassName=this.readKMLValue(iconstyle[0].getElementsByTagNameNS("http://www.connectholland.nl/kml/","infowindowClassName")[0]);var imagemapnode=iconstyle[0].getElementsByTagNameNS("http://www.connectholland.nl/kml/","area");}
else{var iwhotspot=iconstyle[0].getElementsByTagName("chkml:infowindowHotSpot");var chkmlClassName=this.readKMLValue(iconstyle[0].getElementsByTagName("chkml:infowindowClassName").item(0));}
if(iwhotspot.length>0){var iwhotspotpos=this.calculateHotSpot(iwhotspot[0],iconsizeX,iconsizeY,iwanchorX,iwanchorY);iwanchorX=iwhotspotpos.x;iwanchorY=iwhotspotpos.y;}
if((typeof(imagemapnode)!="undefined")&&(imagemapnode.length>0)){var imageMapType=imagemapnode.item(0).getAttribute("shape");var imageMap=imagemapnode.item(0).getAttribute("coords").split(",");}}
var icons=styles[i].getElementsByTagName("Icon");if(icons.length>0){var href=this.readKMLValue(icons[0].getElementsByTagName("href")[0]);if(!!href){var basehref=href.replace(/\.(png|gif)$/i,"");parsedStyles["#"+styleID]=new GIcon(G_DEFAULT_ICON,href);parsedStyles["#"+styleID].iconSize=new GSize(iconsizeX,iconsizeY);parsedStyles["#"+styleID].shadowSize=new GSize(shadowWidth,iconsizeY);parsedStyles["#"+styleID].iconAnchor=new GPoint(anchorX,anchorY);parsedStyles["#"+styleID].dragCrossAnchor=new GPoint(2,8);parsedStyles["#"+styleID].infoWindowAnchor=new GPoint(iwanchorX,iwanchorY);parsedStyles["#"+styleID].shadow=basehref+"-shadow.png";parsedStyles["#"+styleID].printImage=basehref+".gif";parsedStyles["#"+styleID].mozPrintImage=basehref+".gif";if(typeof(imagemapnode)!="undefined"){parsedStyles["#"+styleID].imageMapType=imageMapType;parsedStyles["#"+styleID].imageMap=imageMap;}}}
var linestyles=styles[i].getElementsByTagName("LineStyle");if(linestyles.length>0){var width=parseInt(this.readKMLValue(linestyles[0].getElementsByTagName("width")[0]));if(width<1){width=5;}
var color=this.readKMLValue(linestyles[0].getElementsByTagName("color")[0]);var opacity=parseInt(color.substr(0,2),16)/256;color="#"+color.substr(6,2)+color.substr(4,2)+color.substr(2,2);if(!parsedStyles["#"+styleID]){parsedStyles["#"+styleID]={};}
parsedStyles["#"+styleID].color=color;parsedStyles["#"+styleID].width=width;parsedStyles["#"+styleID].opacity=opacity;}
var polystyles=styles[i].getElementsByTagName("PolyStyle");if(polystyles.length>0){if(!parsedStyles["#"+styleID]){parsedStyles["#"+styleID]={};}
var fill=parseInt(GXml.value(polystyles[0].getElementsByTagName("fill")[0]));if(polystyles[0].getElementsByTagName("fill").length==0){fill=1;}
var outline=parseInt(GXml.value(polystyles[0].getElementsByTagName("outline")[0]));if(polystyles[0].getElementsByTagName("outline").length==0){outline=1;}
var color=this.readKMLValue(polystyles[0].getElementsByTagName("color")[0]);var opacity=parseInt(color.substr(0,2),16)/256;color="#"+color.substr(6,2)+color.substr(4,2)+color.substr(2,2);parsedStyles["#"+styleID].fillcolor=color;parsedStyles["#"+styleID].fillopacity=opacity;if(!fill){parsedStyles["#"+styleID].fillopacity=0;}
if(!outline){parsedStyles["#"+styleID].opacity=0;}}
parsedStyles["#"+styleID].chkmlClassName=chkmlClassName;}
return parsedStyles;},calculateHotSpot:function(hotspot,iconsizeX,iconsizeY,anchorX,anchorY){var xunits=hotspot.getAttribute("xunits");var yunits=hotspot.getAttribute("yunits");var xval=hotspot.getAttribute("x");var yval=hotspot.getAttribute("y");var anchorX=(xunits=="fraction")?(iconsizeX*xval):anchorX;var anchorX=(xunits=="pixels")?xval:anchorX;var anchorX=(xunits=="insetPixels")?(iconsizeX-xval):anchorX;var anchorY=(yunits=="fraction")?(iconsizeY*yval):anchorY;var anchorY=(yunits=="pixels")?yval:anchorY;var anchorY=(yunits=="insetPixels")?(iconsizeY-yval):anchorY;return{x:anchorX,y:anchorY};},readKMLValue:function(node){return GXml.value(node).replace(/^\s*/,"").replace(/\s*$/,"");},positionInfowindowRelativeToMarker:function(overlayvalue){if(typeof(overlayvalue.lastmarker)=="undefined"){return;}
var fullheight=overlayvalue.infowindow.getFullHeight();if(fullheight>this._map.getContainer().getHeight()){var newheight=overlayvalue.infowindow.getContentHeight()-(fullheight-this._map.getContainer().getHeight());fullheight=overlayvalue.infowindow.setHeight(newheight,null,false).getFullHeight();}
var p=this._map.fromLatLngToDivPixel(overlayvalue.lastmarker.getLatLng());var icon=overlayvalue.lastmarker.getIcon();var halfwidth=(overlayvalue.infowindow.getWidth()/2);var offsety=(icon.iconAnchor.y-icon.infoWindowAnchor.y);p.y-=offsety;p.x-=(icon.iconAnchor.x-icon.infoWindowAnchor.x);p.y-=fullheight;p.x-=halfwidth;overlayvalue.infowindow.setX(p.x);overlayvalue.infowindow.setY(p.y);overlayvalue.infowindow.getPushpinWindowConnectorElement().setStyle({"left":((halfwidth+overlayvalue.infowindow.getStyleSetting("pushpinwindowconnector-left"))-offsety)+"px"});var newy=p.y+((overlayvalue.infowindow.getFullHeight()+icon.iconSize.height)/2);var newx=p.x+halfwidth;return new GPoint(newx,newy);},positionInfowindowRelativeToPoint:function(overlayvalue,point){var p=this._map.fromLatLngToDivPixel(point);var halfwidth=(overlayvalue.infowindow.getWidth()/2);p.y-=overlayvalue.infowindow.getFullHeight();p.x-=halfwidth;overlayvalue.infowindow.setX(p.x);overlayvalue.infowindow.setY(p.y);overlayvalue.infowindow.getPushpinWindowConnectorElement().setStyle({"left":(halfwidth+overlayvalue.infowindow.getStyleSetting("pushpinwindowconnector-left"))+"px"});var newy=p.y;var newx=p.x+halfwidth;return new GPoint(newx,newy);}});var WJChapCB=Class.create({initialize:function(chapid,chaptarget){this._chapid=chapid;this._target=$(chaptarget);this._load();},_load:function(){var spin=new WJSpin();var url=new WJUrl({"ct":"wmdynamic","blockid":this._chapid,"module":"Wmchapblock","wmtrigger[]":["requestufts"],"uft[]":["sideblock"]});spin.content(url,[this._target,this.updateBlock.bind(this)]);},updateBlock:function(response){if(this._target){var title=this._target.select(".chap_rsstitle").first();if(title){this._target.up(".chap_block").select(".chap_title .chap_content h1").first().update(title.innerHTML);}
var icon=this._target.select(".chap_rssicon").first();if(icon){this._target.up(".chap_block").select(".chap_title .chap_content .chap_icon").first().update(icon.innerHTML);}}}});var WJImageBannerCB=Class.create({initialize:function(img,newsrc){img=$(img);if(img.tagName.toLowerCase()!="img"){if(img.down("img")){img=img.down("img");}
else{img=false;}}
if(!img){return;}
this._img=img;var src=this._img.src;src=src.replace(/(^[^\/]+\/\/[^\/]+\/)/,"/");this._basepath="";var basepath=src.match(/(\/images\/thumbs(\/__[^\/]*)*)\/?/);if(basepath){this._basepath=basepath[1];src=src.replace(/(^([^\/]+\/\/[^\/]+)?\/images\/thumbs(\/+__[^\/]*)*)\/*/,"/");}
this._src=src;this._newsrc=newsrc;this._newimg=new Image();Event.observe(this._newimg,"load",function(){this._img.observe("mouseover",this.swap.bindAsEventListener(this,this._newsrc));this._img.observe("mouseout",this.swap.bindAsEventListener(this,this._src));}.bind(this));this._newimg.src=this._basepath+this._newsrc;},swap:function(event,src){this._img.src=this._basepath+src;}});var WJTransition=Class.create({initialize:function(){},init:function(elementTransition,properties){this.elementTransition=elementTransition;this.properties=this._getProperties(properties);},_getProperties:function(properties){return properties;},transit:function(){var from=this.elementTransition.getFromElement();var to=this.elementTransition.getToElement();if(from&&to){this._doTransition(from,to);}
else{WJDebugger.log(WJDebugger.ERROR,"Transition not ready, to and from should both be set but at least one isn't, logging both, to first then from",to,from);}
this.elementTransition.notifyDone();},_doTransition:function(from,to){from.replace(to);}});var WJElementTransition=Class.create({initialize:function(properties){var properties=properties||{};this.properties=this._getProperties(properties);},_getProperties:function(properties){return properties;},setFromElement:function(from){this.from=from;},setToElement:function(to){this.to=to;},getFromElement:function(from){return this.from},getToElement:function(to){return this.to;},notifyDone:function(){this.from=this.to;}});var WJBackgroundImage=Class.create();WJBackgroundImage.prototype={_started:false,initialize:function(backgroundimage,element){if(Object.isString(backgroundimage)&&!backgroundimage.strip().empty()){this.backgroundimage=backgroundimage;this.element=element||document.body;this.sizeelement=element||document.viewport;Element.extend(this.element);Event.observe(window,"resize",this.resizeImage.bindAsEventListener(this),false);this._started=true;}
else{WJDebugger.log(WJDebugger.ERROR,"Trying to run",this,"without a source, you have to overwrite the backgroundImageImgSrc template in your UFT");}},toString:function(){return"WJBackgroundImage";},resizeImage:function(resize_x,resize_y){if(this._started){var sizeelement=this.sizeelement.getDimensions();var height=(sizeelement.height-(sizeelement.height%25))+25+100;var width=(sizeelement.width-(sizeelement.width%25))+25;var image=new Image();Event.observe(image,"load",this.setBackgroundImage.bindAsEventListener(this,image));Event.observe(image,"error",this.noBackgroundImage.bindAsEventListener(this,image));if(resize_x&&resize_y){image.src="/images/thumbs/__rw"+width+"h"+height+this.backgroundimage;}
else if(resize_x&&!resize_y){image.src="/images/thumbs/__lw"+width+"h"+(height+3000)+this.backgroundimage;}
else if(!resize_x&&resize_y){image.src="/images/thumbs/__lw"+(width+5000)+"h"+height+this.backgroundimage;}
else{image.src="/images/thumbs/"+this.backgroundimage;}}},setBackgroundImage:function(event,image){WJDebugger.log(WJDebugger.INFO,"Adding a backgroundimage",image,"to",this.element);this.element.setStyle({backgroundImage:"url(\""+image.src+"\")"});},noBackgroundImage:function(event,image){WJDebugger.log(WJDebugger.ERROR,"Trying to add a backgroundimage that doesn't exist",image,event);}};var WJMediaTransition=Class.create(WJElementTransition,{initialize:function($super,properties){$super(properties);},_getProperties:function(properties){var defaults={width:500,height:500,background:"ffffff",backgroundResize:true,crop:false};for(var key in defaults){var properties_keys=Object.keys(properties);if(properties_keys.include(key)){defaults[key]=properties[key];}}
return defaults;},_getOperations:function(){var sizeinfo="w"+this.properties.width+"h"+this.properties.height;if(this.properties.backgroundResize){return"__bc"+this.properties.background+sizeinfo;}
else if(this.properties.crop){return"__r"+sizeinfo+"/__c"+sizeinfo;}
else{return"__l"+sizeinfo;}},setToImage:function(image){this.setToElement(new Element("img",{src:"/images/thumbs/"+this._getOperations()+image}));},setToVideo:function(video){this.setToElement(new Element("img",{src:"/images/thumbs/"+this._getOperations()+video+".png"}));}});var WJTransitionAppear=Class.create(WJTransition,{initialize:function(){},_doTransition:function(from,to){to.setStyle({"display":"none"});from.up().insert(to);from.up().setStyle({"height":from.getHeight()+"px"});Effect.Fade(from,{duration:1});Effect.Appear.bind(Effect,to).delay(1);from.remove.bind(from).delay(1.5);}});var WJTransitionBlind=Class.create(WJTransition,{initialize:function(){},_doTransition:function(from,to){to.setStyle({"display":"none"});from.up().insert(to);Effect.BlindUp(from,{duration:1});Effect.BlindDown.bind(Effect,to).delay(1);from.remove.bind(from).delay(1);}});
