String.prototype.parseColor=function(){var color='#';if(this.slice(0,4)=='rgb('){var cols=this.slice(4,this.length-1).split(',');var i=0;do{color+=parseInt(cols[i]).toColorPart()}while(++i<3);}else{if(this.slice(0,1)=='#'){if(this.length==4)for(var i=1;i<4;i++)color+=(this.charAt(i)+this.charAt(i)).toLowerCase();if(this.length==7)color=this.toLowerCase();}}
return(color.length==7?color:(arguments[0]||this));};Element.collectTextNodes=function(element){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:(node.hasChildNodes()?Element.collectTextNodes(node):''));}).flatten().join('');};Element.collectTextNodesIgnoreClass=function(element,className){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:((node.hasChildNodes()&&!Element.hasClassName(node,className))?Element.collectTextNodesIgnoreClass(node,className):''));}).flatten().join('');};Element.setContentZoom=function(element,percent){element=$(element);element.setStyle({fontSize:(percent/100)+'em'});if(Prototype.Browser.WebKit)window.scrollBy(0,0);return element;};Element.getInlineOpacity=function(element){return $(element).style.opacity||'';};Element.forceRerendering=function(element){try{element=$(element);var n=document.createTextNode(' ');element.appendChild(n);element.removeChild(n);}catch(e){}};var Effect={_elementDoesNotExistError:{name:'ElementDoesNotExistError',message:'The specified DOM element does not exist, but is required for this effect to operate'},Transitions:{linear:Prototype.K,sinoidal:function(pos){return(-Math.cos(pos*Math.PI)/2)+.5;},reverse:function(pos){return 1-pos;},flicker:function(pos){var pos=((-Math.cos(pos*Math.PI)/4)+.75)+Math.random()/4;return pos>1?1:pos;},wobble:function(pos){return(-Math.cos(pos*Math.PI*(9*pos))/2)+.5;},pulse:function(pos,pulses){return(-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2)+.5;},spring:function(pos){return 1-(Math.cos(pos*4.5*Math.PI)*Math.exp(-pos*6));},none:function(pos){return 0;},full:function(pos){return 1;}},DefaultOptions:{duration:1.0,fps:100,sync:false,from:0.0,to:1.0,delay:0.0,queue:'parallel'},tagifyText:function(element){var tagifyStyle='position:relative';if(Prototype.Browser.IE)tagifyStyle+=';zoom:1';element=$(element);$A(element.childNodes).each(function(child){if(child.nodeType==3){child.nodeValue.toArray().each(function(character){element.insertBefore(new Element('span',{style:tagifyStyle}).update(character==' '?String.fromCharCode(160):character),child);});Element.remove(child);}});},multiple:function(element,effect){var elements;if(((typeof element=='object')||Object.isFunction(element))&&(element.length))
elements=element;else
elements=$(element).childNodes;var options=Object.extend({speed:0.1,delay:0.0},arguments[2]||{});var masterDelay=options.delay;$A(elements).each(function(element,index){new effect(element,Object.extend(options,{delay:index*options.speed+masterDelay}));});},PAIRS:{'slide':['SlideDown','SlideUp'],'blind':['BlindDown','BlindUp'],'appear':['Appear','Fade']},toggle:function(element,effect){element=$(element);effect=(effect||'appear').toLowerCase();var options=Object.extend({queue:{position:'end',scope:(element.id||'global'),limit:1}},arguments[2]||{});Effect[element.visible()?Effect.PAIRS[effect][1]:Effect.PAIRS[effect][0]](element,options);}};Effect.DefaultOptions.transition=Effect.Transitions.sinoidal;Effect.ScopedQueue=Class.create(Enumerable,{initialize:function(){this.effects=[];this.interval=null;},_each:function(iterator){this.effects._each(iterator);},add:function(effect){var timestamp=new Date().getTime();var position=Object.isString(effect.options.queue)?effect.options.queue:effect.options.queue.position;switch(position){case'front':this.effects.findAll(function(e){return e.state=='idle'}).each(function(e){e.startOn+=effect.finishOn;e.finishOn+=effect.finishOn;});break;case'with-last':timestamp=this.effects.pluck('startOn').max()||timestamp;break;case'end':timestamp=this.effects.pluck('finishOn').max()||timestamp;break;}
effect.startOn+=timestamp;effect.finishOn+=timestamp;if(!effect.options.queue.limit||(this.effects.length<effect.options.queue.limit))
this.effects.push(effect);if(!this.interval)
this.interval=setInterval(this.loop.bind(this),15);},remove:function(effect){this.effects=this.effects.reject(function(e){return e==effect});if(this.effects.length==0){clearInterval(this.interval);this.interval=null;}},loop:function(){var timePos=new Date().getTime();for(var i=0,len=this.effects.length;i<len;i++)
this.effects[i]&&this.effects[i].loop(timePos);}});Effect.Queues={instances:$H(),get:function(queueName){if(!Object.isString(queueName))return queueName;return this.instances.get(queueName)||this.instances.set(queueName,new Effect.ScopedQueue());}};Effect.Queue=Effect.Queues.get('global');Effect.Base=Class.create({position:null,start:function(options){function codeForEvent(options,eventName){return((options[eventName+'Internal']?'this.options.'+eventName+'Internal(this);':'')+
(options[eventName]?'this.options.'+eventName+'(this);':''));}
if(options&&options.transition===false)options.transition=Effect.Transitions.linear;this.options=Object.extend(Object.extend({},Effect.DefaultOptions),options||{});this.currentFrame=0;this.state='idle';this.startOn=this.options.delay*1000;this.finishOn=this.startOn+(this.options.duration*1000);this.fromToDelta=this.options.to-this.options.from;this.totalTime=this.finishOn-this.startOn;this.totalFrames=this.options.fps*this.options.duration;this.render=(function(){function dispatch(effect,eventName){if(effect.options[eventName+'Internal'])
effect.options[eventName+'Internal'](effect);if(effect.options[eventName])
effect.options[eventName](effect);}
return function(pos){if(this.state==="idle"){this.state="running";dispatch(this,'beforeSetup');if(this.setup)this.setup();dispatch(this,'afterSetup');}
if(this.state==="running"){pos=(this.options.transition(pos)*this.fromToDelta)+this.options.from;this.position=pos;dispatch(this,'beforeUpdate');if(this.update)this.update(pos);dispatch(this,'afterUpdate');}};})();this.event('beforeStart');if(!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).add(this);},loop:function(timePos){if(timePos>=this.startOn){if(timePos>=this.finishOn){this.render(1.0);this.cancel();this.event('beforeFinish');if(this.finish)this.finish();this.event('afterFinish');return;}
var pos=(timePos-this.startOn)/this.totalTime,frame=(pos*this.totalFrames).round();if(frame>this.currentFrame){this.render(pos);this.currentFrame=frame;}}},cancel:function(){if(!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).remove(this);this.state='finished';},event:function(eventName){if(this.options[eventName+'Internal'])this.options[eventName+'Internal'](this);if(this.options[eventName])this.options[eventName](this);},inspect:function(){var data=$H();for(property in this)
if(!Object.isFunction(this[property]))data.set(property,this[property]);return'#<Effect:'+data.inspect()+',options:'+$H(this.options).inspect()+'>';}});Effect.Parallel=Class.create(Effect.Base,{initialize:function(effects){this.effects=effects||[];this.start(arguments[1]);},update:function(position){this.effects.invoke('render',position);},finish:function(position){this.effects.each(function(effect){effect.render(1.0);effect.cancel();effect.event('beforeFinish');if(effect.finish)effect.finish(position);effect.event('afterFinish');});}});Effect.Tween=Class.create(Effect.Base,{initialize:function(object,from,to){object=Object.isString(object)?$(object):object;var args=$A(arguments),method=args.last(),options=args.length==5?args[3]:null;this.method=Object.isFunction(method)?method.bind(object):Object.isFunction(object[method])?object[method].bind(object):function(value){object[method]=value};this.start(Object.extend({from:from,to:to},options||{}));},update:function(position){this.method(position);}});Effect.Event=Class.create(Effect.Base,{initialize:function(){this.start(Object.extend({duration:0},arguments[0]||{}));},update:Prototype.emptyFunction});Effect.Opacity=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});var options=Object.extend({from:this.element.getOpacity()||0.0,to:1.0},arguments[1]||{});this.start(options);},update:function(position){this.element.setOpacity(position);}});Effect.Move=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({x:0,y:0,mode:'relative'},arguments[1]||{});this.start(options);},setup:function(){this.element.makePositioned();this.originalLeft=parseFloat(this.element.getStyle('left')||'0');this.originalTop=parseFloat(this.element.getStyle('top')||'0');if(this.options.mode=='absolute'){this.options.x=this.options.x-this.originalLeft;this.options.y=this.options.y-this.originalTop;}},update:function(position){this.element.setStyle({left:(this.options.x*position+this.originalLeft).round()+'px',top:(this.options.y*position+this.originalTop).round()+'px'});}});Effect.MoveBy=function(element,toTop,toLeft){return new Effect.Move(element,Object.extend({x:toLeft,y:toTop},arguments[3]||{}));};Effect.Scale=Class.create(Effect.Base,{initialize:function(element,percent){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({scaleX:true,scaleY:true,scaleContent:true,scaleFromCenter:false,scaleMode:'box',scaleFrom:100.0,scaleTo:percent},arguments[2]||{});this.start(options);},setup:function(){this.restoreAfterFinish=this.options.restoreAfterFinish||false;this.elementPositioning=this.element.getStyle('position');this.originalStyle={};['top','left','width','height','fontSize'].each(function(k){this.originalStyle[k]=this.element.style[k];}.bind(this));this.originalTop=this.element.offsetTop;this.originalLeft=this.element.offsetLeft;var fontSize=this.element.getStyle('font-size')||'100%';['em','px','%','pt'].each(function(fontSizeType){if(fontSize.indexOf(fontSizeType)>0){this.fontSize=parseFloat(fontSize);this.fontSizeType=fontSizeType;}}.bind(this));this.factor=(this.options.scaleTo-this.options.scaleFrom)/100;this.dims=null;if(this.options.scaleMode=='box')
this.dims=[this.element.offsetHeight,this.element.offsetWidth];if(/^content/.test(this.options.scaleMode))
this.dims=[this.element.scrollHeight,this.element.scrollWidth];if(!this.dims)
this.dims=[this.options.scaleMode.originalHeight,this.options.scaleMode.originalWidth];},update:function(position){var currentScale=(this.options.scaleFrom/100.0)+(this.factor*position);if(this.options.scaleContent&&this.fontSize)
this.element.setStyle({fontSize:this.fontSize*currentScale+this.fontSizeType});this.setDimensions(this.dims[0]*currentScale,this.dims[1]*currentScale);},finish:function(position){if(this.restoreAfterFinish)this.element.setStyle(this.originalStyle);},setDimensions:function(height,width){var d={};if(this.options.scaleX)d.width=width.round()+'px';if(this.options.scaleY)d.height=height.round()+'px';if(this.options.scaleFromCenter){var topd=(height-this.dims[0])/2;var leftd=(width-this.dims[1])/2;if(this.elementPositioning=='absolute'){if(this.options.scaleY)d.top=this.originalTop-topd+'px';if(this.options.scaleX)d.left=this.originalLeft-leftd+'px';}else{if(this.options.scaleY)d.top=-topd+'px';if(this.options.scaleX)d.left=-leftd+'px';}}
this.element.setStyle(d);}});Effect.Highlight=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({startcolor:'#ffff99'},arguments[1]||{});this.start(options);},setup:function(){if(this.element.getStyle('display')=='none'){this.cancel();return;}
this.oldStyle={};if(!this.options.keepBackgroundImage){this.oldStyle.backgroundImage=this.element.getStyle('background-image');this.element.setStyle({backgroundImage:'none'});}
if(!this.options.endcolor)
this.options.endcolor=this.element.getStyle('background-color').parseColor('#ffffff');if(!this.options.restorecolor)
this.options.restorecolor=this.element.getStyle('background-color');this._base=$R(0,2).map(function(i){return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16)}.bind(this));this._delta=$R(0,2).map(function(i){return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i]}.bind(this));},update:function(position){this.element.setStyle({backgroundColor:$R(0,2).inject('#',function(m,v,i){return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart());}.bind(this))});},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}));}});Effect.ScrollTo=function(element){var options=arguments[1]||{},scrollOffsets=document.viewport.getScrollOffsets(),elementOffsets=$(element).cumulativeOffset();if(options.offset)elementOffsets[1]+=options.offset;return new Effect.Tween(null,scrollOffsets.top,elementOffsets[1],options,function(p){scrollTo(scrollOffsets.left,p.round());});};Effect.Fade=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();var options=Object.extend({from:element.getOpacity()||1.0,to:0.0,afterFinishInternal:function(effect){if(effect.options.to!=0)return;effect.element.hide().setStyle({opacity:oldOpacity});}},arguments[1]||{});return new Effect.Opacity(element,options);};Effect.Appear=function(element){element=$(element);var options=Object.extend({from:(element.getStyle('display')=='none'?0.0:element.getOpacity()||0.0),to:1.0,afterFinishInternal:function(effect){effect.element.forceRerendering();},beforeSetup:function(effect){effect.element.setOpacity(effect.options.from).show();}},arguments[1]||{});return new Effect.Opacity(element,options);};Effect.Puff=function(element){element=$(element);var oldStyle={opacity:element.getInlineOpacity(),position:element.getStyle('position'),top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};return new Effect.Parallel([new Effect.Scale(element,200,{sync:true,scaleFromCenter:true,scaleContent:true,restoreAfterFinish:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:1.0,beforeSetupInternal:function(effect){Position.absolutize(effect.effects[0].element);},afterFinishInternal:function(effect){effect.effects[0].element.hide().setStyle(oldStyle);}},arguments[1]||{}));};Effect.BlindUp=function(element){element=$(element);element.makeClipping();return new Effect.Scale(element,0,Object.extend({scaleContent:false,scaleX:false,restoreAfterFinish:true,afterFinishInternal:function(effect){effect.element.hide().undoClipping();}},arguments[1]||{}));};Effect.BlindDown=function(element){element=$(element);var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:0,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makeClipping().setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.element.undoClipping();}},arguments[1]||{}));};Effect.SwitchOff=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();return new Effect.Appear(element,Object.extend({duration:0.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(effect){new Effect.Scale(effect.element,1,{duration:0.3,scaleFromCenter:true,scaleX:false,scaleContent:false,restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned().setStyle({opacity:oldOpacity});}});}},arguments[1]||{}));};Effect.DropOut=function(element){element=$(element);var oldStyle={top:element.getStyle('top'),left:element.getStyle('left'),opacity:element.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(element,{x:0,y:100,sync:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:0.5,beforeSetup:function(effect){effect.effects[0].element.makePositioned();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);}},arguments[1]||{}));};Effect.Shake=function(element){element=$(element);var options=Object.extend({distance:20,duration:0.5},arguments[1]||{});var distance=parseFloat(options.distance);var split=parseFloat(options.duration)/10.0;var oldStyle={top:element.getStyle('top'),left:element.getStyle('left')};return new Effect.Move(element,{x:distance,y:0,duration:split,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance,y:0,duration:split,afterFinishInternal:function(effect){effect.element.undoPositioned().setStyle(oldStyle);}});}});}});}});}});}});};Effect.SlideDown=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().setStyle({height:'0px'}).show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));};Effect.SlideUp=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:'box',scaleFrom:100,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));};Effect.Squish=function(element){return new Effect.Scale(element,window.opera?1:0,{restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping();}});};Effect.Grow=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var initialMoveX,initialMoveY;var moveX,moveY;switch(options.direction){case'top-left':initialMoveX=initialMoveY=moveX=moveY=0;break;case'top-right':initialMoveX=dims.width;initialMoveY=moveY=0;moveX=-dims.width;break;case'bottom-left':initialMoveX=moveX=0;initialMoveY=dims.height;moveY=-dims.height;break;case'bottom-right':initialMoveX=dims.width;initialMoveY=dims.height;moveX=-dims.width;moveY=-dims.height;break;case'center':initialMoveX=dims.width/2;initialMoveY=dims.height/2;moveX=-dims.width/2;moveY=-dims.height/2;break;}
return new Effect.Move(element,{x:initialMoveX,y:initialMoveY,duration:0.01,beforeSetup:function(effect){effect.element.hide().makeClipping().makePositioned();},afterFinishInternal:function(effect){new Effect.Parallel([new Effect.Opacity(effect.element,{sync:true,to:1.0,from:0.0,transition:options.opacityTransition}),new Effect.Move(effect.element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition}),new Effect.Scale(effect.element,100,{scaleMode:{originalHeight:dims.height,originalWidth:dims.width},sync:true,scaleFrom:window.opera?1:0,transition:options.scaleTransition,restoreAfterFinish:true})],Object.extend({beforeSetup:function(effect){effect.effects[0].element.setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);}},options));}});};Effect.Shrink=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var moveX,moveY;switch(options.direction){case'top-left':moveX=moveY=0;break;case'top-right':moveX=dims.width;moveY=0;break;case'bottom-left':moveX=0;moveY=dims.height;break;case'bottom-right':moveX=dims.width;moveY=dims.height;break;case'center':moveX=dims.width/2;moveY=dims.height/2;break;}
return new Effect.Parallel([new Effect.Opacity(element,{sync:true,to:0.0,from:1.0,transition:options.opacityTransition}),new Effect.Scale(element,window.opera?1:0,{sync:true,transition:options.scaleTransition,restoreAfterFinish:true}),new Effect.Move(element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition})],Object.extend({beforeStartInternal:function(effect){effect.effects[0].element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle);}},options));};Effect.Pulsate=function(element){element=$(element);var options=arguments[1]||{},oldOpacity=element.getInlineOpacity(),transition=options.transition||Effect.Transitions.linear,reverser=function(pos){return 1-transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2)+.5);};return new Effect.Opacity(element,Object.extend(Object.extend({duration:2.0,from:0,afterFinishInternal:function(effect){effect.element.setStyle({opacity:oldOpacity});}},options),{transition:reverser}));};Effect.Fold=function(element){element=$(element);var oldStyle={top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};element.makeClipping();return new Effect.Scale(element,5,Object.extend({scaleContent:false,scaleX:false,afterFinishInternal:function(effect){new Effect.Scale(element,1,{scaleContent:false,scaleY:false,afterFinishInternal:function(effect){effect.element.hide().undoClipping().setStyle(oldStyle);}});}},arguments[1]||{}));};Effect.Morph=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({style:{}},arguments[1]||{});if(!Object.isString(options.style))this.style=$H(options.style);else{if(options.style.include(':'))
this.style=options.style.parseStyle();else{this.element.addClassName(options.style);this.style=$H(this.element.getStyles());this.element.removeClassName(options.style);var css=this.element.getStyles();this.style=this.style.reject(function(style){return style.value==css[style.key];});options.afterFinishInternal=function(effect){effect.element.addClassName(effect.options.style);effect.transforms.each(function(transform){effect.element.style[transform.style]='';});};}}
this.start(options);},setup:function(){function parseColor(color){if(!color||['rgba(0, 0, 0, 0)','transparent'].include(color))color='#ffffff';color=color.parseColor();return $R(0,2).map(function(i){return parseInt(color.slice(i*2+1,i*2+3),16);});}
this.transforms=this.style.map(function(pair){var property=pair[0],value=pair[1],unit=null;if(value.parseColor('#zzzzzz')!='#zzzzzz'){value=value.parseColor();unit='color';}else if(property=='opacity'){value=parseFloat(value);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});}else if(Element.CSS_LENGTH.test(value)){var components=value.match(/^([\+\-]?[0-9\.]+)(.*)$/);value=parseFloat(components[1]);unit=(components.length==3)?components[2]:null;}
var originalValue=this.element.getStyle(property);return{style:property.camelize(),originalValue:unit=='color'?parseColor(originalValue):parseFloat(originalValue||0),targetValue:unit=='color'?parseColor(value):value,unit:unit};}.bind(this)).reject(function(transform){return((transform.originalValue==transform.targetValue)||(transform.unit!='color'&&(isNaN(transform.originalValue)||isNaN(transform.targetValue))));});},update:function(position){var style={},transform,i=this.transforms.length;while(i--)
style[(transform=this.transforms[i]).style]=transform.unit=='color'?'#'+
(Math.round(transform.originalValue[0]+
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart()+
(Math.round(transform.originalValue[1]+
(transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart()+
(Math.round(transform.originalValue[2]+
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart():(transform.originalValue+
(transform.targetValue-transform.originalValue)*position).toFixed(3)+
(transform.unit===null?'':transform.unit);this.element.setStyle(style,true);}});Effect.Transform=Class.create({initialize:function(tracks){this.tracks=[];this.options=arguments[1]||{};this.addTracks(tracks);},addTracks:function(tracks){tracks.each(function(track){track=$H(track);var data=track.values().first();this.tracks.push($H({ids:track.keys().first(),effect:Effect.Morph,options:{style:data}}));}.bind(this));return this;},play:function(){return new Effect.Parallel(this.tracks.map(function(track){var ids=track.get('ids'),effect=track.get('effect'),options=track.get('options');var elements=[$(ids)||$$(ids)].flatten();return elements.map(function(e){return new effect(e,Object.extend({sync:true},options))});}).flatten(),this.options);}});Element.CSS_PROPERTIES=$w('backgroundColor backgroundPosition borderBottomColor borderBottomStyle '+'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth '+'borderRightColor borderRightStyle borderRightWidth borderSpacing '+'borderTopColor borderTopStyle borderTopWidth bottom clip color '+'fontSize fontWeight height left letterSpacing lineHeight '+'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+'maxWidth minHeight minWidth opacity outlineColor outlineOffset '+'outlineWidth paddingBottom paddingLeft paddingRight paddingTop '+'right textIndent top width wordSpacing zIndex');Element.CSS_LENGTH=/^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;String.__parseStyleElement=document.createElement('div');String.prototype.parseStyle=function(){var style,styleRules=$H();if(Prototype.Browser.WebKit)
style=new Element('div',{style:this}).style;else{String.__parseStyleElement.innerHTML='<div style="'+this+'"></div>';style=String.__parseStyleElement.childNodes[0].style;}
Element.CSS_PROPERTIES.each(function(property){if(style[property])styleRules.set(property,style[property]);});if(Prototype.Browser.IE&&this.include('opacity'))
styleRules.set('opacity',this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);return styleRules;};if(document.defaultView&&document.defaultView.getComputedStyle){Element.getStyles=function(element){var css=document.defaultView.getComputedStyle($(element),null);return Element.CSS_PROPERTIES.inject({},function(styles,property){styles[property]=css[property];return styles;});};}else{Element.getStyles=function(element){element=$(element);var css=element.currentStyle,styles;styles=Element.CSS_PROPERTIES.inject({},function(results,property){results[property]=css[property];return results;});if(!styles.opacity)styles.opacity=element.getOpacity();return styles;};}
Effect.Methods={morph:function(element,style){element=$(element);new Effect.Morph(element,Object.extend({style:style},arguments[2]||{}));return element;},visualEffect:function(element,effect,options){element=$(element);var s=effect.dasherize().camelize(),klass=s.charAt(0).toUpperCase()+s.substring(1);new Effect[klass](element,options);return element;},highlight:function(element,options){element=$(element);new Effect.Highlight(element,options);return element;}};$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+'pulsate shake puff squish switchOff dropOut').each(function(effect){Effect.Methods[effect]=function(element,options){element=$(element);Effect[effect.charAt(0).toUpperCase()+effect.substring(1)](element,options);return element;};});$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(function(f){Effect.Methods[f]=Element[f];});Element.addMethods(Effect.Methods);if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");var Droppables={drops:[],remove:function(element){this.drops=this.drops.reject(function(d){return d.element==$(element)});},add:function(element){element=$(element);var options=Object.extend({greedy:true,hoverclass:null,tree:false},arguments[1]||{});if(options.containment){options._containers=[];var containment=options.containment;if(Object.isArray(containment)){containment.each(function(c){options._containers.push($(c))});}else{options._containers.push($(containment));}}
if(options.accept)options.accept=[options.accept].flatten();Element.makePositioned(element);options.element=element;this.drops.push(options);},findDeepestChild:function(drops){deepest=drops[0];for(i=1;i<drops.length;++i)
if(Element.isParent(drops[i].element,deepest.element))
deepest=drops[i];return deepest;},isContained:function(element,drop){var containmentNode;if(drop.tree){containmentNode=element.treeNode;}else{containmentNode=element.parentNode;}
return drop._containers.detect(function(c){return containmentNode==c});},isAffected:function(point,element,drop){return((drop.element!=element)&&((!drop._containers)||this.isContained(element,drop))&&((!drop.accept)||(Element.classNames(element).detect(function(v){return drop.accept.include(v)})))&&Position.within(drop.element,point[0],point[1]));},deactivate:function(drop){if(drop.hoverclass)
Element.removeClassName(drop.element,drop.hoverclass);this.last_active=null;},activate:function(drop){if(drop.hoverclass)
Element.addClassName(drop.element,drop.hoverclass);this.last_active=drop;},show:function(point,element){if(!this.drops.length)return;var drop,affected=[];this.drops.each(function(drop){if(Droppables.isAffected(point,element,drop))
affected.push(drop);});if(affected.length>0)
drop=Droppables.findDeepestChild(affected);if(this.last_active&&this.last_active!=drop)this.deactivate(this.last_active);if(drop){Position.within(drop.element,point[0],point[1]);if(drop.onHover)
drop.onHover(element,drop.element,Position.overlap(drop.overlap,drop.element));if(drop!=this.last_active)Droppables.activate(drop);}},fire:function(event,element){if(!this.last_active)return;Position.prepare();if(this.isAffected([Event.pointerX(event),Event.pointerY(event)],element,this.last_active))
if(this.last_active.onDrop){this.last_active.onDrop(element,this.last_active.element,event);return true;}},reset:function(){if(this.last_active)
this.deactivate(this.last_active);}};var Draggables={drags:[],observers:[],register:function(draggable){if(this.drags.length==0){this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.updateDrag.bindAsEventListener(this);this.eventKeypress=this.keyPress.bindAsEventListener(this);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);Event.observe(document,"keypress",this.eventKeypress);}
this.drags.push(draggable);},unregister:function(draggable){this.drags=this.drags.reject(function(d){return d==draggable});if(this.drags.length==0){Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);Event.stopObserving(document,"keypress",this.eventKeypress);}},activate:function(draggable){if(draggable.options.delay){this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=draggable;}.bind(this),draggable.options.delay);}else{window.focus();this.activeDraggable=draggable;}},deactivate:function(){this.activeDraggable=null;},updateDrag:function(event){if(!this.activeDraggable)return;var pointer=[Event.pointerX(event),Event.pointerY(event)];if(this._lastPointer&&(this._lastPointer.inspect()==pointer.inspect()))return;this._lastPointer=pointer;this.activeDraggable.updateDrag(event,pointer);},endDrag:function(event){if(this._timeout){clearTimeout(this._timeout);this._timeout=null;}
if(!this.activeDraggable)return;this._lastPointer=null;this.activeDraggable.endDrag(event);this.activeDraggable=null;},keyPress:function(event){if(this.activeDraggable)
this.activeDraggable.keyPress(event);},addObserver:function(observer){this.observers.push(observer);this._cacheObserverCallbacks();},removeObserver:function(element){this.observers=this.observers.reject(function(o){return o.element==element});this._cacheObserverCallbacks();},notify:function(eventName,draggable,event){if(this[eventName+'Count']>0)
this.observers.each(function(o){if(o[eventName])o[eventName](eventName,draggable,event);});if(draggable.options[eventName])draggable.options[eventName](draggable,event);},_cacheObserverCallbacks:function(){['onStart','onEnd','onDrag'].each(function(eventName){Draggables[eventName+'Count']=Draggables.observers.select(function(o){return o[eventName];}).length;});}};var Draggable=Class.create({initialize:function(element){var defaults={handle:false,reverteffect:function(element,top_offset,left_offset){var dur=Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:dur,queue:{scope:'_draggable',position:'end'}});},endeffect:function(element){var toOpacity=Object.isNumber(element._opacity)?element._opacity:1.0;new Effect.Opacity(element,{duration:0.2,from:0.7,to:toOpacity,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[element]=false}});},zindex:1000,revert:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults,{starteffect:function(element){element._opacity=Element.getOpacity(element);Draggable._dragging[element]=true;new Effect.Opacity(element,{duration:0.2,from:element._opacity,to:0.7});}});var options=Object.extend(defaults,arguments[1]||{});this.element=$(element);if(options.handle&&Object.isString(options.handle))
this.handle=this.element.down('.'+options.handle,0);if(!this.handle)this.handle=$(options.handle);if(!this.handle)this.handle=this.element;if(options.scroll&&!options.scroll.scrollTo&&!options.scroll.outerHTML){options.scroll=$(options.scroll);this._isScrollChild=Element.childOf(this.element,options.scroll);}
Element.makePositioned(this.element);this.options=options;this.dragging=false;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this);},destroy:function(){Event.stopObserving(this.handle,"mousedown",this.eventMouseDown);Draggables.unregister(this);},currentDelta:function(){return([parseInt(Element.getStyle(this.element,'left')||'0'),parseInt(Element.getStyle(this.element,'top')||'0')]);},initDrag:function(event){if(!Object.isUndefined(Draggable._dragging[this.element])&&Draggable._dragging[this.element])return;if(Event.isLeftClick(event)){var src=Event.element(event);if((tag_name=src.tagName.toUpperCase())&&(tag_name=='INPUT'||tag_name=='SELECT'||tag_name=='OPTION'||tag_name=='BUTTON'||tag_name=='TEXTAREA'))return;var pointer=[Event.pointerX(event),Event.pointerY(event)];var pos=Position.cumulativeOffset(this.element);this.offset=[0,1].map(function(i){return(pointer[i]-pos[i])});Draggables.activate(this);Event.stop(event);}},startDrag:function(event){this.dragging=true;if(!this.delta)
this.delta=this.currentDelta();if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,'z-index')||0);this.element.style.zIndex=this.options.zindex;}
if(this.options.ghosting){this._clone=this.element.cloneNode(true);this._originallyAbsolute=(this.element.getStyle('position')=='absolute');if(!this._originallyAbsolute)
Position.absolutize(this.element);this.element.parentNode.insertBefore(this._clone,this.element);}
if(this.options.scroll){if(this.options.scroll==window){var where=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=where.left;this.originalScrollTop=where.top;}else{this.originalScrollLeft=this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop;}}
Draggables.notify('onStart',this,event);if(this.options.starteffect)this.options.starteffect(this.element);},updateDrag:function(event,pointer){if(!this.dragging)this.startDrag(event);if(!this.options.quiet){Position.prepare();Droppables.show(pointer,this.element);}
Draggables.notify('onDrag',this,event);this.draw(pointer);if(this.options.change)this.options.change(this);if(this.options.scroll){this.stopScrolling();var p;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){p=[left,top,left+width,top+height];}}else{p=Position.page(this.options.scroll);p[0]+=this.options.scroll.scrollLeft+Position.deltaX;p[1]+=this.options.scroll.scrollTop+Position.deltaY;p.push(p[0]+this.options.scroll.offsetWidth);p.push(p[1]+this.options.scroll.offsetHeight);}
var speed=[0,0];if(pointer[0]<(p[0]+this.options.scrollSensitivity))speed[0]=pointer[0]-(p[0]+this.options.scrollSensitivity);if(pointer[1]<(p[1]+this.options.scrollSensitivity))speed[1]=pointer[1]-(p[1]+this.options.scrollSensitivity);if(pointer[0]>(p[2]-this.options.scrollSensitivity))speed[0]=pointer[0]-(p[2]-this.options.scrollSensitivity);if(pointer[1]>(p[3]-this.options.scrollSensitivity))speed[1]=pointer[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(speed);}
if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);},finishDrag:function(event,success){this.dragging=false;if(this.options.quiet){Position.prepare();var pointer=[Event.pointerX(event),Event.pointerY(event)];Droppables.show(pointer,this.element);}
if(this.options.ghosting){if(!this._originallyAbsolute)
Position.relativize(this.element);delete this._originallyAbsolute;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){element=$(element);var s=Sortable.sortables[element.id];if(s){Draggables.removeObserver(s.element);s.droppables.each(function(d){Droppables.remove(d)});s.draggables.invoke('destroy');delete Sortable.sortables[s.element.id];}},create:function(element){element=$(element);var options=Object.extend({element:element,tag:'li',dropOnEmpty:false,tree:false,treeTag:'ul',overlap:'vertical',constraint:'vertical',containment:element,handle:false,only:false,delay:0,hoverclass:null,ghosting:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,format:this.SERIALIZE_RULE,elements:false,handles:false,onChange:Prototype.emptyFunction,onUpdate:Prototype.emptyFunction},arguments[1]||{});this.destroy(element);var options_for_draggable={revert:true,quiet:options.quiet,scroll:options.scroll,scrollSpeed:options.scrollSpeed,scrollSensitivity:options.scrollSensitivity,delay:options.delay,ghosting:options.ghosting,constraint:options.constraint,handle:options.handle};if(options.starteffect)
options_for_draggable.starteffect=options.starteffect;if(options.reverteffect)
options_for_draggable.reverteffect=options.reverteffect;else
if(options.ghosting)options_for_draggable.reverteffect=function(element){element.style.top=0;element.style.left=0;};if(options.endeffect)
options_for_draggable.endeffect=options.endeffect;if(options.zindex)
options_for_draggable.zindex=options.zindex;var options_for_droppable={overlap:options.overlap,containment:options.containment,tree:options.tree,hoverclass:options.hoverclass,onHover:Sortable.onHover};var options_for_tree={onHover:Sortable.onEmptyHover,overlap:options.overlap,containment:options.containment,hoverclass:options.hoverclass};Element.cleanWhitespace(element);options.draggables=[];options.droppables=[];if(options.dropOnEmpty||options.tree){Droppables.add(element,options_for_tree);options.droppables.push(element);}
(options.elements||this.findElements(element,options)||[]).each(function(e,i){var handle=options.handles?$(options.handles[i]):(options.handle?$(e).select('.'+options.handle)[0]:e);options.draggables.push(new Draggable(e,Object.extend(options_for_draggable,{handle:handle})));Droppables.add(e,options_for_droppable);if(options.tree)e.treeNode=element;options.droppables.push(e);});if(options.tree){(Sortable.findTreeElements(element,options)||[]).each(function(e){Droppables.add(e,options_for_tree);e.treeNode=element;options.droppables.push(e);});}
this.sortables[element.id]=options;Draggables.addObserver(new SortableObserver(element,options.onUpdate));},findElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.tag);},findTreeElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.treeTag);},onHover:function(element,dropon,overlap){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(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.scrollHeight});}
Effect.Appear(update,{duration:0.15});};this.options.onHide=this.options.onHide||function(element,update){new Effect.Fade(update,{duration:0.15})};if(typeof(this.options.tokens)=='string')
this.options.tokens=new Array(this.options.tokens);if(!this.options.tokens.include('\n'))
this.options.tokens.push('\n');this.observer=null;this.element.setAttribute('autocomplete','off');Element.hide(this.update);Event.observe(this.element,'blur',this.onBlur.bindAsEventListener(this));Event.observe(this.element,'keydown',this.onKeyPress.bindAsEventListener(this));},show:function(){if(Element.getStyle(this.update,'display')=='none')this.options.onShow(this.element,this.update);if(!this.iefix&&(Prototype.Browser.IE)&&(Element.getStyle(this.update,'position')=='absolute')){new Insertion.After(this.update,'<iframe id="'+this.update.id+'_iefix" '+'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" '+'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');this.iefix=$(this.update.id+'_iefix');}
if(this.iefix)setTimeout(this.fixIEOverlapping.bind(this),50);},fixIEOverlapping:function(){Position.clone(this.update,this.iefix,{setTop:(!this.update.style.height)});this.iefix.style.zIndex=1;this.update.style.zIndex=2;Element.show(this.iefix);},hide:function(){this.stopIndicator();if(Element.getStyle(this.update,'display')!='none')this.options.onHide(this.element,this.update);if(this.iefix)Element.hide(this.iefix);},startIndicator:function(){if(this.options.indicator)Element.show(this.options.indicator);},stopIndicator:function(){if(this.options.indicator)Element.hide(this.options.indicator);},onKeyPress:function(event){if(this.active)
switch(event.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:this.selectEntry();Event.stop(event);case Event.KEY_ESC:this.hide();this.active=false;Event.stop(event);return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:this.markPrevious();this.render();Event.stop(event);return;case Event.KEY_DOWN:this.markNext();this.render();Event.stop(event);return;}
else
if(event.keyCode==Event.KEY_TAB||event.keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&event.keyCode==0))return;this.changed=true;this.hasFocus=true;if(this.observer)clearTimeout(this.observer);this.observer=setTimeout(this.onObserverEvent.bind(this),this.options.frequency*1000);},activate:function(){this.changed=false;this.hasFocus=true;this.getUpdatedChoices();},onHover:function(event){var element=Event.findElement(event,'LI');if(this.index!=element.autocompleteIndex)
{this.index=element.autocompleteIndex;this.render();}
Event.stop(event);},onClick:function(event){var element=Event.findElement(event,'LI');this.index=element.autocompleteIndex;this.selectEntry();this.hide();},onBlur:function(event){setTimeout(this.hide.bind(this),250);this.hasFocus=false;this.active=false;},render:function(){if(this.entryCount>0){for(var i=0;i<this.entryCount;i++)
this.index==i?Element.addClassName(this.getEntry(i),"selected"):Element.removeClassName(this.getEntry(i),"selected");if(this.hasFocus){this.show();this.active=true;}}else{this.active=false;this.hide();}},markPrevious:function(){if(this.index>0)this.index--;else this.index=this.entryCount-1;this.getEntry(this.index).scrollIntoView(true);},markNext:function(){if(this.index<this.entryCount-1)this.index++;else this.index=0;this.getEntry(this.index).scrollIntoView(false);},getEntry:function(index){return this.update.firstChild.childNodes[index];},getCurrentEntry:function(){return this.getEntry(this.index);},selectEntry:function(){this.active=false;this.updateElement(this.getCurrentEntry());},updateElement:function(selectedElement){if(this.options.updateElement){this.options.updateElement(selectedElement);return;}
var value='';if(this.options.select){var nodes=$(selectedElement).select('.'+this.options.select)||[];if(nodes.length>0)value=Element.collectTextNodes(nodes[0],this.options.select);}else
value=Element.collectTextNodesIgnoreClass(selectedElement,'informal');var bounds=this.getTokenBounds();if(bounds[0]!=-1){var newValue=this.element.value.substr(0,bounds[0]);var whitespace=this.element.value.substr(bounds[0]).match(/^\s+/);if(whitespace)
newValue+=whitespace[0];this.element.value=newValue+value+this.element.value.substr(bounds[1]);}else{this.element.value=value;}
this.oldElementValue=this.element.value;this.element.focus();if(this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element,selectedElement);},updateChoices:function(choices){if(!this.changed&&this.hasFocus){this.update.innerHTML=choices;Element.cleanWhitespace(this.update);Element.cleanWhitespace(this.update.down());if(this.update.firstChild&&this.update.down().childNodes){this.entryCount=this.update.down().childNodes.length;for(var i=0;i<this.entryCount;i++){var entry=this.getEntry(i);entry.autocompleteIndex=i;this.addObservers(entry);}}else{this.entryCount=0;}
this.stopIndicator();this.index=0;if(this.entryCount==1&&this.options.autoSelect){this.selectEntry();this.hide();}else{this.render();}}},addObservers:function(element){Event.observe(element,"mouseover",this.onHover.bindAsEventListener(this));Event.observe(element,"click",this.onClick.bindAsEventListener(this));},onObserverEvent:function(){this.changed=false;this.tokenBounds=null;if(this.getToken().length>=this.options.minChars){this.getUpdatedChoices();}else{this.active=false;this.hide();}
this.oldElementValue=this.element.value;},getToken:function(){var bounds=this.getTokenBounds();return this.element.value.substring(bounds[0],bounds[1]).strip();},getTokenBounds:function(){if(null!=this.tokenBounds)return this.tokenBounds;var value=this.element.value;if(value.strip().empty())return[-1,0];var diff=arguments.callee.getFirstDifferencePos(value,this.oldElementValue);var offset=(diff==this.oldElementValue.length?1:0);var prevTokenPos=-1,nextTokenPos=value.length;var tp;for(var index=0,l=this.options.tokens.length;index<l;++index){tp=value.lastIndexOf(this.options.tokens[index],diff+offset-1);if(tp>prevTokenPos)prevTokenPos=tp;tp=value.indexOf(this.options.tokens[index],diff+offset);if(-1!=tp&&tp<nextTokenPos)nextTokenPos=tp;}
return(this.tokenBounds=[prevTokenPos+1,nextTokenPos]);}});Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos=function(newS,oldS){var boundary=Math.min(newS.length,oldS.length);for(var index=0;index<boundary;++index)
if(newS[index]!=oldS[index])
return index;return boundary;};Ajax.Autocompleter=Class.create(Autocompleter.Base,{initialize:function(element,update,url,options){this.baseInitialize(element,update,options);this.options.asynchronous=true;this.options.onComplete=this.onComplete.bind(this);this.options.defaultParams=this.options.parameters||null;this.url=url;},getUpdatedChoices:function(){this.startIndicator();var entry=encodeURIComponent(this.options.paramName)+'='+
encodeURIComponent(this.getToken());this.options.parameters=this.options.callback?this.options.callback(this.element,entry):entry;if(this.options.defaultParams)
this.options.parameters+='&'+this.options.defaultParams;new Ajax.Request(this.url,this.options);},onComplete:function(request){this.updateChoices(request.responseText);}});Autocompleter.Local=Class.create(Autocompleter.Base,{initialize:function(element,update,array,options){this.baseInitialize(element,update,options);this.options.array=array;},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this));},setOptions:function(options){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,ignoreCase:true,fullSearch:false,selector:function(instance){var ret=[];var partial=[];var entry=instance.getToken();var count=0;for(var i=0;i<instance.options.array.length&&ret.length<instance.options.choices;i++){var elem=instance.options.array[i];var foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase()):elem.indexOf(entry);while(foundPos!=-1){if(foundPos==0&&elem.length!=entry.length){ret.push("<li><strong>"+elem.substr(0,entry.length)+"</strong>"+
elem.substr(entry.length)+"</li>");break;}else if(entry.length>=instance.options.partialChars&&instance.options.partialSearch&&foundPos!=-1){if(instance.options.fullSearch||/\s/.test(elem.substr(foundPos-1,1))){partial.push("<li>"+elem.substr(0,foundPos)+"<strong>"+
elem.substr(foundPos,entry.length)+"</strong>"+elem.substr(foundPos+entry.length)+"</li>");break;}}
foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase(),foundPos+1):elem.indexOf(entry,foundPos+1);}}
if(partial.length)
ret=ret.concat(partial.slice(0,instance.options.choices-ret.length));return"<ul>"+ret.join('')+"</ul>";}},options||{});}});Field.scrollFreeActivate=function(field){setTimeout(function(){Field.activate(field);},1);};Ajax.InPlaceEditor=Class.create({initialize:function(element,url,options){this.url=url;this.element=element=$(element);this.prepareOptions();this._controls={};arguments.callee.dealWithDeprecatedOptions(options);Object.extend(this.options,options||{});if(!this.options.formId&&this.element.id){this.options.formId=this.element.id+'-inplaceeditor';if($(this.options.formId))
this.options.formId='';}
if(this.options.externalControl)
this.options.externalControl=$(this.options.externalControl);if(!this.options.externalControl)
this.options.externalControlOnly=false;this._originalBackground=this.element.getStyle('background-color')||'transparent';this.element.title=this.options.clickToEditText;this._boundCancelHandler=this.handleFormCancellation.bind(this);this._boundComplete=(this.options.onComplete||Prototype.emptyFunction).bind(this);this._boundFailureHandler=this.handleAJAXFailure.bind(this);this._boundSubmitHandler=this.handleFormSubmission.bind(this);this._boundWrapperHandler=this.wrapUp.bind(this);this.registerListeners();},checkForEscapeOrReturn:function(e){if(!this._editing||e.ctrlKey||e.altKey||e.shiftKey)return;if(Event.KEY_ESC==e.keyCode)
this.handleFormCancellation(e);else if(Event.KEY_RETURN==e.keyCode)
this.handleFormSubmission(e);},createControl:function(mode,handler,extraClasses){var control=this.options[mode+'Control'];var text=this.options[mode+'Text'];if('button'==control){var btn=document.createElement('input');btn.type='submit';btn.value=text;btn.className='editor_'+mode+'_button';if('cancel'==mode)
btn.onclick=this._boundCancelHandler;this._form.appendChild(btn);this._controls[mode]=btn;}else if('link'==control){var link=document.createElement('a');link.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.unescapeHTML();},handleAJAXFailure:function(transport){this.triggerCallback('onFailure',transport);if(this._oldInnerHTML){this.element.innerHTML=this._oldInnerHTML;this._oldInnerHTML=null;}},handleFormCancellation:function(e){this.wrapUp();if(e)Event.stop(e);},handleFormSubmission:function(e){var form=this._form;var value=$F(this._controls.editor);this.prepareSubmission();var params=this.options.callback(form,value)||'';if(Object.isString(params))
params=params.toQueryParams();params.editorId=this.element.id;if(this.options.htmlResponse){var options=Object.extend({evalScripts:true},this.options.ajaxOptions);Object.extend(options,{parameters:params,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Updater({success:this.element},this.url,options);}else{var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:params,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Request(this.url,options);}
if(e)Event.stop(e);},leaveEditMode:function(){this.element.removeClassName(this.options.savingClassName);this.removeForm();this.leaveHover();this.element.style.backgroundColor=this._originalBackground;this.element.show();if(this.options.externalControl)
this.options.externalControl.show();this._saving=false;this._editing=false;this._oldInnerHTML=null;this.triggerCallback('onLeaveEditMode');},leaveHover:function(e){if(this.options.hoverClassName)
this.element.removeClassName(this.options.hoverClassName);if(this._saving)return;this.triggerCallback('onLeaveHover');},loadExternalText:function(){this._form.addClassName(this.options.loadingClassName);this._controls.editor.disabled=true;var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){this._form.removeClassName(this.options.loadingClassName);var text=transport.responseText;if(this.options.stripLoadedTextTags)
text=text.stripTags();this._controls.editor.value=text;this._controls.editor.disabled=false;this.postProcessEditField();}.bind(this),onFailure:this._boundFailureHandler});new Ajax.Request(this.options.loadTextURL,options);},postProcessEditField:function(){var fpc=this.options.fieldPostCreation;if(fpc)
$(this._controls.editor)['focus'==fpc?'focus':'activate']();},prepareOptions:function(){this.options=Object.clone(Ajax.InPlaceEditor.DefaultOptions);Object.extend(this.options,Ajax.InPlaceEditor.DefaultCallbacks);[this._extraDefaultOptions].flatten().compact().each(function(defs){Object.extend(this.options,defs);}.bind(this));},prepareSubmission:function(){this._saving=true;this.removeForm();this.leaveHover();this.showSaving();},registerListeners:function(){this._listeners={};var listener;$H(Ajax.InPlaceEditor.Listeners).each(function(pair){listener=this[pair.value].bind(this);this._listeners[pair.key]=listener;if(!this.options.externalControlOnly)
this.element.observe(pair.key,listener);if(this.options.externalControl)
this.options.externalControl.observe(pair.key,listener);}.bind(this));},removeForm:function(){if(!this._form)return;this._form.remove();this._form=null;this._controls={};},showSaving:function(){this._oldInnerHTML=this.element.innerHTML;this.element.innerHTML=this.options.savingText;this.element.addClassName(this.options.savingClassName);this.element.style.backgroundColor=this._originalBackground;this.element.show();},triggerCallback:function(cbName,arg){if('function'==typeof this.options[cbName]){this.options[cbName](this,arg);}},unregisterListeners:function(){$H(this._listeners).each(function(pair){if(!this.options.externalControlOnly)
this.element.stopObserving(pair.key,pair.value);if(this.options.externalControl)
this.options.externalControl.stopObserving(pair.key,pair.value);}.bind(this));},wrapUp:function(transport){this.leaveEditMode();this._boundComplete(transport,this.element);}});Object.extend(Ajax.InPlaceEditor.prototype,{dispose:Ajax.InPlaceEditor.prototype.destroy});Ajax.InPlaceCollectionEditor=Class.create(Ajax.InPlaceEditor,{initialize:function($super,element,url,options){this._extraDefaultOptions=Ajax.InPlaceCollectionEditor.DefaultOptions;$super(element,url,options);},createEditField:function(){var list=document.createElement('select');list.name=this.options.paramName;list.size=1;this._controls.editor=list;this._collection=this.options.collection||[];if(this.options.loadCollectionURL)
this.loadCollection();else
this.checkForExternalText();this._form.appendChild(this._controls.editor);},loadCollection:function(){this._form.addClassName(this.options.loadingClassName);this.showLoadingText(this.options.loadingCollectionText);var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){var js=transport.responseText.strip();if(!/^\[.*\]$/.test(js))
throw('Server returned an invalid collection representation.');this._collection=eval(js);this.checkForExternalText();}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadCollectionURL,options);},showLoadingText:function(text){this._controls.editor.disabled=true;var tempOption=this._controls.editor.firstChild;if(!tempOption){tempOption=document.createElement('option');tempOption.value='';this._controls.editor.appendChild(tempOption);tempOption.selected=true;}
tempOption.update((text||'').stripScripts().stripTags());},checkForExternalText:function(){this._text=this.getText();if(this.options.loadTextURL)
this.loadExternalText();else
this.buildOptionList();},loadExternalText:function(){this.showLoadingText(this.options.loadingText);var options=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(options,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(transport){this._text=transport.responseText.strip();this.buildOptionList();}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadTextURL,options);},buildOptionList:function(){this._form.removeClassName(this.options.loadingClassName);this._collection=this._collection.map(function(entry){return 2===entry.length?entry:[entry,entry].flatten();});var marker=('value'in this.options)?this.options.value:this._text;var textFound=this._collection.any(function(entry){return entry[0]==marker;}.bind(this));this._controls.editor.update('');var option;this._collection.each(function(entry,index){option=document.createElement('option');option.value=entry[0];option.selected=textFound?entry[0]==marker:0==index;option.appendChild(document.createTextNode(entry[1]));this._controls.editor.appendChild(option);}.bind(this));this._controls.editor.disabled=false;Field.scrollFreeActivate(this._controls.editor);}});Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions=function(options){if(!options)return;function fallback(name,expr){if(name in options||expr===undefined)return;options[name]=expr;};fallback('cancelControl',(options.cancelLink?'link':(options.cancelButton?'button':options.cancelLink==options.cancelButton==false?false:undefined)));fallback('okControl',(options.okLink?'link':(options.okButton?'button':options.okLink==options.okButton==false?false:undefined)));fallback('highlightColor',options.highlightcolor);fallback('highlightEndColor',options.highlightendcolor);};Object.extend(Ajax.InPlaceEditor,{DefaultOptions:{ajaxOptions:{},autoRows:3,cancelControl:'link',cancelText:'cancel',clickToEditText:'Click to edit',externalControl:null,externalControlOnly:false,fieldPostCreation:'activate',formClassName:'inplaceeditor-form',formId:null,highlightColor:'#ffff99',highlightEndColor:'#ffffff',hoverClassName:'',htmlResponse:true,loadingClassName:'inplaceeditor-loading',loadingText:'Loading...',okControl:'button',okText:'ok',paramName:'value',rows:1,savingClassName:'inplaceeditor-saving',savingText:'Saving...',size:0,stripLoadedTextTags:false,submitOnBlur:false,textAfterControls:'',textBeforeControls:'',textBetweenControls:''},DefaultCallbacks:{callback:function(form){return Form.serialize(form);},onComplete:function(transport,element){new Effect.Highlight(element,{startcolor:this.options.highlightColor,keepBackgroundImage:true});},onEnterEditMode:null,onEnterHover:function(ipe){ipe.element.style.backgroundColor=ipe.options.highlightColor;if(ipe._effect)
ipe._effect.cancel();},onFailure:function(transport,ipe){alert('Error communication with the server: '+transport.responseText.stripTags());},onFormCustomization:null,onLeaveEditMode:null,onLeaveHover:function(ipe){ipe._effect=new Effect.Highlight(ipe.element,{startcolor:ipe.options.highlightColor,endcolor:ipe.options.highlightEndColor,restorecolor:ipe._originalBackground,keepBackgroundImage:true});}},Listeners:{click:'enterEditMode',keydown:'checkForEscapeOrReturn',mouseover:'enterHover',mouseout:'leaveHover'}});Ajax.InPlaceCollectionEditor.DefaultOptions={loadingCollectionText:'Loading options...'};Form.Element.DelayedObserver=Class.create({initialize:function(element,delay,callback){this.delay=delay||0.5;this.element=$(element);this.callback=callback;this.timer=null;this.lastValue=$F(this.element);Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));},delayedListener:function(event){if(this.lastValue==$F(this.element))return;if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(this.onTimerEvent.bind(this),this.delay*1000);this.lastValue=$F(this.element);},onTimerEvent:function(){this.timer=null;this.callback(this.element,$F(this.element));}});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)));};});}};(function(d,dp){d.i18n=function(l){return(typeof l=='string')?(l in Date.i18n?Date.i18n[l]:Date.i18n(l.substr(0,l.lastIndexOf('-')))):(l||Date.i18n(navigator.language||navigator.browserLanguage||''));};d.i18n.inherit=function(l,o){l=Date.i18n(l);for(var k in l)if(typeof o[k]=='undefined')o[k]=l[k];return o;};d.i18n['']=d.i18n['en']=d.i18n['en-US']={months:{abbr:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep'],full:['January','February','March','April','May','June','July','August','September','October','November','December']},days:{abbr:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],full:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']},week:{abbr:'Wk',full:'Week'},formats:{dateShort:'dd-MM-yyyy',dateMedium:'MMM d, yyyy',dateLong:'MMMM d, yyyy',timeShort:'HH:mm',timeMedium:'HH:mm',timeLong:'HH:mm:ss',dateTimeShort:'dd-MM-yyyy HH:mm',dateTimeMedium:'MMM d, yyyy HH:mm',dateTimeLong:'EEEE, MMMM d, yyyy HH:mm'},ad:'AD',am:'AM',pm:'PM',gmt:'GMT',z:':',Z:'',fdow:0,mdifw:1};d.i18n['iso']=d.i18n.inherit('en',{Z:':',fdow:1,mdifw:4});d.WEEK=6048e5;d.DAY=864e5;d.HOUR=36e5;d.MINUTE=6e4
d.SECOND=1000;d.today=function(){return new Date().datePart();};dp.clone=function(){return new Date(+this);};dp.datePart=function(){with(this)return new Date(getFullYear(),getMonth(),getDate());};dp.timePart=function(){with(this)return new Date(1970,0,1,getHours(),getMinutes(),getSeconds(),getMilliseconds());};dp.setDay=function(d){with(this)setDate((getDate()-getDay())+d);};dp.getDayOfWeek=function(o){if(typeof o!='number')o=Date.i18n(o).fdow;var d=this.getDay()-o;if(d<0)d+=7;return d+1;};dp.setDayOfWeek=function(d,o){with(this)setDate((getDate()-getDayOfWeek(o))+d);};dp.getDaysInMonth=function(){with(this.clone()){setDate(32);return 32-getDate();}};dp.getDaysInYear=function(){var y=this.getFullYear();return Math.floor((Date.UTC(y+1,0,1)-Date.UTC(y,0,1))/Date.DAY);};dp.getDayOfYear=function(){return Math.floor((this-new Date(this.getFullYear(),0,1))/Date.DAY)+1;};dp.setDayOfYear=function(d){this.setMonth(0,d);};dp.getWeekOfMonth=function(l){l=Date.i18n(l);with(this.clone()){setDate(1);var d=(7-(getDay()-l.fdow))%7;d=(d<l.mdifw)?-d:(7-d);return Math.ceil((this.getDate()+d)/7);}};dp.setWeekOfMonth=function(w,l){l=Date.i18n(l);with(this.clone()){setDate(1);var d=(7-(getDay()-l.fdow))%7;d=(d<l.mdifw)?-d:(7-d);setDate(d);}};dp.getWeekOfYear=function(l){l=Date.i18n(l);with(this.clone()){setMonth(0,1);var d=(7-(getDay()-l.fdow))%7;if(l.mdifw<d)d-=7;setDate(d);var w=Math.ceil((+this-valueOf())/Date.WEEK);return(w<=getWeeksInYear())?w:1;}};dp.setWeekOfYear=function(w,l){l=Date.i18n(l);with(this){setMonth(0,1);var d=(7-(getDay()-l.fdow))%7;if(l.mdifw<d)d-=7;d+=w*7;setDate(d);}};dp.getWeeksInYear=function(){var y=this.getFullYear();return 52+(new Date(y,0,1).getDay()==4||new Date(y,11,31).getDay()==4);};dp.setTimezoneOffset=function(o){with(this)setTime(valueOf()+((getTimezoneOffset()+-o)*Date.MINUTE));};dp.format=function(p,l){var i18n=Date.i18n(l);var d=this;var pad=function(n,l){for(n=String(n),l-=n.length;--l>=0;n='0'+n);return n;};var tz=function(n,s){return((n<0)?'+':'-')+pad(Math.abs(n/60),2)+s+pad(Math.abs(n%60),2);};return p.replace(/([aDdEFGHhKkMmSsWwyZz])\1*|'[^']*'|"[^"]*"/g,function(m){l=m.length;switch(m.charAt(0)){case'a':return(d.getHours()<12)?i18n.am:i18n.pm;case'D':return pad(d.getDayOfYear(),l);case'd':return pad(d.getDate(),l);case'E':return i18n.days[(l>3)?'full':'abbr'][d.getDay()];case'F':return pad(d.getDayOfWeek(i18n),l);case'G':return i18n.ad;case'H':return pad(d.getHours(),l);case'h':return pad(d.getHours()%12||12,l);case'K':return pad(d.getHours()%12,l);case'k':return pad(d.getHours()||24,l);case'M':return(l<3)?pad(d.getMonth()+1,l):i18n.months[(l>3)?'full':'abbr'][d.getMonth()];case'm':return pad(d.getMinutes(),l);case'S':return pad(d.getMilliseconds(),l);case's':return pad(d.getSeconds(),l);case'W':return pad(d.getWeekOfMonth(i18n),l);case'w':return pad(d.getWeekOfYear(i18n),l);case'y':return(l==2)?String(d.getFullYear()).substr(2):pad(d.getFullYear(),l);case'Z':return tz(d.getTimezoneOffset(),i18n.Z);case'z':return i18n.gmt+tz(d.getTimezoneOffset(),i18n.z);case"'":case'"':return m.substr(1,l-2);default:throw new Error('Illegal pattern');}});}
d.parse=function(s,p,l){if(!p)return arguments.callee.original.call(this);var i18n=Date.i18n(l),d=new Date(1970,0,1,0,0,0,0);var pi=0,si=0,i,j,k,c;var num=function(x){if(x)l=x;else if(!/[DdFHhKkMmSsWwy]/.test(p.charAt(pi)))l=Number.MAX_VALUE;for(i=si;--l>=0&&/[0-9]/.test(s.charAt(si));si++);if(i==si)throw 1;return parseInt(s.substring(i,si),10);};var cmp=function(x){if(s.substr(si,x.length).toLowerCase()!=x.toLowerCase())return false;si+=x.length;return true;};var idx=function(x){for(i=x.length;--i>=0;)if(cmp(x[i]))return i+1;return 0;};try{while(pi<p.length){c=p.charAt(l=pi);if(/[aDdEFGHhKkMmSsWwyZz]/.test(c)){while(p.charAt(++pi)==c);l=pi-l;switch(c){case'a':if(cmp(i18n.pm))d.setHours(12+d.getHours());else if(!cmp(i18n.am))throw 2;break;case'D':d.setDayOfYear(num());break;case'd':d.setDate(num());break;case'E':if(i=idx(i18n.days.full))d.setDay(i-1);else if(i=idx(i18n.days.abbr))d.setDay(i-1);else throw 3;break;case'F':d.setDayOfWeek(num(),i18n);break;case'G':if(!cmp(i18n.ad))throw 4;break;case'H':case'k':d.setHours((i=num())<24?i:0);break;case'K':case'h':d.setHours((i=num())<12?i:0);break;case'M':if(l<3)d.setMonth(num()-1);else if(i=idx(i18n.months.full))d.setMonth(i-1);else if(i=idx(i18n.months.abbr))d.setMonth(i-1);else throw 5;break;case'm':d.setMinutes(num());break;case'S':d.setMilliseconds(num());break;case's':d.setSeconds(num());break;case'W':d.setWeekOfMonth(num(),i18n);break;case'w':d.setWeekOfYear(num(),i18n);break;case'y':d.setFullYear((l==2)?2000+num():num());break;case'z':if(!cmp(i18n.gmt))throw 6;case'Z':if(!/[+-]/.test(j=s.charAt(si++)))throw 6;k=num(2)*60;if(!cmp(i18n[c]))throw 7;k+=num(2);d.setTimezoneOffset((j=='+')?-k:k);}}
else if(/["']/.test(c)){while(++pi<p.length&&p.charAt(pi)!=c);if(!cmp(p.substring(l+1,pi++)))throw 8;}
else{while(pi<p.length&&!/[aDdEFGHhKkMmSsWwyZz"']/.test(p.charAt(pi)))pi++;if(!cmp(p.substring(l,pi)))throw 9;}}
return d;}
catch(e){if(e>0)return Number.NaN;throw e;}};d.parse.original=d.parse;})(Date,Date.prototype);var facebook_login=function(){if(redboxOpenedWindowUrl==null){RedBox.close();}
new Ajax.Request('/fb_connect/connect');}
var hs={lang:{cssDirection:'ltr',loadingText:'Loading...',loadingTitle:'Click to cancel',focusTitle:'Click to bring to front',fullExpandTitle:'Expand to actual size (f)',creditsText:'Powered by <i>Highslide JS</i>',creditsTitle:'Go to the Highslide JS homepage',previousText:'Previous',nextText:'Next',moveText:'Move',closeText:'Close',closeTitle:'Close (esc)',resizeTitle:'Resize',playText:'Play',playTitle:'Play slideshow (spacebar)',pauseText:'Pause',pauseTitle:'Pause slideshow (spacebar)',previousTitle:'Previous (arrow left)',nextTitle:'Next (arrow right)',moveTitle:'Move',fullExpandText:'Full size',number:'Image %1 of %2',restoreTitle:'Click to close image, click and drag to move. Use arrow keys for next and previous.'},graphicsDir:'highslide/graphics/',expandCursor:'zoomin.cur',restoreCursor:'zoomout.cur',expandDuration:250,restoreDuration:250,marginLeft:15,marginRight:15,marginTop:15,marginBottom:15,zIndexCounter:1001,loadingOpacity:0.75,allowMultipleInstances:true,numberOfImagesToPreload:5,outlineWhileAnimating:2,outlineStartOffset:3,padToMinWidth:false,fullExpandPosition:'bottom right',fullExpandOpacity:1,showCredits:true,creditsHref:'http://highslide.com/',enableKeyListener:true,openerTagNames:['a','area'],transitions:[],transitionDuration:250,dimmingOpacity:0,dimmingDuration:50,allowWidthReduction:false,allowHeightReduction:true,preserveContent:true,objectLoadTime:'before',cacheAjax:true,anchor:'auto',align:'auto',targetX:null,targetY:null,dragByHeading:true,minWidth:200,minHeight:200,allowSizeReduction:true,outlineType:'drop-shadow',wrapperClassName:'highslide-wrapper',skin:{controls:'<div class="highslide-controls"><ul>'+'<li class="highslide-previous">'+'<a href="#" title="{hs.lang.previousTitle}">'+'<span>{hs.lang.previousText}</span></a>'+'</li>'+'<li class="highslide-play">'+'<a href="#" title="{hs.lang.playTitle}">'+'<span>{hs.lang.playText}</span></a>'+'</li>'+'<li class="highslide-pause">'+'<a href="#" title="{hs.lang.pauseTitle}">'+'<span>{hs.lang.pauseText}</span></a>'+'</li>'+'<li class="highslide-next">'+'<a href="#" title="{hs.lang.nextTitle}">'+'<span>{hs.lang.nextText}</span></a>'+'</li>'+'<li class="highslide-move">'+'<a href="#" title="{hs.lang.moveTitle}">'+'<span>{hs.lang.moveText}</span></a>'+'</li>'+'<li class="highslide-full-expand">'+'<a href="#" title="{hs.lang.fullExpandTitle}">'+'<span>{hs.lang.fullExpandText}</span></a>'+'</li>'+'<li class="highslide-close">'+'<a href="#" title="{hs.lang.closeTitle}" >'+'<span>{hs.lang.closeText}</span></a>'+'</li>'+'</ul></div>',contentWrapper:'<div class="highslide-header"><ul>'+'<li class="highslide-previous">'+'<a href="#" title="{hs.lang.previousTitle}" onclick="return hs.previous(this)">'+'<span>{hs.lang.previousText}</span></a>'+'</li>'+'<li class="highslide-next">'+'<a href="#" title="{hs.lang.nextTitle}" onclick="return hs.next(this)">'+'<span>{hs.lang.nextText}</span></a>'+'</li>'+'<li class="highslide-move">'+'<a href="#" title="{hs.lang.moveTitle}" onclick="return false">'+'<span>{hs.lang.moveText}</span></a>'+'</li>'+'<li class="highslide-close">'+'<a href="#" title="{hs.lang.closeTitle}" onclick="return hs.close(this)">'+'<span>{hs.lang.closeText}</span></a>'+'</li>'+'</ul></div>'+'<div class="highslide-body"></div>'+'<div class="highslide-footer"><div>'+'<span class="highslide-resize" title="{hs.lang.resizeTitle}"><span></span></span>'+'</div></div>'},preloadTheseImages:[],continuePreloading:true,expanders:[],overrides:['allowSizeReduction','useBox','anchor','align','targetX','targetY','outlineType','outlineWhileAnimating','captionId','captionText','captionEval','captionOverlay','headingId','headingText','headingEval','headingOverlay','dragByHeading','autoplay','numberPosition','transitions','dimmingOpacity','width','height','contentId','allowWidthReduction','allowHeightReduction','preserveContent','maincontentId','maincontentText','maincontentEval','objectType','cacheAjax','objectWidth','objectHeight','objectLoadTime','swfOptions','wrapperClassName','minWidth','minHeight','maxWidth','maxHeight','slideshowGroup','easing','easingClose','fadeInOut','src'],overlays:[],idCounter:0,oPos:{x:['leftpanel','left','center','right','rightpanel'],y:['above','top','middle','bottom','below']},mouse:{},headingOverlay:{},captionOverlay:{},swfOptions:{flashvars:{},params:{},attributes:{}},faders:[],slideshows:[],pendingOutlines:{},sleeping:[],preloadTheseAjax:[],cacheBindings:[],cachedGets:{},clones:{},ie:(document.all&&!window.opera),safari:/Safari/.test(navigator.userAgent),geckoMac:/Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent),$:function(id){return document.getElementById(id);},push:function(arr,val){arr[arr.length]=val;},createElement:function(tag,attribs,styles,parent,nopad){var el=document.createElement(tag);if(attribs)hs.setAttribs(el,attribs);if(nopad)hs.setStyles(el,{padding:0,border:'none',margin:0});if(styles)hs.setStyles(el,styles);if(parent)parent.appendChild(el);return el;},setAttribs:function(el,attribs){for(var x in attribs)el[x]=attribs[x];},setStyles:function(el,styles){for(var x in styles){if(hs.ie&&x=='opacity'){if(styles[x]>0.99)el.style.removeAttribute('filter');else el.style.filter='alpha(opacity='+(styles[x]*100)+')';}
else el.style[x]=styles[x];}},ieVersion:function(){var arr=navigator.appVersion.split("MSIE");return arr[1]?parseFloat(arr[1]):null;},getPageSize:function(){var d=document,w=window,iebody=d.compatMode&&d.compatMode!='BackCompat'?d.documentElement:d.body;var b=d.body;var xScroll=(w.innerWidth&&w.scrollMaxX)?w.innerWidth+w.scrollMaxX:Math.max(b.scrollWidth,b.offsetWidth),yScroll=(w.innerHeight&&window.scrollMaxY)?w.innerHeight+w.scrollMaxY:Math.max(b.scrollHeight,b.offsetHeight),pageWidth=hs.ie?iebody.scrollWidth:(d.documentElement.clientWidth||self.innerWidth),pageHeight=hs.ie?Math.max(iebody.scrollHeight,iebody.clientHeight):(d.documentElement.clientHeight||self.innerHeight);var width=hs.ie?iebody.clientWidth:(d.documentElement.clientWidth||self.innerWidth),height=hs.ie?iebody.clientHeight:self.innerHeight;return{pageWidth:Math.max(pageWidth,xScroll),pageHeight:Math.max(pageHeight,yScroll),width:width,height:height,scrollLeft:hs.ie?iebody.scrollLeft:pageXOffset,scrollTop:hs.ie?iebody.scrollTop:pageYOffset}},getPosition:function(el){if(/area/i.test(el.tagName)){var imgs=document.getElementsByTagName('img');for(var i=0;i<imgs.length;i++){var u=imgs[i].useMap;if(u&&u.replace(/^.*?#/,'')==el.parentNode.name){el=imgs[i];break;}}}
var p={x:el.offsetLeft,y:el.offsetTop};while(el.offsetParent){el=el.offsetParent;p.x+=el.offsetLeft;p.y+=el.offsetTop;if(el!=document.body&&el!=document.documentElement){p.x-=el.scrollLeft;p.y-=el.scrollTop;}}
return p;},expand:function(a,params,custom,type){if(!a)a=hs.createElement('a',null,{display:'none'},hs.container);if(typeof a.getParams=='function')return params;if(type=='html'){for(var i=0;i<hs.sleeping.length;i++){if(hs.sleeping[i]&&hs.sleeping[i].a==a){hs.sleeping[i].awake();hs.sleeping[i]=null;return false;}}
hs.hasHtmlExpanders=true;}
try{new hs.Expander(a,params,custom,type);return false;}catch(e){return true;}},htmlExpand:function(a,params,custom){return hs.expand(a,params,custom,'html');},getSelfRendered:function(){return hs.createElement('div',{className:'highslide-html-content',innerHTML:hs.replaceLang(hs.skin.contentWrapper)});},getElementByClass:function(el,tagName,className){var els=el.getElementsByTagName(tagName);for(var i=0;i<els.length;i++){if((new RegExp(className)).test(els[i].className)){return els[i];}}
return null;},replaceLang:function(s){s=s.replace(/\s/g,' ');var re=/{hs\.lang\.([^}]+)\}/g,matches=s.match(re),lang;if(matches)for(var i=0;i<matches.length;i++){lang=matches[i].replace(re,"$1");if(typeof hs.lang[lang]!='undefined')s=s.replace(matches[i],hs.lang[lang]);}
return s;},setClickEvents:function(){var els=document.getElementsByTagName('a');for(var i=0;i<els.length;i++){var type=hs.isUnobtrusiveAnchor(els[i]);if(type&&!els[i].hsHasSetClick){(function(){var t=type;if(hs.fireEvent(hs,'onSetClickEvent',{element:els[i],type:t})){els[i].onclick=(type=='image')?function(){return hs.expand(this)}:function(){return hs.htmlExpand(this,{objectType:t});};}})();els[i].hsHasSetClick=true;}}
if(!hs.pageLoaded)setTimeout(hs.setClickEvents,50);else hs.getAnchors();},isUnobtrusiveAnchor:function(el){if(el.rel=='highslide')return'image';else if(el.rel=='highslide-ajax')return'ajax';else if(el.rel=='highslide-iframe')return'iframe';else if(el.rel=='highslide-swf')return'swf';},getCacheBinding:function(a){for(var i=0;i<hs.cacheBindings.length;i++){if(hs.cacheBindings[i][0]==a){var c=hs.cacheBindings[i][1];hs.cacheBindings[i][1]=c.cloneNode(1);return c;}}
return null;},preloadAjax:function(e){var arr=hs.getAnchors();for(var i=0;i<arr.htmls.length;i++){var a=arr.htmls[i];if(hs.getParam(a,'objectType')=='ajax'&&hs.getParam(a,'cacheAjax'))
hs.push(hs.preloadTheseAjax,a);}
hs.preloadAjaxElement(0);},preloadAjaxElement:function(i){if(!hs.preloadTheseAjax[i])return;var a=hs.preloadTheseAjax[i];var cache=hs.getNode(hs.getParam(a,'contentId'));if(!cache)cache=hs.getSelfRendered();var ajax=new hs.Ajax(a,cache,1);ajax.onError=function(){};ajax.onLoad=function(){hs.push(hs.cacheBindings,[a,cache]);hs.preloadAjaxElement(i+1);};ajax.run();},focusTopmost:function(){var topZ=0,topmostKey=-1;for(var i=0;i<hs.expanders.length;i++){if(hs.expanders[i]){if(hs.expanders[i].wrapper.style.zIndex&&hs.expanders[i].wrapper.style.zIndex>topZ){topZ=hs.expanders[i].wrapper.style.zIndex;topmostKey=i;}}}
if(topmostKey==-1)hs.focusKey=-1;else hs.expanders[topmostKey].focus();},getParam:function(a,param){a.getParams=a.onclick;var p=a.getParams?a.getParams():null;a.getParams=null;return(p&&typeof p[param]!='undefined')?p[param]:(typeof hs[param]!='undefined'?hs[param]:null);},getSrc:function(a){var src=hs.getParam(a,'src');if(src)return src;return a.href;},getNode:function(id){var node=hs.$(id),clone=hs.clones[id],a={};if(!node&&!clone)return null;if(!clone){clone=node.cloneNode(true);clone.id='';hs.clones[id]=clone;return node;}else{return clone.cloneNode(true);}},discardElement:function(d){hs.garbageBin.appendChild(d);hs.garbageBin.innerHTML='';},dim:function(exp){if(!hs.dimmer){hs.dimmer=hs.createElement('div',{className:'highslide-dimming',owner:'',onclick:function(){if(hs.fireEvent(hs,'onDimmerClick'))
hs.close();}},{position:'absolute',left:0},hs.container,true);hs.addEventListener(window,'resize',hs.setDimmerSize);}
hs.dimmer.style.display='';hs.setDimmerSize();hs.dimmer.owner+='|'+exp.key;if(hs.geckoMac&&hs.dimmingGeckoFix)
hs.dimmer.style.background='url('+hs.graphicsDir+'geckodimmer.png)';else
hs.fade(hs.dimmer,0,exp.dimmingOpacity,hs.dimmingDuration);},undim:function(key){if(!hs.dimmer)return;if(typeof key!='undefined')hs.dimmer.owner=hs.dimmer.owner.replace('|'+key,'');if((typeof key!='undefined'&&hs.dimmer.owner!='')||(hs.upcoming&&hs.getParam(hs.upcoming,'dimmingOpacity')))return;if(hs.geckoMac&&hs.dimmingGeckoFix)
hs.setStyles(hs.dimmer,{background:'none',width:0,height:0});else hs.fade(hs.dimmer,hs.dimmingOpacity,0,hs.dimmingDuration,function(){hs.setStyles(hs.dimmer,{display:'none',width:0,height:0});});},setDimmerSize:function(exp){if(!hs.dimmer)return;var page=hs.getPageSize();var h=(hs.ie&&exp&&exp.wrapper)?parseInt(exp.wrapper.style.top)+parseInt(exp.wrapper.style.height)+(exp.outline?exp.outline.offset:0):0;hs.setStyles(hs.dimmer,{width:page.pageWidth+'px',height:Math.max(page.pageHeight,h)+'px'});},transit:function(adj,exp){hs.last=exp=exp||hs.getExpander();try{hs.upcoming=adj;adj.onclick();}catch(e){hs.last=hs.upcoming=null;}
try{if(!adj||exp.transitions[1]!='crossfade')
exp.close();}catch(e){}
return false;},previousOrNext:function(el,op){var exp=hs.getExpander(el),adj=exp.getAdjacentAnchor(op);return hs.transit(adj,exp);},previous:function(el){return hs.previousOrNext(el,-1);},next:function(el){return hs.previousOrNext(el,1);},keyHandler:function(e){if(!e)e=window.event;if(!e.target)e.target=e.srcElement;if(typeof e.target.form!='undefined')return true;if(!hs.fireEvent(hs,'onKeyDown',e))return true;var exp=hs.getExpander();var op=null;switch(e.keyCode){case 70:if(exp)exp.doFullExpand();return true;case 32:op=2;break;case 34:case 39:case 40:op=1;break;case 8:case 33:case 37:case 38:op=-1;break;case 27:case 13:op=0;}
if(op!==null){if(op!=2)hs.removeEventListener(document,window.opera?'keypress':'keydown',hs.keyHandler);if(!hs.enableKeyListener)return true;if(e.preventDefault)e.preventDefault();else e.returnValue=false;if(exp){if(op==0){exp.close();}else if(op==2){if(exp.slideshow)exp.slideshow.hitSpace();}else{if(exp.slideshow)exp.slideshow.pause();hs.previousOrNext(exp.key,op);}
return false;}}
return true;},registerOverlay:function(overlay){hs.push(hs.overlays,overlay);},addSlideshow:function(options){var sg=options.slideshowGroup;if(typeof sg=='object'){for(var i=0;i<sg.length;i++){var o={};for(var x in options)o[x]=options[x];o.slideshowGroup=sg[i];hs.push(hs.slideshows,o);}}else{hs.push(hs.slideshows,options);}},getWrapperKey:function(element,expOnly){var el,re=/^highslide-wrapper-([0-9]+)$/;el=element;while(el.parentNode){if(el.id&&re.test(el.id))return el.id.replace(re,"$1");el=el.parentNode;}
if(!expOnly){el=element;while(el.parentNode){if(el.tagName&&hs.isHsAnchor(el)){for(var key=0;key<hs.expanders.length;key++){var exp=hs.expanders[key];if(exp&&exp.a==el)return key;}}
el=el.parentNode;}}
return null;},getExpander:function(el,expOnly){if(typeof el=='undefined')return hs.expanders[hs.focusKey]||null;if(typeof el=='number')return hs.expanders[el]||null;if(typeof el=='string')el=hs.$(el);return hs.expanders[hs.getWrapperKey(el,expOnly)]||null;},isHsAnchor:function(a){return(a.onclick&&a.onclick.toString().replace(/\s/g,' ').match(/hs.(htmlE|e)xpand/));},reOrder:function(){for(var i=0;i<hs.expanders.length;i++)
if(hs.expanders[i]&&hs.expanders[i].isExpanded)hs.focusTopmost();},fireEvent:function(obj,evt,args){return obj&&obj[evt]?(obj[evt](obj,args)!==false):true;},mouseClickHandler:function(e)
{if(!e)e=window.event;if(e.button>1)return true;if(!e.target)e.target=e.srcElement;var el=e.target;while(el.parentNode&&!(/highslide-(image|move|html|resize)/.test(el.className)))
{el=el.parentNode;}
var exp=hs.getExpander(el);if(exp&&(exp.isClosing||!exp.isExpanded))return true;if(exp&&e.type=='mousedown'){if(e.target.form)return true;var match=el.className.match(/highslide-(image|move|resize)/);if(match){hs.dragArgs={exp:exp,type:match[1],left:exp.x.pos,width:exp.x.size,top:exp.y.pos,height:exp.y.size,clickX:e.clientX,clickY:e.clientY};hs.addEventListener(document,'mousemove',hs.dragHandler);if(e.preventDefault)e.preventDefault();if(/highslide-(image|html)-blur/.test(exp.content.className)){exp.focus();hs.hasFocused=true;}
return false;}
else if(/highslide-html/.test(el.className)&&hs.focusKey!=exp.key){exp.focus();exp.doShowHide('hidden');}}else if(e.type=='mouseup'){hs.removeEventListener(document,'mousemove',hs.dragHandler);if(hs.dragArgs){if(hs.styleRestoreCursor&&hs.dragArgs.type=='image')
hs.dragArgs.exp.content.style.cursor=hs.styleRestoreCursor;var hasDragged=hs.dragArgs.hasDragged;if(!hasDragged&&!hs.hasFocused&&!/(move|resize)/.test(hs.dragArgs.type)){if(hs.fireEvent(exp,'onImageClick'))
exp.close();}
else if(hasDragged||(!hasDragged&&hs.hasHtmlExpanders)){hs.dragArgs.exp.doShowHide('hidden');}
if(hs.dragArgs.exp.releaseMask)
hs.dragArgs.exp.releaseMask.style.display='none';if(hasDragged)hs.fireEvent(hs.dragArgs.exp,'onDrop',hs.dragArgs);if(hasDragged)hs.setDimmerSize(exp);hs.hasFocused=false;hs.dragArgs=null;}else if(/highslide-image-blur/.test(el.className)){el.style.cursor=hs.styleRestoreCursor;}}
return false;},dragHandler:function(e)
{if(!hs.dragArgs)return true;if(!e)e=window.event;var a=hs.dragArgs,exp=a.exp;if(exp.iframe){if(!exp.releaseMask)exp.releaseMask=hs.createElement('div',null,{position:'absolute',width:exp.x.size+'px',height:exp.y.size+'px',left:exp.x.cb+'px',top:exp.y.cb+'px',zIndex:4,background:(hs.ie?'white':'none'),opacity:.01},exp.wrapper,true);if(exp.releaseMask.style.display=='none')
exp.releaseMask.style.display='';}
a.dX=e.clientX-a.clickX;a.dY=e.clientY-a.clickY;var distance=Math.sqrt(Math.pow(a.dX,2)+Math.pow(a.dY,2));if(!a.hasDragged)a.hasDragged=(a.type!='image'&&distance>0)||(distance>(hs.dragSensitivity||5));if(a.hasDragged&&e.clientX>5&&e.clientY>5){if(!hs.fireEvent(exp,'onDrag',a))return false;if(a.type=='resize')exp.resize(a);else{exp.moveTo(a.left+a.dX,a.top+a.dY);if(a.type=='image')exp.content.style.cursor='move';}}
return false;},wrapperMouseHandler:function(e){try{if(!e)e=window.event;var over=/mouseover/i.test(e.type);if(!e.target)e.target=e.srcElement;if(hs.ie)e.relatedTarget=over?e.fromElement:e.toElement;var exp=hs.getExpander(e.target);if(!exp.isExpanded)return;if(!exp||!e.relatedTarget||hs.getExpander(e.relatedTarget,true)==exp||hs.dragArgs)return;hs.fireEvent(exp,over?'onMouseOver':'onMouseOut',e);for(var i=0;i<exp.overlays.length;i++){var o=hs.$('hsId'+exp.overlays[i]);if(o&&o.hideOnMouseOut){var from=over?0:o.opacity,to=over?o.opacity:0;hs.fade(o,from,to);}}}catch(e){}},addEventListener:function(el,event,func){try{el.addEventListener(event,func,false);}catch(e){try{el.detachEvent('on'+event,func);el.attachEvent('on'+event,func);}catch(e){el['on'+event]=func;}}},removeEventListener:function(el,event,func){try{el.removeEventListener(event,func,false);}catch(e){try{el.detachEvent('on'+event,func);}catch(e){el['on'+event]=null;}}},preloadFullImage:function(i){if(hs.continuePreloading&&hs.preloadTheseImages[i]&&hs.preloadTheseImages[i]!='undefined'){var img=document.createElement('img');img.onload=function(){img=null;hs.preloadFullImage(i+1);};img.src=hs.preloadTheseImages[i];}},preloadImages:function(number){if(number&&typeof number!='object')hs.numberOfImagesToPreload=number;var arr=hs.getAnchors();for(var i=0;i<arr.images.length&&i<hs.numberOfImagesToPreload;i++){hs.push(hs.preloadTheseImages,hs.getSrc(arr.images[i]));}
if(hs.outlineType)new hs.Outline(hs.outlineType,function(){hs.preloadFullImage(0)});else
hs.preloadFullImage(0);if(hs.restoreCursor)var cur=hs.createElement('img',{src:hs.graphicsDir+hs.restoreCursor});},init:function(){if(!hs.container){hs.container=hs.createElement('div',{className:'highslide-container'},{position:'absolute',left:0,top:0,width:'100%',zIndex:hs.zIndexCounter,direction:'ltr'},document.body,true);hs.loading=hs.createElement('a',{className:'highslide-loading',title:hs.lang.loadingTitle,innerHTML:hs.lang.loadingText,href:'javascript:;'},{position:'absolute',top:'-9999px',opacity:hs.loadingOpacity,zIndex:1},hs.container);hs.garbageBin=hs.createElement('div',null,{display:'none'},hs.container);hs.clearing=hs.createElement('div',null,{clear:'both',paddingTop:'1px'},null,true);Math.linearTween=function(t,b,c,d){return c*t/d+b;};Math.easeInQuad=function(t,b,c,d){return c*(t/=d)*t+b;};Math.easeInOutQuad=function(t,b,c,d){if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;};for(var x in hs.langDefaults){if(typeof hs[x]!='undefined')hs.lang[x]=hs[x];else if(typeof hs.lang[x]=='undefined'&&typeof hs.langDefaults[x]!='undefined')
hs.lang[x]=hs.langDefaults[x];}
hs.ie6SSL=(hs.ie&&hs.ieVersion()<=6&&location.protocol=='https:');hs.hideSelects=(hs.ie&&hs.ieVersion()<7);hs.hideIframes=((window.opera&&navigator.appVersion<9)||navigator.vendor=='KDE'||(hs.ie&&hs.ieVersion()<5.5));hs.fireEvent(this,'onActivate');}},domReady:function(){hs.isDomReady=true;if(hs.onDomReady)hs.onDomReady();},updateAnchors:function(){var el,els,all=[],images=[],htmls=[],groups={},re;for(var i=0;i<hs.openerTagNames.length;i++){els=document.getElementsByTagName(hs.openerTagNames[i]);for(var j=0;j<els.length;j++){el=els[j];re=hs.isHsAnchor(el);if(re){hs.push(all,el);if(re[0]=='hs.expand')hs.push(images,el);else if(re[0]=='hs.htmlExpand')hs.push(htmls,el);var g=hs.getParam(el,'slideshowGroup')||'none';if(!groups[g])groups[g]=[];hs.push(groups[g],el);}}}
hs.anchors={all:all,groups:groups,images:images,htmls:htmls};return hs.anchors;},getAnchors:function(){return hs.anchors||hs.updateAnchors();},fade:function(el,o,oFinal,dur,fn,i,dir){if(typeof i=='undefined'){if(typeof dur!='number')dur=250;if(dur<25){hs.setStyles(el,{opacity:oFinal});if(fn)fn();return;}
i=hs.faders.length;dir=oFinal>o?1:-1;var step=(25/(dur-dur%25))*Math.abs(o-oFinal);}
o=parseFloat(o);var skip=(el.fade===0||el.fade===false||(el.fade==2&&hs.ie));el.style.visibility=((skip?oFinal:o)<=0)?'hidden':'visible';if(skip||o<0||(dir==1&&o>oFinal)){if(fn)fn();return;}
if(el.fading&&el.fading.i!=i){clearTimeout(hs.faders[el.fading.i]);o=el.fading.o;}
el.fading={i:i,o:o,step:(step||el.fading.step)};el.style.visibility=(o<=0)?'hidden':'visible';hs.setStyles(el,{opacity:o});hs.faders[i]=setTimeout(function(){hs.fade(el,o+el.fading.step*dir,oFinal,null,fn,i,dir);},25);},close:function(el){var exp=hs.getExpander(el);if(exp)exp.close();return false;}};hs.Outline=function(outlineType,onLoad){this.onLoad=onLoad;this.outlineType=outlineType;var v=hs.ieVersion(),tr;this.hasAlphaImageLoader=hs.ie&&v>=5.5&&v<7;if(!outlineType){if(onLoad)onLoad();return;}
hs.init();this.table=hs.createElement('table',{cellSpacing:0},{visibility:'hidden',position:'absolute',borderCollapse:'collapse',width:0},hs.container,true);var tbody=hs.createElement('tbody',null,null,this.table,1);this.td=[];for(var i=0;i<=8;i++){if(i%3==0)tr=hs.createElement('tr',null,{height:'auto'},tbody,true);this.td[i]=hs.createElement('td',null,null,tr,true);var style=i!=4?{lineHeight:0,fontSize:0}:{position:'relative'};hs.setStyles(this.td[i],style);}
this.td[4].className=outlineType+' highslide-outline';this.preloadGraphic();};hs.Outline.prototype={preloadGraphic:function(){var src=hs.graphicsDir+(hs.outlinesDir||"outlines/")+this.outlineType+".png";var appendTo=hs.safari?hs.container:null;this.graphic=hs.createElement('img',null,{position:'absolute',top:'-9999px'},appendTo,true);var pThis=this;this.graphic.onload=function(){pThis.onGraphicLoad();};this.graphic.src=src;},onGraphicLoad:function(){var o=this.offset=this.graphic.width/4,pos=[[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]],dim={height:(2*o)+'px',width:(2*o)+'px'};for(var i=0;i<=8;i++){if(pos[i]){if(this.hasAlphaImageLoader){var w=(i==1||i==7)?'100%':this.graphic.width+'px';var div=hs.createElement('div',null,{width:'100%',height:'100%',position:'relative',overflow:'hidden'},this.td[i],true);hs.createElement('div',null,{filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+this.graphic.src+"')",position:'absolute',width:w,height:this.graphic.height+'px',left:(pos[i][0]*o)+'px',top:(pos[i][1]*o)+'px'},div,true);}else{hs.setStyles(this.td[i],{background:'url('+this.graphic.src+') '+(pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'});}
if(window.opera&&(i==3||i==5))
hs.createElement('div',null,dim,this.td[i],true);hs.setStyles(this.td[i],dim);}}
this.graphic=null;if(hs.pendingOutlines[this.outlineType])hs.pendingOutlines[this.outlineType].destroy();hs.pendingOutlines[this.outlineType]=this;if(this.onLoad)this.onLoad();},setPosition:function(exp,pos,vis){pos=pos||{x:exp.x.pos,y:exp.y.pos,w:exp.x.size+exp.x.p1+exp.x.p2,h:exp.y.size+exp.y.p1+exp.y.p2};if(vis)this.table.style.visibility=(pos.h>=4*this.offset)?'visible':'hidden';hs.setStyles(this.table,{left:(pos.x-this.offset)+'px',top:(pos.y-this.offset)+'px',width:(pos.w+2*(exp.x.cb+this.offset))+'px'});pos.w+=2*(exp.x.cb-this.offset);pos.h+=+2*(exp.y.cb-this.offset);hs.setStyles(this.td[4],{width:pos.w>=0?pos.w+'px':0,height:pos.h>=0?pos.h+'px':0});if(this.hasAlphaImageLoader)this.td[3].style.height=this.td[5].style.height=this.td[4].style.height;},destroy:function(hide){if(hide)this.table.style.visibility='hidden';else hs.discardElement(this.table);}};hs.Dimension=function(exp,dim){this.exp=exp;this.dim=dim;this.ucwh=dim=='x'?'Width':'Height';this.wh=this.ucwh.toLowerCase();this.uclt=dim=='x'?'Left':'Top';this.lt=this.uclt.toLowerCase();this.ucrb=dim=='x'?'Right':'Bottom';this.rb=this.ucrb.toLowerCase();this.p1=this.p2=0;};hs.Dimension.prototype={get:function(key){switch(key){case'loadingPos':return this.tpos+this.tb+(this.t-hs.loading['offset'+this.ucwh])/2;case'loadingPosXfade':return this.pos+this.cb+this.p1+(this.size-hs.loading['offset'+this.ucwh])/2;case'wsize':return this.size+2*this.cb+this.p1+this.p2;case'fitsize':return this.clientSize-this.marginMin-this.marginMax;case'opos':return this.pos-(this.exp.outline?this.exp.outline.offset:0);case'osize':return this.get('wsize')+(this.exp.outline?2*this.exp.outline.offset:0);case'imgPad':return this.imgSize?Math.round((this.size-this.imgSize)/2):0;}},calcBorders:function(){this.cb=(this.exp.content['offset'+this.ucwh]-this.t)/2;this.marginMax=hs['margin'+this.ucrb]+2*this.cb;},calcThumb:function(){this.t=this.exp.el[this.wh]?parseInt(this.exp.el[this.wh]):this.exp.el['offset'+this.ucwh];this.tpos=this.exp.tpos[this.dim];this.tb=(this.exp.el['offset'+this.ucwh]-this.t)/2;if(this.tpos==0){this.tpos=(hs.page[this.wh]/2)+hs.page['scroll'+this.uclt];};},calcExpanded:function(){var exp=this.exp;this.justify='auto';if(exp.align=='center')this.justify='center';else if(new RegExp(this.lt).test(exp.anchor))this.justify=null;else if(new RegExp(this.rb).test(exp.anchor))this.justify='max';this.pos=this.tpos-this.cb+this.tb;this.size=Math.min(this.full,exp['max'+this.ucwh]||this.full);this.minSize=exp.allowSizeReduction?Math.min(exp['min'+this.ucwh],this.full):this.full;if(exp.useBox){this.size=exp[this.wh];this.imgSize=this.full;}
if(this.dim=='x'&&hs.padToMinWidth)this.minSize=exp.minWidth;this.target=exp['target'+this.dim.toUpperCase()];this.marginMin=hs['margin'+this.uclt];this.scroll=hs.page['scroll'+this.uclt];this.clientSize=hs.page[this.wh];},setSize:function(i){var exp=this.exp;if(exp.isImage&&(exp.useBox||hs.padToMinWidth)){this.imgSize=i;this.size=Math.max(this.size,this.imgSize);exp.content.style[this.lt]=this.get('imgPad')+'px';}else
this.size=i;exp.content.style[this.wh]=i+'px';exp.wrapper.style[this.wh]=this.get('wsize')+'px';if(exp.outline)exp.outline.setPosition(exp);if(exp.releaseMask)exp.releaseMask.style[this.wh]=i+'px';if(exp.isHtml){var d=exp.scrollerDiv;if(this.sizeDiff===undefined)
this.sizeDiff=exp.innerContent['offset'+this.ucwh]-d['offset'+this.ucwh];d.style[this.wh]=(this.size-this.sizeDiff)+'px';if(this.dim=='x')exp.mediumContent.style.width='auto';if(exp.body)exp.body.style[this.wh]='auto';}
if(this.dim=='x'&&exp.overlayBox)exp.sizeOverlayBox(true);if(this.dim=='x'&&exp.slideshow&&exp.isImage){if(i==this.full)exp.slideshow.disable('full-expand');else exp.slideshow.enable('full-expand');}},setPos:function(i){this.pos=i;this.exp.wrapper.style[this.lt]=i+'px';if(this.exp.outline)this.exp.outline.setPosition(this.exp);}};hs.Expander=function(a,params,custom,contentType){if(document.readyState&&hs.ie&&!hs.isDomReady){hs.onDomReady=function(){new hs.Expander(a,params,custom,contentType);};return;}
this.a=a;this.custom=custom;this.contentType=contentType||'image';this.isHtml=(contentType=='html');this.isImage=!this.isHtml;hs.continuePreloading=false;this.overlays=[];this.last=hs.last;hs.last=null;hs.init();var key=this.key=hs.expanders.length;for(var i=0;i<hs.overrides.length;i++){var name=hs.overrides[i];this[name]=params&&typeof params[name]!='undefined'?params[name]:hs[name];}
if(!this.src)this.src=a.href;var el=(params&&params.thumbnailId)?hs.$(params.thumbnailId):a;el=this.thumb=el.getElementsByTagName('img')[0]||el;this.thumbsUserSetId=el.id||a.id;if(!hs.fireEvent(this,'onInit'))return true;for(var i=0;i<hs.expanders.length;i++){if(hs.expanders[i]&&hs.expanders[i].a==a&&!(this.last&&this.transitions[1]=='crossfade')){hs.expanders[i].focus();return false;}}
for(var i=0;i<hs.expanders.length;i++){if(hs.expanders[i]&&hs.expanders[i].thumb!=el&&!hs.expanders[i].onLoadStarted){hs.expanders[i].cancelLoading();}}
hs.expanders[this.key]=this;if(!hs.allowMultipleInstances&&!hs.upcoming){if(hs.expanders[key-1])hs.expanders[key-1].close();if(typeof hs.focusKey!='undefined'&&hs.expanders[hs.focusKey])
hs.expanders[hs.focusKey].close();}
this.el=el;this.tpos=hs.getPosition(el);hs.page=hs.getPageSize();var x=this.x=new hs.Dimension(this,'x');x.calcThumb();var y=this.y=new hs.Dimension(this,'y');y.calcThumb();if(/area/i.test(el.tagName))this.getImageMapAreaCorrection(el);this.wrapper=hs.createElement('div',{id:'highslide-wrapper-'+this.key,className:this.wrapperClassName},{visibility:'hidden',position:'absolute',zIndex:hs.zIndexCounter++},null,true);this.wrapper.onmouseover=this.wrapper.onmouseout=hs.wrapperMouseHandler;if(this.contentType=='image'&&this.outlineWhileAnimating==2)
this.outlineWhileAnimating=0;if(!this.outlineType||(this.last&&this.isImage&&this.transitions[1]=='crossfade')){this[this.contentType+'Create']();}else if(hs.pendingOutlines[this.outlineType]){this.connectOutline();this[this.contentType+'Create']();}else{this.showLoading();var exp=this;new hs.Outline(this.outlineType,function(){exp.connectOutline();exp[exp.contentType+'Create']();});}
return true;};hs.Expander.prototype={connectOutline:function(){var o=this.outline=hs.pendingOutlines[this.outlineType];o.table.style.zIndex=this.wrapper.style.zIndex;hs.pendingOutlines[this.outlineType]=null;},showLoading:function(){if(this.onLoadStarted||this.loading)return;this.loading=hs.loading;var exp=this;this.loading.onclick=function(){exp.cancelLoading();};if(!hs.fireEvent(this,'onShowLoading'))return;var exp=this,l=this.x.get('loadingPos')+'px',t=this.y.get('loadingPos')+'px';if(!tgt&&this.last&&this.transitions[1]=='crossfade')
var tgt=this.last;if(tgt){l=tgt.x.get('loadingPosXfade')+'px';t=tgt.y.get('loadingPosXfade')+'px';this.loading.style.zIndex=hs.zIndexCounter++;}
setTimeout(function(){if(exp.loading)hs.setStyles(exp.loading,{left:l,top:t,zIndex:hs.zIndexCounter++})},100);},imageCreate:function(){var exp=this;var img=document.createElement('img');this.content=img;img.onload=function(){if(hs.expanders[exp.key])exp.contentLoaded();};if(hs.blockRightClick)img.oncontextmenu=function(){return false;};img.className='highslide-image';hs.setStyles(img,{visibility:'hidden',display:'block',position:'absolute',maxWidth:'9999px',zIndex:3});img.title=hs.lang.restoreTitle;if(hs.safari)hs.container.appendChild(img);if(hs.ie&&hs.flushImgSize)img.src=null;img.src=this.src;this.showLoading();},htmlCreate:function(){if(!hs.fireEvent(this,'onBeforeGetContent'))return;this.content=hs.getCacheBinding(this.a);if(!this.content)
this.content=hs.getNode(this.contentId);if(!this.content)
this.content=hs.getSelfRendered();this.getInline(['maincontent']);if(this.maincontent){var body=hs.getElementByClass(this.content,'div','highslide-body');if(body)body.appendChild(this.maincontent);this.maincontent.style.display='block';}
hs.fireEvent(this,'onAfterGetContent');this.innerContent=this.content;if(/(swf|iframe)/.test(this.objectType))this.setObjContainerSize(this.innerContent);hs.container.appendChild(this.wrapper);hs.setStyles(this.wrapper,{position:'static',padding:'0 '+hs.marginRight+'px 0 '+hs.marginLeft+'px'});this.content=hs.createElement('div',{className:'highslide-html'},{position:'relative',zIndex:3,overflow:'hidden'},this.wrapper);this.mediumContent=hs.createElement('div',null,null,this.content,1);this.mediumContent.appendChild(this.innerContent);hs.setStyles(this.innerContent,{position:'relative',display:'block',direction:hs.lang.cssDirection||''});if(this.width)this.innerContent.style.width=this.width+'px';if(this.height)this.innerContent.style.height=this.height+'px';if(this.innerContent.offsetWidth<this.minWidth)
this.innerContent.style.width=this.minWidth+'px';if(this.objectType=='ajax'&&!hs.getCacheBinding(this.a)){this.showLoading();var ajax=new hs.Ajax(this.a,this.innerContent);var exp=this;ajax.onLoad=function(){if(hs.expanders[exp.key])exp.contentLoaded();};ajax.onError=function(){location.href=exp.src;};ajax.run();}
else
if(this.objectType=='iframe'&&this.objectLoadTime=='before'){this.writeExtendedContent();}
else
this.contentLoaded();},contentLoaded:function(){try{if(!this.content)return;this.content.onload=null;if(this.onLoadStarted)return;else this.onLoadStarted=true;var x=this.x,y=this.y;if(this.loading){hs.setStyles(this.loading,{top:'-9999px'});this.loading=null;hs.fireEvent(this,'onHideLoading');}
hs.setStyles(this.wrapper,{left:x.tpos+'px',top:y.tpos+'px'});if(this.isImage){x.full=this.content.width;y.full=this.content.height;hs.setStyles(this.content,{width:this.x.t+'px',height:this.y.t+'px'});this.wrapper.appendChild(this.content);hs.container.appendChild(this.wrapper);}else if(this.htmlGetSize)this.htmlGetSize();x.calcBorders();y.calcBorders();this.initSlideshow();this.getOverlays();var ratio=x.full/y.full;x.calcExpanded();this.justify(x);y.calcExpanded();this.justify(y);if(this.isHtml)this.htmlSizeOperations();if(this.overlayBox)this.sizeOverlayBox(0,1);if(this.allowSizeReduction){if(this.isImage)
this.correctRatio(ratio);else this.fitOverlayBox();var ss=this.slideshow;if(ss&&this.last&&ss.controls&&ss.fixedControls){var pos=ss.overlayOptions.position||'',p;for(var dim in hs.oPos)for(var i=0;i<5;i++){p=this[dim];if(pos.match(hs.oPos[dim][i])){p.pos=this.last[dim].pos
+(this.last[dim].p1-p.p1)
+(this.last[dim].size-p.size)*[0,0,.5,1,1][i];if(ss.fixedControls=='fit'){if(p.pos+p.size+p.p1+p.p2>p.scroll+p.clientSize-p.marginMax)
p.pos=p.scroll+p.clientSize-p.size-p.marginMin-p.marginMax-p.p1-p.p2;if(p.pos<p.scroll+p.marginMin)p.pos=p.scroll+p.marginMin;}}}}
if(this.isImage&&this.x.full>(this.x.imgSize||this.x.size)){this.createFullExpand();if(this.overlays.length==1)this.sizeOverlayBox();}}
this.show();}catch(e){alert('Exception: '+e+'\nStack trace: '+e.stack);}},setObjContainerSize:function(parent,auto){var c=hs.getElementByClass(parent,'DIV','highslide-body');if(/(iframe|swf)/.test(this.objectType)){if(this.objectWidth)c.style.width=this.objectWidth+'px';if(this.objectHeight)c.style.height=this.objectHeight+'px';}},writeExtendedContent:function(){if(this.hasExtendedContent)return;var exp=this;this.body=hs.getElementByClass(this.innerContent,'DIV','highslide-body');if(this.objectType=='iframe'){this.showLoading();var ruler=hs.clearing.cloneNode(1);this.body.appendChild(ruler);this.newWidth=this.innerContent.offsetWidth;if(!this.objectWidth)this.objectWidth=ruler.offsetWidth;var hDiff=this.innerContent.offsetHeight-this.body.offsetHeight,h=this.objectHeight||(hs.getPageSize()).height-hDiff-hs.marginTop-hs.marginBottom,onload=this.objectLoadTime=='before'?' onload="if (hs.expanders['+this.key+']) hs.expanders['+this.key+'].contentLoaded()" ':'';this.body.innerHTML+='<iframe name="hs'+(new Date()).getTime()+'" frameborder="0" key="'+this.key+'" '
+' allowtransparency="true" style="width:'+this.objectWidth+'px; height:'+h+'px" '
+onload+' src="'+this.src+'"></iframe>';this.ruler=this.body.getElementsByTagName('div')[0];this.iframe=this.body.getElementsByTagName('iframe')[0];if(this.objectLoadTime=='after')this.correctIframeSize();}
if(this.objectType=='swf'){this.body.id=this.body.id||'hs-flash-id-'+this.key;var a=this.swfOptions;if(typeof a.params.wmode=='undefined')a.params.wmode='transparent';if(swfobject)swfobject.embedSWF(this.src,this.body.id,this.objectWidth,this.objectHeight,a.version||'7',a.expressInstallSwfurl,a.flashvars,a.params,a.attributes);}
this.hasExtendedContent=true;},htmlGetSize:function(){if(this.iframe&&!this.objectHeight){this.iframe.style.height=this.body.style.height=this.getIframePageHeight()+'px';}
this.innerContent.appendChild(hs.clearing);if(!this.x.full)this.x.full=this.innerContent.offsetWidth;this.y.full=this.innerContent.offsetHeight;this.innerContent.removeChild(hs.clearing);if(hs.ie&&this.newHeight>parseInt(this.innerContent.currentStyle.height)){this.newHeight=parseInt(this.innerContent.currentStyle.height);}
hs.setStyles(this.wrapper,{position:'absolute',padding:'0'});hs.setStyles(this.content,{width:this.x.t+'px',height:this.y.t+'px'});},getIframePageHeight:function(){var h;try{var doc=this.iframe.contentDocument||this.iframe.contentWindow.document;var clearing=doc.createElement('div');clearing.style.clear='both';doc.body.appendChild(clearing);h=clearing.offsetTop;if(hs.ie)h+=parseInt(doc.body.currentStyle.marginTop)
+parseInt(doc.body.currentStyle.marginBottom)-1;}catch(e){h=300;}
return h;},correctIframeSize:function(){var wDiff=this.innerContent.offsetWidth-this.ruler.offsetWidth;if(wDiff<0)wDiff=0;var hDiff=this.innerContent.offsetHeight-this.iframe.offsetHeight;hs.setStyles(this.iframe,{width:(this.x.size-wDiff)+'px',height:(this.y.size-hDiff)+'px'});hs.setStyles(this.body,{width:this.iframe.style.width,height:this.iframe.style.height});this.scrollingContent=this.iframe;this.scrollerDiv=this.scrollingContent;},htmlSizeOperations:function(){this.setObjContainerSize(this.innerContent);if(this.objectType=='swf'&&this.objectLoadTime=='before')this.writeExtendedContent();if(this.x.size<this.x.full&&!this.allowWidthReduction)this.x.size=this.x.full;if(this.y.size<this.y.full&&!this.allowHeightReduction)this.y.size=this.y.full;this.scrollerDiv=this.innerContent;hs.setStyles(this.mediumContent,{width:this.x.size+'px',position:'relative',left:(this.x.pos-this.x.tpos)+'px',top:(this.y.pos-this.y.tpos)+'px'});hs.setStyles(this.innerContent,{border:'none',width:'auto',height:'auto'});var node=hs.getElementByClass(this.innerContent,'DIV','highslide-body');if(node&&!/(iframe|swf)/.test(this.objectType)){var cNode=node;node=hs.createElement(cNode.nodeName,null,{overflow:'hidden'},null,true);cNode.parentNode.insertBefore(node,cNode);node.appendChild(hs.clearing);node.appendChild(cNode);var wDiff=this.innerContent.offsetWidth-node.offsetWidth;var hDiff=this.innerContent.offsetHeight-node.offsetHeight;node.removeChild(hs.clearing);var kdeBugCorr=hs.safari||navigator.vendor=='KDE'?1:0;hs.setStyles(node,{width:(this.x.size-wDiff-kdeBugCorr)+'px',height:(this.y.size-hDiff)+'px',overflow:'auto',position:'relative'});if(kdeBugCorr&&cNode.offsetHeight>node.offsetHeight){node.style.width=(parseInt(node.style.width)+kdeBugCorr)+'px';}
this.scrollingContent=node;this.scrollerDiv=this.scrollingContent;}
if(this.iframe&&this.objectLoadTime=='before')this.correctIframeSize();if(!this.scrollingContent&&this.y.size<this.mediumContent.offsetHeight)this.scrollerDiv=this.content;if(this.scrollerDiv==this.content&&!this.allowWidthReduction&&!/(iframe|swf)/.test(this.objectType)){this.x.size+=17;}
if(this.scrollerDiv&&this.scrollerDiv.offsetHeight>this.scrollerDiv.parentNode.offsetHeight){setTimeout("try { hs.expanders["+this.key+"].scrollerDiv.style.overflow = 'auto'; } catch(e) {}",hs.expandDuration);}},getImageMapAreaCorrection:function(area){var c=area.coords.split(',');for(var i=0;i<c.length;i++)c[i]=parseInt(c[i]);if(area.shape.toLowerCase()=='circle'){this.x.tpos+=c[0]-c[2];this.y.tpos+=c[1]-c[2];this.x.t=this.y.t=2*c[2];}else{var maxX,maxY,minX=maxX=c[0],minY=maxY=c[1];for(var i=0;i<c.length;i++){if(i%2==0){minX=Math.min(minX,c[i]);maxX=Math.max(maxX,c[i]);}else{minY=Math.min(minY,c[i]);maxY=Math.max(maxY,c[i]);}}
this.x.tpos+=minX;this.x.t=maxX-minX;this.y.tpos+=minY;this.y.t=maxY-minY;}},justify:function(p,moveOnly){var tgtArr,tgt=p.target,dim=p==this.x?'x':'y';if(tgt&&tgt.match(/ /)){tgtArr=tgt.split(' ');tgt=tgtArr[0];}
if(tgt&&hs.$(tgt)){p.pos=hs.getPosition(hs.$(tgt))[dim];if(tgtArr&&tgtArr[1]&&tgtArr[1].match(/^[-]?[0-9]+px$/))
p.pos+=parseInt(tgtArr[1]);}else if(p.justify=='auto'||p.justify=='center'){var hasMovedMin=false;var allowReduce=p.exp.allowSizeReduction;if(p.justify=='center')
p.pos=Math.round(p.scroll+(p.clientSize-p.get('wsize'))/2);else
p.pos=Math.round(p.pos-((p.get('wsize')-p.t)/2));if(p.pos<p.scroll+p.marginMin){p.pos=p.scroll+p.marginMin;hasMovedMin=true;}
if(!moveOnly&&p.size<p.minSize){p.size=p.minSize;allowReduce=false;}
if(p.pos+p.get('wsize')>p.scroll+p.clientSize-p.marginMax){if(!moveOnly&&hasMovedMin&&allowReduce){p.size=p.get('fitsize')-2*p.cb-p.p1-p.p2;}else if(p.get('wsize')<p.get('fitsize')){p.pos=p.scroll+p.clientSize-p.marginMax-p.get('wsize');}else{p.pos=p.scroll+p.marginMin;if(!moveOnly&&allowReduce)p.size=p.get('fitsize')-2*p.cb-p.p1-p.p2;}}
if(!moveOnly&&p.size<p.minSize){p.size=p.minSize;allowReduce=false;}}else if(p.justify=='max'){p.pos=Math.floor(p.pos-p.size+p.t);}
if(p.pos<p.marginMin){var tmpMin=p.pos;p.pos=p.marginMin;if(allowReduce&&!moveOnly)p.size=p.size-(p.pos-tmpMin);}},correctRatio:function(ratio){var x=this.x,y=this.y,changed=false,xSize=Math.min(x.full,x.size),ySize=Math.min(y.full,y.size),useBox=(this.useBox||hs.padToMinWidth);if(xSize/ySize>ratio){xSize=ySize*ratio;if(xSize<x.minSize){xSize=x.minSize;ySize=xSize/ratio;}
changed=true;}else if(xSize/ySize<ratio){ySize=xSize/ratio;changed=true;}
if(hs.padToMinWidth&&x.full<x.minSize){x.imgSize=x.full;y.size=y.imgSize=y.full;}else if(this.useBox){x.imgSize=xSize;y.imgSize=ySize;}else{x.size=xSize;y.size=ySize;}
this.fitOverlayBox(useBox?null:ratio);if(useBox&&y.size<y.imgSize){y.imgSize=y.size;x.imgSize=y.size*ratio;}
if(changed||useBox){x.pos=x.tpos-x.cb+x.tb;x.minSize=x.size;this.justify(x,true);y.pos=y.tpos-y.cb+y.tb;y.minSize=y.size;this.justify(y,true);if(this.overlayBox)this.sizeOverlayBox();}},fitOverlayBox:function(ratio){var x=this.x,y=this.y;if(this.overlayBox){while(y.size>this.minHeight&&x.size>this.minWidth&&y.get('wsize')>y.get('fitsize')){y.size-=10;if(ratio)x.size=y.size*ratio;this.sizeOverlayBox(0,1);}}},reflow:function(){var h=/iframe/i.test(this.scrollerDiv.tagName)?this.getIframePageHeight()+1+'px':'auto';if(this.body)this.body.style.height=h;this.scrollerDiv.style.height=h;this.y.setSize(this.innerContent.offsetHeight);},show:function(){this.doShowHide('hidden');hs.fireEvent(this,'onBeforeExpand');this.changeSize(1,{xpos:this.x.tpos+this.x.tb-this.x.cb,ypos:this.y.tpos+this.y.tb-this.y.cb,xsize:this.x.t,ysize:this.y.t,xp1:0,xp2:0,yp1:0,yp2:0,ximgSize:this.x.t,ximgPad:0,yimgSize:this.y.t,yimgPad:0,o:hs.outlineStartOffset},{xpos:this.x.pos,ypos:this.y.pos,xsize:this.x.size,ysize:this.y.size,xp1:this.x.p1,yp1:this.y.p1,xp2:this.x.p2,yp2:this.y.p2,ximgSize:this.x.imgSize,ximgPad:this.x.get('imgPad'),yimgSize:this.y.imgSize,yimgPad:this.y.get('imgPad'),o:this.outline?this.outline.offset:0},hs.expandDuration);},changeSize:function(up,from,to,dur){var trans=this.transitions,other=up?(this.last?this.last.a:null):hs.upcoming,t=(trans[1]&&other&&hs.getParam(other,'transitions')[1]==trans[1])?trans[1]:trans[0];if(this[t]&&t!='expand'){this[t](up,from,to);return;}
if(up)hs.setStyles(this.wrapper,{opacity:1});if(this.outline&&!this.outlineWhileAnimating){if(up)this.outline.setPosition(this);else this.outline.destroy((this.isHtml&&this.preserveContent));}
if(!up&&this.overlayBox){if(this.slideshow){var c=this.slideshow.controls;if(c&&hs.getExpander(c)==this)c.parentNode.removeChild(c);}
if(this.isHtml&&this.preserveContent){this.overlayBox.style.top='-9999px';hs.container.appendChild(this.overlayBox);}else
hs.discardElement(this.overlayBox);}
if(this.fadeInOut){from.op=up?0:1;to.op=up;}
var t,exp=this,easing=Math[this.easing]||Math.easeInQuad,steps=(up?hs.expandSteps:hs.restoreSteps)||parseInt(dur/25)||1;if(!up)easing=Math[this.easingClose]||easing;for(var i=1;i<=steps;i++){t=Math.round(i*(dur/steps));(function(){var pI=i,size={};for(var x in from){size[x]=easing(t,from[x],to[x]-from[x],dur);if(isNaN(size[x]))size[x]=to[x];if(!/^op$/.test(x))size[x]=Math.round(size[x]);}
setTimeout(function(){if(up&&pI==1){exp.content.style.visibility='visible';exp.a.className+=' highslide-active-anchor';}
exp.setSize(size);},t);})();}
if(up){setTimeout(function(){if(exp.outline)exp.outline.table.style.visibility="visible";},t);setTimeout(function(){exp.afterExpand();},t+50);}
else setTimeout(function(){exp.afterClose();},t);},setSize:function(to){try{if(to.op)hs.setStyles(this.wrapper,{opacity:to.op});hs.setStyles(this.wrapper,{width:(to.xsize+to.xp1+to.xp2+
2*this.x.cb)+'px',height:(to.ysize+to.yp1+to.yp2+
2*this.y.cb)+'px',left:to.xpos+'px',top:to.ypos+'px'});hs.setStyles(this.content,{left:(to.xp1+to.ximgPad)+'px',top:(to.yp1+to.yimgPad)+'px',width:(to.ximgSize||to.xsize)+'px',height:(to.yimgSize||to.ysize)+'px'});if(this.isHtml){hs.setStyles(this.mediumContent,{left:(this.x.pos-to.xpos
+this.x.p1-to.xp1)+'px',top:(this.y.pos-to.ypos
+this.y.p1-to.yp1)+'px'});this.innerContent.style.visibility='visible';}
if(this.outline&&this.outlineWhileAnimating){var o=this.outline.offset-to.o;this.outline.setPosition(this,{x:to.xpos+o,y:to.ypos+o,w:to.xsize+to.xp1+to.xp2+-2*o,h:to.ysize+to.yp1+to.yp2+-2*o},1);}
this.wrapper.style.visibility='visible';}catch(e){alert('Exception: '+e+'\nStack trace: '+e.stack);}},fade:function(up,from,to){this.outlineWhileAnimating=false;var exp=this,t=up?250:0;if(up){hs.setStyles(this.wrapper,{opacity:0});this.setSize(to);this.content.style.visibility='visible';hs.fade(this.wrapper,0,1);}
if(this.outline){this.outline.table.style.zIndex=this.wrapper.style.zIndex;var dir=up||-1;for(var i=from.o;dir*i<=dir*to.o;i+=dir,t+=25){(function(){var o=up?to.o-i:from.o-i;setTimeout(function(){exp.outline.setPosition(exp,{x:(exp.x.pos+o),y:(exp.y.pos+o),w:(exp.x.size-2*o+exp.x.p1+exp.x.p2),h:(exp.y.size-2*o+exp.y.p1+exp.y.p2)},1);},t);})();}}
if(up)setTimeout(function(){exp.afterExpand();},t+50);else{setTimeout(function(){if(exp.outline)exp.outline.destroy(exp.preserveContent);hs.fade(exp.wrapper,1,0);setTimeout(function(){exp.afterClose();},250);},t);}},crossfade:function(up,from,to){if(!up)return;var exp=this,steps=parseInt(hs.transitionDuration/25)||1,last=this.last;hs.removeEventListener(document,'mousemove',hs.dragHandler);hs.setStyles(this.content,{width:(to.ximgSize||to.xsize)+'px',height:(to.yimgSize||to.ysize)+'px'});this.outline=this.last.outline;this.last.outline=null;this.fadeBox=hs.createElement('div',{className:'highslide-image'},{position:'absolute',zIndex:4,overflow:'hidden',display:'none'});if(this.isHtml){hs.setStyles(this.mediumContent,{left:'0px',top:'0px'});}
var names={oldImg:last,newImg:this};for(var x in names){this[x]=names[x].content.cloneNode(1);hs.setStyles(this[x],{position:'absolute',border:0,visibility:'visible'});this.fadeBox.appendChild(this[x]);}
this.wrapper.appendChild(this.fadeBox);from={xpos:last.x.pos,xsize:last.x.size,xp1:last.x.p1,xp2:last.x.p2,ximgSize:last.x.imgSize||last.x.size,ximgPad:last.x.get('imgPad'),yimgSize:last.y.imgSize||last.y.size,yimgPad:last.y.get('imgPad'),ypos:last.y.pos,ysize:last.y.size,yp1:last.y.p1,yp2:last.y.p2,o:1/steps};to.ysize=this.y.size;to.o=1;if(!to.ximgSize)to.ximgSize=to.xsize;if(!to.yimgSize)to.yimgSize=to.ysize;var t,easing=Math.easeInOutQuad;if(steps>1)this.crossfadeStep(from);function prep(){if(exp.overlayBox){exp.overlayBox.className='';exp.overlayBox.style.overflow='visible';exp.wrapper.appendChild(exp.overlayBox);for(var i=0;i<exp.last.overlays.length;i++){var oDiv=hs.$('hsId'+exp.last.overlays[i]);if(oDiv.reuse===exp.key)exp.overlayBox.appendChild(oDiv);else hs.fade(oDiv,oDiv.opacity,0);}}
exp.fadeBox.style.display='';exp.last.content.style.display='none';};if(/rv:1\.[0-8].+Gecko/.test(navigator.userAgent))setTimeout(prep,0);else prep();if(hs.safari){var match=navigator.userAgent.match(/Safari\/([0-9]{3})/);if(match&&parseInt(match[1])<525)this.wrapper.style.visibility='visible';}
for(var i=1;i<=steps;i++){t=Math.round(i*(hs.transitionDuration/steps));(function(){var size={},pI=i;for(var x in from){var val=easing(t,from[x],to[x]-from[x],hs.transitionDuration);if(isNaN(val))val=to[x];size[x]=(x!='o')?Math.round(val):val;}
setTimeout(function(){exp.crossfadeStep(size);},t);})();}
setTimeout(function(){exp.crossfadeEnd();},t+100);},crossfadeStep:function(size){try{if(this.outline)this.outline.setPosition(this,{x:size.xpos,y:size.ypos,w:size.xsize+size.xp1+size.xp2,h:size.ysize+size.yp1+size.yp2},1);this.last.wrapper.style.clip='rect('
+(size.ypos-this.last.y.pos)+'px, '
+(size.xsize+size.xp1+size.xp2+size.xpos+2*this.last.x.cb-this.last.x.pos)+'px, '
+(size.ysize+size.yp1+size.yp2+size.ypos+2*this.last.y.cb-this.last.y.pos)+'px, '
+(size.xpos-this.last.x.pos)+'px)';hs.setStyles(this.content,{top:(size.yp1+this.y.get('imgPad'))+'px',left:(size.xp1+this.x.get('imgPad'))+'px',marginTop:(this.y.pos-size.ypos)+'px',marginLeft:(this.x.pos-size.xpos)+'px'});hs.setStyles(this.wrapper,{top:size.ypos+'px',left:size.xpos+'px',width:(size.xp1+size.xp2+size.xsize+2*this.x.cb)+'px',height:(size.yp1+size.yp2+size.ysize+2*this.y.cb)+'px'});hs.setStyles(this.fadeBox,{width:(size.ximgSize||size.xsize)+'px',height:(size.yimgSize||size.ysize)+'px',left:(size.xp1+size.ximgPad)+'px',top:(size.yp1+size.yimgPad)+'px',visibility:'visible'});hs.setStyles(this.oldImg,{top:(this.last.y.pos-size.ypos+this.last.y.p1-size.yp1+
this.last.y.get('imgPad')-size.yimgPad)+'px',left:(this.last.x.pos-size.xpos+this.last.x.p1-size.xp1+
this.last.x.get('imgPad')-size.ximgPad)+'px'});hs.setStyles(this.newImg,{opacity:size.o,top:(this.y.pos-size.ypos+this.y.p1-size.yp1+this.y.get('imgPad')-size.yimgPad)+'px',left:(this.x.pos-size.xpos+this.x.p1-size.xp1+this.x.get('imgPad')-size.ximgPad)+'px'});hs.setStyles(this.overlayBox,{width:size.xsize+'px',height:size.ysize+'px',left:(size.xp1+this.x.cb)+'px',top:(size.yp1+this.y.cb)+'px'});}catch(e){}},crossfadeEnd:function(){this.wrapper.style.background=this.wrapperBG||'';this.wrapper.style.visibility=this.content.style.visibility='visible';this.fadeBox.style.display='none';this.a.className+=' highslide-active-anchor';this.afterExpand();this.last.afterClose();},reuseOverlay:function(o,el){if(!this.last)return false;for(var i=0;i<this.last.overlays.length;i++){var oDiv=hs.$('hsId'+this.last.overlays[i]);if(oDiv&&oDiv.hsId==o.hsId){this.genOverlayBox();oDiv.reuse=this.key;hs.push(this.overlays,this.last.overlays[i]);return true;}}
return false;},afterExpand:function(){this.isExpanded=true;this.focus();if(this.isHtml&&this.objectLoadTime=='after')this.writeExtendedContent();if(this.isHtml){if(this.iframe){try{var exp=this,doc=this.iframe.contentDocument||this.iframe.contentWindow.document;hs.addEventListener(doc,'mousedown',function(){if(hs.focusKey!=exp.key)exp.focus();});}catch(e){}
if(hs.ie&&typeof this.isClosing!='boolean')
this.iframe.style.width=(this.objectWidth-1)+'px';}}
if(this.dimmingOpacity)hs.dim(this);if(hs.upcoming&&hs.upcoming==this.a)hs.upcoming=null;this.prepareNextOutline();var p=hs.page,mX=hs.mouse.x+p.scrollLeft,mY=hs.mouse.y+p.scrollTop;this.mouseIsOver=this.x.pos<mX&&mX<this.x.pos+this.x.get('wsize')&&this.y.pos<mY&&mY<this.y.pos+this.y.get('wsize');if(this.overlayBox)this.showOverlays();hs.fireEvent(this,'onAfterExpand');},prepareNextOutline:function(){var key=this.key;var outlineType=this.outlineType;new hs.Outline(outlineType,function(){try{hs.expanders[key].preloadNext();}catch(e){}});},preloadNext:function(){var next=this.getAdjacentAnchor(1);if(next&&next.onclick.toString().match(/hs\.expand/))
var img=hs.createElement('img',{src:hs.getSrc(next)});},getAdjacentAnchor:function(op){var current=this.getAnchorIndex(),as=hs.anchors.groups[this.slideshowGroup||'none'];if(!as[current+op]&&this.slideshow&&this.slideshow.repeat){if(op==1)return as[0];else if(op==-1)return as[as.length-1];}
return as[current+op]||null;},getAnchorIndex:function(){var arr=hs.anchors.groups[this.slideshowGroup||'none'];for(var i=0;i<arr.length;i++){if(arr[i]==this.a)return i;}
return null;},getNumber:function(){if(this[this.numberPosition]){var arr=hs.anchors.groups[this.slideshowGroup||'none'];var s=hs.lang.number.replace('%1',this.getAnchorIndex()+1).replace('%2',arr.length);this[this.numberPosition].innerHTML='<div class="highslide-number">'+s+'</div>'+this[this.numberPosition].innerHTML;}},initSlideshow:function(){if(!this.last){for(var i=0;i<hs.slideshows.length;i++){var ss=hs.slideshows[i],sg=ss.slideshowGroup;if(typeof sg=='undefined'||sg===null||sg===this.slideshowGroup)
this.slideshow=new hs.Slideshow(ss);}}else{this.slideshow=this.last.slideshow;}
var ss=this.slideshow;if(!ss)return;var exp=ss.exp=this;ss.checkFirstAndLast();ss.disable('full-expand');if(ss.controls){var o=ss.overlayOptions||{};o.overlayId=ss.controls;o.hsId='controls';this.createOverlay(o);}
if(!this.last&&this.autoplay)ss.play(true);if(ss.autoplay){ss.autoplay=setTimeout(function(){hs.next(exp.key);},(ss.interval||500));}},cancelLoading:function(){hs.expanders[this.key]=null;if(hs.upcoming==this.a)hs.upcoming=null;hs.undim(this.key);if(this.loading)hs.loading.style.left='-9999px';hs.fireEvent(this,'onHideLoading');},writeCredits:function(){if(this.credits)return;this.credits=hs.createElement('a',{href:hs.creditsHref,className:'highslide-credits',innerHTML:hs.lang.creditsText,title:hs.lang.creditsTitle});this.createOverlay({overlayId:this.credits,position:'top left',hsId:'credits'});},getInline:function(types,addOverlay){for(var i=0;i<types.length;i++){var type=types[i],s=null;if(type=='caption'&&!hs.fireEvent(this,'onBeforeGetCaption'))return;else if(type=='heading'&&!hs.fireEvent(this,'onBeforeGetHeading'))return;if(!this[type+'Id']&&this.thumbsUserSetId)
this[type+'Id']=type+'-for-'+this.thumbsUserSetId;if(this[type+'Id'])this[type]=hs.getNode(this[type+'Id']);if(!this[type]&&!this[type+'Text']&&this[type+'Eval'])try{s=eval(this[type+'Eval']);}catch(e){}
if(!this[type]&&this[type+'Text']){s=this[type+'Text'];}
if(!this[type]&&!s){var next=this.a.nextSibling;while(next&&!hs.isHsAnchor(next)){if((new RegExp('highslide-'+type)).test(next.className||null)){this[type]=next.cloneNode(1);break;}
next=next.nextSibling;}}
if(!this[type]&&!s&&this.numberPosition==type)s='\n';if(!this[type]&&s)this[type]=hs.createElement('div',{className:'highslide-'+type,innerHTML:s});if(addOverlay&&this[type]){var o={position:(type=='heading')?'above':'below'};for(var x in this[type+'Overlay'])o[x]=this[type+'Overlay'][x];o.overlayId=this[type];this.createOverlay(o);}}},doShowHide:function(visibility){if(hs.hideSelects)this.showHideElements('SELECT',visibility);if(hs.hideIframes)this.showHideElements('IFRAME',visibility);if(hs.geckoMac)this.showHideElements('*',visibility);},showHideElements:function(tagName,visibility){var els=document.getElementsByTagName(tagName);var prop=tagName=='*'?'overflow':'visibility';for(var i=0;i<els.length;i++){if(prop=='visibility'||(document.defaultView.getComputedStyle(els[i],"").getPropertyValue('overflow')=='auto'||els[i].getAttribute('hidden-by')!=null)){var hiddenBy=els[i].getAttribute('hidden-by');if(visibility=='visible'&&hiddenBy){hiddenBy=hiddenBy.replace('['+this.key+']','');els[i].setAttribute('hidden-by',hiddenBy);if(!hiddenBy)els[i].style[prop]=els[i].origProp;}else if(visibility=='hidden'){var elPos=hs.getPosition(els[i]);elPos.w=els[i].offsetWidth;elPos.h=els[i].offsetHeight;if(!this.dimmingOpacity){var clearsX=(elPos.x+elPos.w<this.x.get('opos')||elPos.x>this.x.get('opos')+this.x.get('osize'));var clearsY=(elPos.y+elPos.h<this.y.get('opos')||elPos.y>this.y.get('opos')+this.y.get('osize'));}
var wrapperKey=hs.getWrapperKey(els[i]);if(!clearsX&&!clearsY&&wrapperKey!=this.key){if(!hiddenBy){els[i].setAttribute('hidden-by','['+this.key+']');els[i].origProp=els[i].style[prop];els[i].style[prop]='hidden';}else if(hiddenBy.indexOf('['+this.key+']')==-1){els[i].setAttribute('hidden-by',hiddenBy+'['+this.key+']');}}else if((hiddenBy=='['+this.key+']'||hs.focusKey==wrapperKey)&&wrapperKey!=this.key){els[i].setAttribute('hidden-by','');els[i].style[prop]=els[i].origProp||'';}else if(hiddenBy&&hiddenBy.indexOf('['+this.key+']')>-1){els[i].setAttribute('hidden-by',hiddenBy.replace('['+this.key+']',''));}}}}},focus:function(){this.wrapper.style.zIndex=hs.zIndexCounter++;for(var i=0;i<hs.expanders.length;i++){if(hs.expanders[i]&&i==hs.focusKey){var blurExp=hs.expanders[i];blurExp.content.className+=' highslide-'+blurExp.contentType+'-blur';if(blurExp.isImage){blurExp.content.style.cursor=hs.ie?'hand':'pointer';blurExp.content.title=hs.lang.focusTitle;}
hs.fireEvent(this,'onBlur');}}
if(this.outline)this.outline.table.style.zIndex=this.wrapper.style.zIndex;this.content.className='highslide-'+this.contentType;if(this.isImage){this.content.title=hs.lang.restoreTitle;if(hs.restoreCursor){hs.styleRestoreCursor=window.opera?'pointer':'url('+hs.graphicsDir+hs.restoreCursor+'), pointer';if(hs.ie&&hs.ieVersion()<6)hs.styleRestoreCursor='hand';this.content.style.cursor=hs.styleRestoreCursor;}}
hs.focusKey=this.key;hs.addEventListener(document,window.opera?'keypress':'keydown',hs.keyHandler);hs.fireEvent(this,'onFocus');},moveTo:function(x,y){this.x.setPos(x);this.y.setPos(y);},resize:function(e){var w,h,r=e.width/e.height;w=Math.max(e.width+e.dX,Math.min(this.minWidth,this.x.full));if(this.isImage&&Math.abs(w-this.x.full)<12)w=this.x.full;h=this.isHtml?e.height+e.dY:w/r;if(h<Math.min(this.minHeight,this.y.full)){h=Math.min(this.minHeight,this.y.full);if(this.isImage)w=h*r;}
this.resizeTo(w,h);},resizeTo:function(w,h){this.y.setSize(h);this.x.setSize(w);},close:function(){if(this.isClosing||!this.isExpanded)return;if(this.transitions[1]=='crossfade'&&hs.upcoming){hs.getExpander(hs.upcoming).cancelLoading();hs.upcoming=null;}
if(!hs.fireEvent(this,'onBeforeClose'))return;this.isClosing=true;if(this.slideshow&&!hs.upcoming)this.slideshow.pause();hs.removeEventListener(document,window.opera?'keypress':'keydown',hs.keyHandler);try{if(this.isHtml)this.htmlPrepareClose();this.content.style.cursor='default';this.changeSize(0,{xpos:this.x.pos,ypos:this.y.pos,xsize:this.x.size,ysize:this.y.size,xp1:this.x.p1,yp1:this.y.p1,xp2:this.x.p2,yp2:this.y.p2,ximgSize:this.x.imgSize,ximgPad:this.x.get('imgPad'),yimgSize:this.y.imgSize,yimgPad:this.y.get('imgPad'),o:this.outline?this.outline.offset:0},{xpos:this.x.tpos-this.x.cb+this.x.tb,ypos:this.y.tpos-this.y.cb+this.y.tb,xsize:this.x.t,ysize:this.y.t,xp1:0,yp1:0,xp2:0,yp2:0,ximgSize:this.x.imgSize?this.x.t:null,ximgPad:0,yimgSize:this.y.imgSize?this.y.t:null,yimgPad:0,o:hs.outlineStartOffset},hs.restoreDuration);}catch(e){this.afterClose();}},htmlPrepareClose:function(){if(hs.geckoMac){if(!hs.mask)hs.mask=hs.createElement('div',null,{position:'absolute'},hs.container);hs.setStyles(hs.mask,{width:this.x.size+'px',height:this.y.size+'px',left:this.x.pos+'px',top:this.y.pos+'px',display:'block'});}
if(this.objectType=='swf')try{hs.$(this.body.id).StopPlay();}catch(e){}
if(this.objectLoadTime=='after'&&!this.preserveContent)this.destroyObject();if(this.scrollerDiv&&this.scrollerDiv!=this.scrollingContent)
this.scrollerDiv.style.overflow='hidden';},destroyObject:function(){if(hs.ie&&this.iframe)
try{this.iframe.contentWindow.document.body.innerHTML='';}catch(e){}
if(this.objectType=='swf')swfobject.removeSWF(this.body.id);this.body.innerHTML='';},sleep:function(){if(this.outline)this.outline.table.style.display='none';this.releaseMask=null;this.wrapper.style.display='none';hs.push(hs.sleeping,this);},awake:function(){try{hs.expanders[this.key]=this;if(!hs.allowMultipleInstances&&hs.focusKey!=this.key){try{hs.expanders[hs.focusKey].close();}catch(e){}}
var z=hs.zIndexCounter++,stl={display:'',zIndex:z};hs.setStyles(this.wrapper,stl);this.isClosing=false;var o=this.outline||0;if(o){if(!this.outlineWhileAnimating)stl.visibility='hidden';hs.setStyles(o.table,stl);}
if(this.slideshow){this.initSlideshow();}
this.show();}catch(e){}},createOverlay:function(o){var el=o.overlayId;if(typeof el=='string')el=hs.getNode(el);if(!el||typeof el=='string')return;if(!hs.fireEvent(this,'onCreateOverlay',{overlay:el}))return;el.style.display='block';o.hsId=o.hsId||o.overlayId;if(this.transitions[1]=='crossfade'&&this.reuseOverlay(o,el))return;this.genOverlayBox();var width=o.width&&/^[0-9]+(px|%)$/.test(o.width)?o.width:'auto';if(/^(left|right)panel$/.test(o.position)&&!/^[0-9]+px$/.test(o.width))width='200px';var overlay=hs.createElement('div',{id:'hsId'+hs.idCounter++,hsId:o.hsId},{position:'absolute',visibility:'hidden',width:width,direction:hs.lang.cssDirection||''},this.overlayBox,true);overlay.appendChild(el);hs.setAttribs(overlay,{hideOnMouseOut:o.hideOnMouseOut,opacity:o.opacity||1,hsPos:o.position,fade:o.fade});if(this.gotOverlays){this.positionOverlay(overlay);if(!overlay.hideOnMouseOut||this.mouseIsOver)hs.fade(overlay,0,overlay.opacity);}
hs.push(this.overlays,hs.idCounter-1);},positionOverlay:function(overlay){var p=overlay.hsPos||'middle center';if(/left$/.test(p))overlay.style.left=0;if(/center$/.test(p))hs.setStyles(overlay,{left:'50%',marginLeft:'-'+Math.round(overlay.offsetWidth/2)+'px'});if(/right$/.test(p))overlay.style.right=0;if(/^leftpanel$/.test(p)){hs.setStyles(overlay,{right:'100%',marginRight:this.x.cb+'px',top:-this.y.cb+'px',bottom:-this.y.cb+'px',overflow:'auto'});this.x.p1=overlay.offsetWidth;}else if(/^rightpanel$/.test(p)){hs.setStyles(overlay,{left:'100%',marginLeft:this.x.cb+'px',top:-this.y.cb+'px',bottom:-this.y.cb+'px',overflow:'auto'});this.x.p2=overlay.offsetWidth;}
if(/^top/.test(p))overlay.style.top=0;if(/^middle/.test(p))hs.setStyles(overlay,{top:'50%',marginTop:'-'+Math.round(overlay.offsetHeight/2)+'px'});if(/^bottom/.test(p))overlay.style.bottom=0;if(/^above$/.test(p)){hs.setStyles(overlay,{left:(-this.x.p1-this.x.cb)+'px',right:(-this.x.p2-this.x.cb)+'px',bottom:'100%',marginBottom:this.y.cb+'px',width:'auto'});this.y.p1=overlay.offsetHeight;}else if(/^below$/.test(p)){hs.setStyles(overlay,{position:'relative',left:(-this.x.p1-this.x.cb)+'px',right:(-this.x.p2-this.x.cb)+'px',top:'100%',marginTop:this.y.cb+'px',width:'auto'});this.y.p2=overlay.offsetHeight;overlay.style.position='absolute';}},getOverlays:function(){this.getInline(['heading','caption'],true);this.getNumber();if(this.caption)hs.fireEvent(this,'onAfterGetCaption');if(this.heading)hs.fireEvent(this,'onAfterGetHeading');if(this.heading&&this.dragByHeading)this.heading.className+=' highslide-move';if(hs.showCredits)this.writeCredits();for(var i=0;i<hs.overlays.length;i++){var o=hs.overlays[i],tId=o.thumbnailId,sg=o.slideshowGroup;if((!tId&&!sg)||(tId&&tId==this.thumbsUserSetId)||(sg&&sg===this.slideshowGroup)){if(this.isImage||(this.isHtml&&o.useOnHtml))
this.createOverlay(o);}}
var os=[];for(var i=0;i<this.overlays.length;i++){var o=hs.$('hsId'+this.overlays[i]);if(/panel$/.test(o.hsPos))this.positionOverlay(o);else hs.push(os,o);}
for(var i=0;i<os.length;i++)this.positionOverlay(os[i]);this.gotOverlays=true;},genOverlayBox:function(){if(!this.overlayBox)this.overlayBox=hs.createElement('div',{className:this.wrapperClassName},{position:'absolute',width:this.x.size?this.x.size+'px':this.x.full+'px',height:0,visibility:'hidden',overflow:'hidden',zIndex:hs.ie?4:null},hs.container,true);},sizeOverlayBox:function(doWrapper,doPanels){hs.setStyles(this.overlayBox,{width:this.x.size+'px',height:this.y.size+'px'});if(doWrapper||doPanels){for(var i=0;i<this.overlays.length;i++){var o=hs.$('hsId'+this.overlays[i]);var ie6=(hs.ie&&(hs.ieVersion()<=6||document.compatMode=='BackCompat'));if(o&&/^(above|below)$/.test(o.hsPos)){if(ie6){o.style.width=(this.overlayBox.offsetWidth+2*this.x.cb
+this.x.p1+this.x.p2)+'px';}
this.y[o.hsPos=='above'?'p1':'p2']=o.offsetHeight;}
if(o&&ie6&&/^(left|right)panel$/.test(o.hsPos)){o.style.height=(this.overlayBox.offsetHeight+2*this.y.cb
+this.y.p1+this.y.p2)+'px';}}}
if(doWrapper){hs.setStyles(this.content,{top:this.y.p1+'px'});hs.setStyles(this.overlayBox,{top:(this.y.p1+this.y.cb)+'px'});}},showOverlays:function(){var b=this.overlayBox;b.className='';hs.setStyles(b,{top:(this.y.p1+this.y.cb)+'px',left:(this.x.p1+this.x.cb)+'px',overflow:'visible'});if(hs.safari)b.style.visibility='visible';this.wrapper.appendChild(b);for(var i=0;i<this.overlays.length;i++){var o=hs.$('hsId'+this.overlays[i]);o.style.zIndex=o.hsId=='controls'?5:4;if(!o.hideOnMouseOut||this.mouseIsOver)hs.fade(o,0,o.opacity);}},createFullExpand:function(){if(this.slideshow&&this.slideshow.controls){this.slideshow.enable('full-expand');return;}
this.fullExpandLabel=hs.createElement('a',{href:'javascript:hs.expanders['+this.key+'].doFullExpand();',title:hs.lang.fullExpandTitle,className:'highslide-full-expand'});if(!hs.fireEvent(this,'onCreateFullExpand'))return;this.createOverlay({overlayId:this.fullExpandLabel,position:hs.fullExpandPosition,hideOnMouseOut:true,opacity:hs.fullExpandOpacity});},doFullExpand:function(){try{if(!hs.fireEvent(this,'onDoFullExpand'))return;if(this.fullExpandLabel)hs.discardElement(this.fullExpandLabel);this.focus();var xSize=this.x.size;this.resizeTo(this.x.full,this.y.full);var xpos=this.x.pos-(this.x.size-xSize)/2;if(xpos<hs.marginLeft)xpos=hs.marginLeft;this.moveTo(xpos,this.y.pos);this.doShowHide('hidden');hs.setDimmerSize(this);}catch(e){alert('Exception: '+e+'\nStack trace: '+e.stack);}},afterClose:function(){this.a.className=this.a.className.replace('highslide-active-anchor','');this.doShowHide('visible');if(this.isHtml&&this.preserveContent&&this.transitions[1]!='crossfade'){this.sleep();}else{if(this.outline&&this.outlineWhileAnimating)this.outline.destroy();hs.discardElement(this.wrapper);}
if(hs.mask)hs.mask.style.display='none';if(this.dimmingOpacity)hs.undim(this.key);hs.fireEvent(this,'onAfterClose');hs.expanders[this.key]=null;hs.reOrder();}};hs.Ajax=function(a,content,pre){this.a=a;this.content=content;this.pre=pre;};hs.Ajax.prototype={run:function(){if(!this.src)this.src=hs.getSrc(this.a);if(this.src.match('#')){var arr=this.src.split('#');this.src=arr[0];this.id=arr[1];}
if(hs.cachedGets[this.src]){this.cachedGet=hs.cachedGets[this.src];if(this.id)this.getElementContent();else this.loadHTML();return;}
try{this.xmlHttp=new XMLHttpRequest();}
catch(e){try{this.xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){try{this.xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){this.onError();}}}
var pThis=this;this.xmlHttp.onreadystatechange=function(){if(pThis.xmlHttp.readyState==4){if(pThis.id)pThis.getElementContent();else pThis.loadHTML();}};this.xmlHttp.open("GET",this.src,true);this.xmlHttp.setRequestHeader('X-Requested-With','XMLHttpRequest');this.xmlHttp.send(null);},getElementContent:function(){hs.init();var attribs=window.opera||hs.ie6SSL?{src:'about:blank'}:null;this.iframe=hs.createElement('iframe',attribs,{position:'absolute',top:'-9999px'},hs.container);this.loadHTML();},loadHTML:function(){var s=this.cachedGet||this.xmlHttp.responseText;if(this.pre)hs.cachedGets[this.src]=s;if(!hs.ie||hs.ieVersion()>=5.5){s=s.replace(/\s/g,' ').replace(new RegExp('<link[^>]*>','gi'),'').replace(new RegExp('<script[^>]*>.*?</script>','gi'),'');if(this.iframe){var doc=this.iframe.contentDocument;if(!doc&&this.iframe.contentWindow)doc=this.iframe.contentWindow.document;if(!doc){var pThis=this;setTimeout(function(){pThis.loadHTML();},25);return;}
doc.open();doc.write(s);doc.close();try{s=doc.getElementById(this.id).innerHTML;}catch(e){try{s=this.iframe.document.getElementById(this.id).innerHTML;}catch(e){}}}else{s=s.replace(new RegExp('^.*?<body[^>]*>(.*?)</body>.*?$','i'),'$1');}}
hs.getElementByClass(this.content,'DIV','highslide-body').innerHTML=s;this.onLoad();for(var x in this)this[x]=null;}};hs.Slideshow=function(options){if(hs.dynamicallyUpdateAnchors!==false)hs.updateAnchors();for(var x in options)this[x]=options[x];if(this.useControls)this.getControls();};hs.Slideshow.prototype={getControls:function(){this.controls=hs.createElement('div',{innerHTML:hs.replaceLang(hs.skin.controls)},null,hs.container);var buttons=['play','pause','previous','next','move','full-expand','close'];this.btn={};var pThis=this;for(var i=0;i<buttons.length;i++){this.btn[buttons[i]]=hs.getElementByClass(this.controls,'li','highslide-'+buttons[i]);this.enable(buttons[i]);}
this.btn.pause.style.display='none';},checkFirstAndLast:function(){if(this.repeat||!this.controls)return;var cur=this.exp.getAnchorIndex(),re=/disabled$/;if(cur==0)
this.disable('previous');else if(re.test(this.btn.previous.getElementsByTagName('a')[0].className))
this.enable('previous');if(cur+1==hs.anchors.groups[this.exp.slideshowGroup||'none'].length){this.disable('next');this.disable('play');}else if(re.test(this.btn.next.getElementsByTagName('a')[0].className)){this.enable('next');this.enable('play');}},enable:function(btn){if(!this.btn)return;var sls=this,a=this.btn[btn].getElementsByTagName('a')[0],re=/disabled$/;a.onclick=function(){sls[btn]();return false;};if(re.test(a.className))a.className=a.className.replace(re,'');},disable:function(btn){if(!this.btn)return;var a=this.btn[btn].getElementsByTagName('a')[0];a.onclick=function(){return false;};if(!/disabled$/.test(a.className))a.className+=' disabled';},hitSpace:function(){if(this.autoplay)this.pause();else this.play();},play:function(wait){if(this.btn){this.btn.play.style.display='none';this.btn.pause.style.display='';}
this.autoplay=true;if(!wait)hs.next(this.exp.key);},pause:function(){if(this.btn){this.btn.pause.style.display='none';this.btn.play.style.display='';}
clearTimeout(this.autoplay);this.autoplay=null;},previous:function(){this.pause();hs.previous(this.btn.previous);},next:function(){this.pause();hs.next(this.btn.next);},move:function(){},'full-expand':function(){hs.getExpander().doFullExpand();},close:function(){hs.close(this.btn.close);}};if(document.readyState&&hs.ie){(function(){try{document.documentElement.doScroll('left');}catch(e){setTimeout(arguments.callee,50);return;}
hs.domReady();})();}
hs.langDefaults=hs.lang;var HsExpander=hs.Expander;hs.addEventListener(window,'load',function(){if(hs.expandCursor){var sel='.highslide img',dec='cursor: url('+hs.graphicsDir+hs.expandCursor+'), pointer !important;';var style=hs.createElement('style',{type:'text/css'},null,document.getElementsByTagName('HEAD')[0]);if(!hs.ie){style.appendChild(document.createTextNode(sel+" {"+dec+"}"));}else{var last=document.styleSheets[document.styleSheets.length-1];if(typeof(last.addRule)=="object")last.addRule(sel,dec);}}});hs.addEventListener(document,'mousemove',function(e){hs.mouse={x:e.clientX,y:e.clientY};});hs.addEventListener(document,'mousedown',hs.mouseClickHandler);hs.addEventListener(document,'mouseup',hs.mouseClickHandler);hs.addEventListener(window,'load',hs.preloadImages);hs.addEventListener(window,'load',hs.preloadAjax);hs.addEventListener(window,'load',function(){hs.pageLoaded=true;});hs.setClickEvents();hs.graphicsDir='/images/highslide/';hs.transitions=['expand','crossfade'];hs.outlineType='rounded-white';hs.fadeInOut=true;hs.allowMultipleInstances=false;hs.dimmingOpacity=0.5;hs.showCredits=false;hs.align='center';hs.addSlideshow({interval:5000,repeat:false,useControls:true,fixedControls:'fit',overlayOptions:{opacity:0.75,position:'bottom center',hideOnMouseOut:true}});hs.Expander.prototype.onBeforeExpand=function(){onImageExpand(this.a);};(function(d){d.i18n['de']=d.i18n['de-DE']=d.i18n['de-CH']={months:{abbr:['Jan','Feb','M\u00E4r','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dec'],full:['Januar','Februar','M\u00E4rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember']},days:{abbr:['So','Mo','Di','Mi','Do','Fr','Sa'],full:['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag']},week:{abbr:'W',full:'Woche'},formats:{dateShort:'d.M.yyyy',dateMedium:'d. MMM. yyyy',dateLong:'d. MMMM yyyy',timeShort:'HH:mm',timeMedium:'HH:mm',timeLong:'HH:mm:ss',dateTimeShort:'d.M.yyyy HH:mm',dateTimeMedium:'d. MMM. yyyy HH:mm',dateTimeLong:'EEEE, d. MMMM yyyy HH:mm'},ad:'n. Chr.',am:'vorm.',pm:'nachm.',gmt:'GMT',z:':',Z:'',fdow:1,mdifw:4};})(Date);(function(d){d.i18n['fr']=d.i18n['fr-FR']={months:{abbr:['jan','f\u00E9v','mar','avr','mai','juin','juil','ao\u00FBt','sept','oct','nov','dec'],full:['janvier','f\u00E9vrier','mars','avril','mai','juin','juiller','ao\u00FBt','septembre','octobre','novembre','d\u00E9cembre']},days:{abbr:['dim','lun','mar','mer','jeu','ven','sam'],full:['dimanche','lundi','mardi','mercredi','jeudi','vendredi','samedi']},week:{abbr:'sem',full:'semaine'},formats:{dateShort:'d/MM/yyyy',dateMedium:'d MMM. yyyy',dateLong:'d MMMM yyyy',timeShort:'HH:mm',timeMedium:'HH:mm',timeLong:'HH:mm:ss',dateTimeShort:'d/MM/yyyy HH:mm',dateTimeMedium:'d MMM. yyyy HH:mm',dateTimeLong:'EEEE, d MMMM yyyy HH:mm'},ad:'apr. J.-C.',am:'am',pm:'pm',gmt:'GMT',z:':',Z:'',fdow:1,mdifw:4};})(Date);(function(d){d.i18n['es']=d.i18n['es-ES']={months:{abbr:['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Set','Oct','Nov','Dic'],full:['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Setiembre','Octubre','Noviembre','Diciembre']},days:{abbr:['Dom','Lun','Mar','Mie','Jue','Vie','Sab'],full:['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','S\u00E1bado']},week:{abbr:'sem',full:'semana'},formats:{dateShort:'d/MM/yyyy',dateMedium:'d MMM. yyyy',dateLong:'d \'de\' MMMM \'de\' yyyy',timeShort:'HH:mm',timeMedium:'HH:mm',timeLong:'HH:mm:ss',dateTimeShort:'d/MM/yyyy HH:mm',dateTimeMedium:'d MMM. yyyy HH:mm',dateTimeLong:'EEEE, d \'de\' MMMM \'de\' yyyy HH:mm'},ad:'D. C.',am:'AM',pm:'PM',gmt:'GMT',z:':',Z:'',fdow:1,mdifw:4};})(Date);function LabeledMarker(latlng,opt_opts){this.latlng_=latlng;this.opts_=opt_opts;this.labelText_=opt_opts.labelText||"";this.labelClass_=opt_opts.labelClass||"LabeledMarker_markerLabel";this.labelOffset_=opt_opts.labelOffset||new GSize(0,0);this.clickable_=opt_opts.clickable||true;this.title_=opt_opts.title||"";this.labelVisibility_=true;if(opt_opts.draggable){opt_opts.draggable=false;}
GMarker.apply(this,arguments);};LabeledMarker.prototype=new GMarker(new GLatLng(0,0));LabeledMarker.prototype.initialize=function(map){GMarker.prototype.initialize.apply(this,arguments);this.map_=map;this.div_=document.createElement("div");this.div_.className=this.labelClass_;this.div_.innerHTML=this.labelText_;this.div_.style.position="absolute";this.div_.style.cursor="pointer";this.div_.title=this.title_;map.getPane(G_MAP_MARKER_PANE).appendChild(this.div_);if(this.clickable_){function newEventPassthru(obj,event){return function(){GEvent.trigger(obj,event);};}
var eventPassthrus=['click','dblclick','mousedown','mouseup','mouseover','mouseout'];for(var i=0;i<eventPassthrus.length;i++){var name=eventPassthrus[i];GEvent.addDomListener(this.div_,name,newEventPassthru(this,name));}}};LabeledMarker.prototype.redraw=function(force){GMarker.prototype.redraw.apply(this,arguments);this.redrawLabel_();};LabeledMarker.prototype.redrawLabel_=function(){var p=this.map_.fromLatLngToDivPixel(this.latlng_);var z=(this.opts_.zIndexProcess?this.opts_.zIndexProcess(this):GOverlay.getZIndex(this.latlng_.lat()))+1;this.div_.style.left=(p.x+this.labelOffset_.width)+"px";this.div_.style.top=(p.y+this.labelOffset_.height)+"px";this.div_.style.zIndex=z;};LabeledMarker.prototype.remove=function(){GEvent.clearInstanceListeners(this.div_);if(this.div_.outerHTML){this.div_.outerHTML="";}
if(this.div_.parentNode){this.div_.parentNode.removeChild(this.div_);}
this.div_=null;GMarker.prototype.remove.apply(this,arguments);};LabeledMarker.prototype.copy=function(){return new LabeledMarker(this.latlng_,this.opts_);};LabeledMarker.prototype.show=function(){GMarker.prototype.show.apply(this,arguments);if(this.labelVisibility_){this.showLabel();}else{this.hideLabel();}};LabeledMarker.prototype.hide=function(){GMarker.prototype.hide.apply(this,arguments);this.hideLabel();};LabeledMarker.prototype.setLatLng=function(latlng){this.latlng_=latlng;GMarker.prototype.setLatLng.apply(this,arguments);this.redrawLabel_();};LabeledMarker.prototype.setLabelVisibility=function(visibility){this.labelVisibility_=visibility;if(!this.isHidden()){if(this.labelVisibility_){this.showLabel();}else{this.hideLabel();}}};LabeledMarker.prototype.getLabelVisibility=function(){return this.labelVisibility_;};LabeledMarker.prototype.hideLabel=function(){this.div_.style.visibility='hidden';};LabeledMarker.prototype.showLabel=function(){this.div_.style.visibility='visible';};if(!window.I18n){I18n={};}
I18n.defaultLocale="en";I18n.translations={"de":{"calendar_date_select":{"translations":{"OK":"OK","Close":"Schlie\u00dfen","Clear":"L\u00f6schen","At":"Um","Now":"Jetzt","Today":"Heute"},"date":{"weekdays":["So","Mo","Di","Mi","Do","Fr","Sa"],"months":["Januar","Februar","M\u00e4rz","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"]}},"rendezvous":{"place_event_choice_1":"gut","add_date":"F\u00fcgen Sie ein Zeitfenster!","close_popup":"Dieses Fensters schliessen","confirm":{"reset_all_votes_time_slot":"Alle Stimmen f\u00fcr diese Zeit werden gel\u00f6scht. Fortfahren?","reset_all_votes_day":"Alle Stimmen an diesem Tag werden gel\u00f6scht. Fortfahren?","delete_time_slot":"Wollen Sie diese Zeit wirklich l\u00f6schen?","close":"Nicht gespeicherte \u00c4nderungen gehen verloren. Fortfahren?","delete_day":"Wollen Sie diesen Tag wirklich l\u00f6schen?"},"choice_-1":"nein","remove_place_or_event":"l\u00f6schen Ort oder ein Ereignis von Rendezvous","delete_person":"L\u00f6schen","send":"Speichern und Senden von Benachrichtigungen","choice_1":"ja","help":{"place_4":"Durch einen auf die Schaltfl\u00e4che in einer Vitrine.","place_5":"Durch einen Klick auf den Link in der Event-Anzeige","date_2":"Um einen Termin hinzuzuf\u00fcgen, klicken Sie einfach auf die Schaltfl\u00e4che \"Hinzuf\u00fcgen\"","help":"Hilfe","person_1":"Wenn Sie angemeldet sind, stehen Ihnen all Ihre Kontakte zur Verf\u00fcgung. Tippen Sie einfach die Anfangsbuchstaben eines Namens in Ihrer Kontaktliste.","place_1":"Es gibt mehrere M\u00f6glichkeiten, Orte oder Veranstaltungen zu einem Rendezvous hinzuf\u00fcgen:","can_add":"Deaktivieren Sie diese Optionen, umTeilnehmer daran hindern, weitere Daten, Menschen oder Orte hinzuzuf\u00fcgen.","place_2":"Mit einem Klick auf die kleinen Symbole in der rechten Seitenleiste.","anonymous_2":"Dazu geben Sie Ihren Namen in das Eingabefeld ein und speichern das Rendezvous.","place_3":"Mit einem Klick auf den Link in der Ortsbeschreibung.","person_2":"Schicken Sie diesen pers\u00f6nlichen Link an Ihre Freunde, um sie einzuladen.","anonymous_1":"Wenn Sie nicht eingeloggt sind, k\u00f6nnen Sie nur sich selbst hinzuf\u00fcgen","date_1":"Sie k\u00f6nnen Datum und Uhrzeit \u00e4ndern, indem Sie sie anklicken.","secret_link":"Schicken Sie diesen pers\u00f6nlichen Link an Ihre Freunde, um sie einzuladen."},"place_event_choice_2":"besser","save_or_send":"Einige Teilnehmer wurden noch nicht per Email informiert. Soll dies nun geschehen?","save_button_title":"Rendezvous speichern","click_for_details":"Klicken f\u00fcr Details","place_event_choice_-1":"schlecht","login_to_modify_choice_notice":"Bitte loggen Sie sich ein, um Ihre Auswahl zu \u00e4ndern.","place_event_choice_0":"?","save":"Rendezvous speichern","saved_button_title":"Rendezvous gespeichert","remove_date":"Entfernen Sie dieses Zeitfenster!","back":"Zur\u00fcck","choice_0":"?","place_event_choice_-2":"schlechter"},"users":{"new":{"title":"Einschreibeformular"}},"intro":{"shortcut":{"rest":"Restaurant","search_place":"Suche einen Platz","club":"Night club","must":"Must see","bar":"Bar","acc":"Unterkunft"}},"messaging":{"nongeoloc":"Ohne Ortsangabe","hidden":"versteckt","unread":"ungelesen","enabled":"Nachrichten erscheinen auf der Karte","outofscope":"ausserhalb des angezeigten Bereichs","disabled":"Die neusten Nachrichten werden nicht mehr auf der Karte angezeigt","out_of_map":"Die folgenden ungelesene Nachrichten k\u00f6nnen nicht auf der Karte angezeigt werden: sie sind entweder ausserhalb des angezeigten Bereichs geschrieben worden oder haben keine Ortsangabe."},"shared":{"no":"Nein","yes":"Ja"},"create_place":"Einen Platz hinzuf\u00fcgen","register":{"fb_title":"Registrieren Sie sich bei Facebook","open_id_title":"Registrieren Sie sich mittels OpenID","mil_title":"Normales MadeinLocal-Konto"},"place":{"book":"Buchen"},"map_directions":{"missing_query":"Der HTTP-Q-Parameter ist entweder nicht vorhanden oder hat keinen Wert. F\u00fcr geocoder Zugriffe bedeutet dies, dass eine leere Adresse eingegeben wurde.","bad_request":"Eine Anfrage konnte nicht erfolgreich analysiert werden.","unknown_error":"Ein unbekannter Fehler ist aufgetreten.","server_error":"Ein Geocoding- oder andere Anfrage konnte nicht erfolgreich verarbeitet werden, aber den genauen Grund f\u00fcr das Scheitern ist nicht bekannt.","unknown_address":"Keine entsprechende Lage wurde zur angegebenen Adressen gefunden. M\u00f6glicherweise ist die Adresse relativ neu oder ung\u00fcltig.","bad_key":"Der angegebene Schl\u00fcssel ist entweder ung\u00fcltig oder passt nicht zur Dom\u00e4ne, f\u00fcr die er eingegeben wurde."},"positioning_pointer_inactive":"Das Hinzuf\u00fcgen eines Platzes wurde abgebrochen.","search_tab_already_open":"Dieses Register ist bereits ge\u00f6ffnet.","positioning_pointer_active":"Bitte klicke auf den Ort, wo du deinen Platz hinzuf\u00fcgen willst."},"en":{"calendar_date_select":{"translations":{"OK":"OK","Close":"Close","Clear":"Clear","At":"At","Now":"Now","Today":"Today"},"date":{"first_day_of_week":0,"weekdays":["Su","Mo","Tu","We","Th","Fr","Sa"],"months":["January","February","March","April","May","June","July","August","September","October","November","December"]}},"rendezvous":{"place_event_choice_1":"good","add_date":"Add a time slot!","close_popup":"Close this pop-up","confirm":{"reset_all_votes_time_slot":"Modifying this time slot will reset all votes. Continue?","reset_all_votes_day":"Modifying this day will reset all votes. Continue?","delete_time_slot":"Do you really want to delete this time slot?","close":"Changes you made will be lost. Continue?","delete_day":"Do you really want to delete this day?"},"choice_-1":"no","remove_place_or_event":"delete place or event from rendezvous","delete_person":"Delete this person!","send":"Save and send notifications","choice_1":"yes","help":{"place_4":"Clicking the button in a showcase.","place_5":"Clicking the links in the events feed.","date_2":"To add a date, simply click on the add button","help":"Help","person_1":"When logged in, you can add friends or people you've manually added in your contact list. For this, type the first letters of their name in the input field.","place_1":"There are several ways to add places or events to a rendezvous:","can_add":"Untick these options to prevent participants from adding other dates, people, or places and events.","place_2":"Clicking on the small icons in the right sidebar.","anonymous_2":"For this, enter your name in the input field and submit.","place_3":"Clicking the link in a place bubble.","person_2":"If you want to invite other people to this rendezvous, send them the secret link.","anonymous_1":"If you aren't logged in, you can add one person only, i.e. yourself.","date_1":"You can modify dates and times by clicking them.","secret_link":"Share this link to invite other people to this rendezvous."},"place_event_choice_2":"best","save_or_send":"Some participants haven't been notified yet. Do you want to send them an e-mail now?","save_button_title":"Save the rendezvous","click_for_details":"Click to see more details","place_event_choice_-1":"bad","login_to_modify_choice_notice":"Please log in to modify your choices.","place_event_choice_0":"?","save":"Save this rendezvous","saved_button_title":"Rendezvous saved","remove_date":"Remove this time slot!","back":"Back","choice_0":"?","place_event_choice_-2":"worst"},"users":{"new":{"title":"Register for MadeinLocal"}},"intro":{"shortcut":{"rest":"Restaurant","search_place":"Search a place","club":"Club","must":"Must see","bar":"Bar","acc":"Accommodation"}},"messaging":{"nongeoloc":"non geolocalized","hidden":"hidden","unread":"unread","enabled":"Latest messages appear on the map","outofscope":"out of scope","disabled":"Latest message not displayed anymore on the map","out_of_map":"The following unread messages cannot be displayed on map: they are either out of scope or not geolocalized or their author made them hidden."},"shared":{"no":"No","yes":"Yes"},"create_place":"Create place","register":{"fb_title":"Register with Facebook","open_id_title":"Register with OpenID","mil_title":"Plain MadeinLocal account"},"place":{"book":"Book it"},"map_directions":{"missing_query":"The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.","bad_request":"A directions request could not be successfully parsed.","unknown_error":"An unknown error occurred.","server_error":"A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.","unknown_address":"No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.","bad_key":"The given key is either invalid or does not match the domain for which it was given."},"positioning_pointer_inactive":"Positionning cursor deactivated","search_tab_already_open":"This tab is already open.","positioning_pointer_active":"Please click where you want to add your place."},"fr":{"calendar_date_select":{"translations":{"OK":"OK","Close":"Fermer","Clear":"Effacer","At":"\u00c0","Now":"Maintenant","Today":"Aujourd'hui"},"date":{"first_day_of_week":1,"weekdays":["Lu","Ma","Me","Je","Ve","Sa","Di"],"months":["Janvier","F\u00e9vrier","Mars","Avril","Mai","Juin","Juillet","Ao\u00fbt","Septembre","Octobre","Novembre","D\u00e9cembre"]}},"rendezvous":{"place_event_choice_1":"oui","add_date":"Ajoute une date !","close_popup":"Fermer cette fen\u00eatre","confirm":{"reset_all_votes_time_slot":"La modification de cette tranche horaire annulera tous les votes. Continuer\u00a0?","reset_all_votes_day":"La modification de cette journ\u00e9e annulera tous les votes. Continuer\u00a0?","delete_time_slot":"Veux-tu vraiment supprimer cette tranche horaire\u00a0?","close":"Les changements effectu\u00e9s seront perdus. Continuer ?","delete_day":"Veux-tu vraiement effacer ce jour\u00a0?"},"choice_-1":"non","remove_place_or_event":"supprimer le lieu ou l'\u00e9v\u00e8nement du rendez-vous","delete_person":"Supprimer ce participant !","send":"Enregistrer ce rendez-vous et envoyer les e-mails d'invitation","choice_1":"oui","help":{"place_4":"Cliquer sur le bouton d'une vitrine.","place_5":"Cliquer sur les liens de la liste des \u00e9v\u00e8nements.","date_2":"Pour ajouter une date, clique sur le bouton ","help":"Aide","person_1":"Si tu es connect\u00e9, tu peux ajouter des amis et des gens dans ta liste de contacts. Pour cela, tape les premi\u00e8res lettres de leur nom dans le champ.","place_1":"Il y a plusieurs mani\u00e8res d'ajouter des lieus et \u00e9v\u00e8nements\u00a0:","can_add":"D\u00e9coche ces options pour emp\u00eacher les participants d'ajouter d'autres dates, personnes ou lieux et \u00e9v\u00e9nements.","place_2":"Cliquer sur les petites ic\u00f4nes dans la barre de droite.","anonymous_2":"Pour cela, entre ton nom dans le champ et valide.","place_3":"Cliquer sur le lien dans une bulle.","person_2":"Si tu veux ajouter d'autres personnes au rendez-vous, envoie leur le lien secret.","anonymous_1":"Si tu n'es pas connect\u00e9, tu ne peux ajouter qu'une seule personne.","date_1":"Tu peux modifier les dates et heures en cliquant dessus.","secret_link":"Partage ce lien pour inviter d'autres personnes au rendez-vous."},"place_event_choice_2":"super","save_or_send":"Certains participants n'ont pas encore \u00e9t\u00e9 avertis. D\u00e9sire-tu leur envoyer un e-mail maintenant\u00a0?","save_button_title":"Sauver le rendez-vous","click_for_details":"Cliquer pour voir plus de d\u00e9tails","place_event_choice_-1":"bof","login_to_modify_choice_notice":"Connecte-toi pour modifier tes choix.","place_event_choice_0":"?","save":"Enregistrer ce rendez-vous","saved_button_title":"Rendez-vous enregistr\u00e9","remove_date":"Supprime cette date !","back":"Retour","choice_0":"?","place_event_choice_-2":"surtout pas"},"users":{"new":{"title":"S'inscrire"}},"intro":{"shortcut":{"rest":"Restaurant","search_place":"Rechercher un lieu","club":"Club","must":"Lieu d'int\u00e9r\u00eat","bar":"Bar","acc":"H\u00e9bergement"}},"messaging":{"nongeoloc":"non g\u00e9olocalis\u00e9","hidden":"cach\u00e9","unread":"non lu","enabled":"Les derniers messages appara\u00eessent sur la carte","outofscope":"hors de port\u00e9e","disabled":"Les derniers messages n'appara\u00eessent plus sur la carte","out_of_map":"Les messages non lus suivants ne peuvent pas \u00eatre affich\u00e9s sur la carte\u00a0: ils sont soit hors de port\u00e9e, soit non g\u00e9olocalis\u00e9s, soit leur cr\u00e9ateur les a masqu\u00e9s."},"shared":{"no":"Non","yes":"Oui"},"create_place":"Cr\u00e9er un lieu","register":{"fb_title":"S'inscrire avec Facebook","open_id_title":"S'inscrire avec OpenID","mil_title":"Compte MadeinLocal standard"},"place":{"book":"R\u00e9server"},"map_directions":{"missing_query":"Le param\u00e8tre HTTP q est absent ou n'a pas de valeur. Pour les demandes de g\u00e9ocodage, cela signifie qu'une adresse vide a \u00e9t\u00e9 sp\u00e9cifi\u00e9 en entr\u00e9e. Pour les demandes de directions, cela signifie qu'aucune requ\u00eate n'a \u00e9t\u00e9 sp\u00e9cifi\u00e9 dans l'entr\u00e9e.","bad_request":"Une demande de directions n'a pas pu etre pars\u00e9e correctement","unknown_error":"Une erreur inconnue est survenue","server_error":"Une requ\u00eate de directions ou geocodage n'a pas pu \u00eatre trait\u00e9e avec succ\u00e8s, or la raison de cette d\u00e9faillance n'est pas connue.","unknown_address":"Aucune endroit n'a \u00e9t\u00e9 trouv\u00e9 pour l'une des adresses fournies. L'adresse est peut-\u00eatre relativement nouvelle ou incorrecte.","bad_key":"La cl\u00e9 est invalide ou elle ne correspond pas au nom de domaine pour lequel elle a \u00e9t\u00e9 cr\u00e9\u00e9e"},"positioning_pointer_inactive":"Curseur de positionnement desactiv\u00e9","search_tab_already_open":"Cet onglet est d\u00e9j\u00e0 ouvert","positioning_pointer_active":"Curseur de positionnement activ\u00e9","welcome":{"shortcut":null}},"es":{"calendar_date_select":{"translations":{"OK":"OK","Close":"Cerrar","Clear":"Cancelar","At":"A las","Now":"Ahora","Today":"Hoy"},"date":{"weekdays":["Do","Lu","Ma","Mi","Ju","Vi","Sa"],"months":["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]}},"rendezvous":{"place_event_choice_1":"si","add_date":"A\u00f1ade un intervalo de tiempo!","close_popup":"Cerrar esta ventana","confirm":{"reset_all_votes_time_slot":"Al modificar esta hora los votos volver\u00e1n a cero.\u00bfQuieres continuar?","reset_all_votes_day":"Al modificar este d\u00eda los votos volver\u00e1n a cero.\u00bfQuieres continuar?","delete_time_slot":"\u00bfEst\u00e1s seguro de borrar esta hora?","close":"Los cambios realizados se perder\u00e1n. \u00bfContinuar?","delete_day":"\u00bfEst\u00e1s seguro de borrar este d\u00eda?"},"choice_-1":"no","remove_place_or_event":"eliminar lugar o evento de la cita","delete_person":"Borrar esta persona!","send":"Salvar y enviar notificaciones","choice_1":"si","help":{"place_4":"Haciendo clic en el bot\u00f3n en un escaparate.","place_5":"Haciendo clic en los enlaces de los eventos.","date_2":"Para a\u00f1adir una fecha, simplemente haz clic en el bot\u00f3n A\u00f1adir","help":"Ayuda","person_1":"Cuando est\u00e1s conectado, puedes a\u00f1adir amigos o personas que a\u00f1adas manualmente en tu lista de contactos. Para ello, escribe las primeras letras de su nombre en el campo.","place_1":"Hay varias formas de a\u00f1adir lugares o eventos a una cita:","can_add":"Desmarca estas opciones para evitar que los participantes puedan a\u00f1adir otras fechas, personas o lugares y eventos.","place_2":"Haciendo clic en los iconos peque\u00f1os en la barra lateral derecha.","anonymous_2":"Para ello, escribe tu nombre en el campo y haz clic.","place_3":"Haciendo clic en el v\u00ednculo de una burbuja de un lugar.","person_2":"Si deseas invitar a otras personas a esta cita, env\u00edales el enlace secreto.","anonymous_1":"Si no est\u00e1s registrado, s\u00f3lo puedes a\u00f1adir una persona, es decir, a ti mismo.","date_1":"Puedes modificar las fechas y horas haciendo clic en ellos.","secret_link":"Compartir este enlace para invitar a otras personas a esta cita."},"place_event_choice_2":"super","save_or_send":"\u00bfEst\u00e1s seguro de salvar solamente, o enviar tambi\u00e9n un email a los partipantes que no han sido notificados a\u00fan?","save_button_title":"Guardar la cita","click_for_details":"Haz clic aqu\u00ed para ver m\u00e1s detalles","place_event_choice_-1":"no","login_to_modify_choice_notice":"Es necesario conectarse para modificar tu opini\u00f3n.","place_event_choice_0":"?","save":"Salvar esta cita","saved_button_title":"Cita guardada","remove_date":"Elimina este intervalo de tiempo!","back":"Volver","choice_0":"?","place_event_choice_-2":"no, no y no"},"users":{"new":{"title":"Inscripci\u00f3n a MadeinLocal.com"}},"intro":{"shortcut":{"rest":"Restaurante","event":"Evento","search_place":"Buscar un lugar","club":"Disco","must":"Lugar de inter\u00e9s","bar":"Bar","acc":"Alojamiento"}},"messaging":{"nongeoloc":"no geolocalizado","hidden":"oculto","unread":"no le\u00eddos","enabled":"\u00daltimo mensaje aparece en el mapa","outofscope":"fuera de alcance","disabled":"\u00daltimo mensaje no aparece ya en el mapa","out_of_map":"Los siguientes mensajes no le\u00eddos no se pueden mostrar en el mapa: se sit\u00faan fuera del mapa o no est\u00e1n geolocalizados o el autor los ha escondido."},"shared":{"no":"No","yes":"S\u00ed"},"create_place":"Crear un lugar","register":{"fb_title":"Inscribirse con Facebook","open_id_title":"Inscribirse con OpenID","mil_title":"Cuenta MadeinLocal estandar"},"place":{"book":"Reserva"},"map_directions":{"missing_query":"El HTTP q parametro falta o no tiene valor. Para solicitudes geocodificadas, esto significa que una direcci\u00f3n vac\u00eda ha sido especificada como entrada. Para solicitudes de direcciones, esto significa que ninguna solicitud ha sido especificada como entrada.","bad_request":"La petici\u00f3n de una direcci\u00f3n no ha podido ser tratada (error de parsing)","unknown_error":"Un error desconocido ha sido detectado","server_error":"Una petici\u00f3n de direcci\u00f3n de geocodificaci\u00f3n no ha podido ser tratado por una raz\u00f3n desconocida.","unknown_address":"Ning\u00fan lugar ha sido encontrado con la direcci\u00f3n indicada. Puede ser que la direcci\u00f3n sea relativamente nueva o que sea incorrecta.","bad_key":"La clave indicada es invalida o no corresponde al dominio para la que fu\u00e9 creada."},"positioning_pointer_inactive":"Puntero de posicionamiento desactivado","search_tab_already_open":"Esta pesta\u00f1a ya est\u00e1 abierta","positioning_pointer_active":"Puntero de posicionamiento activado","welcome":{"shortcut":{"search_place":""}}}};(function(){var interpolatePattern=/\{\{([^}]+)\}\}/g;function interpolate(str,obj){return str.replace(interpolatePattern,function(){return obj[arguments[1]]||arguments[0];});};function keyToArray(key){if(!key)return[];if(typeof key!="string")return key;return key.split('.');};function locale(){return I18n.locale||I18n.defaultLocale;};function getLocaleFromCookie(){var cookies=document.cookie.split(/\s*;\s*/),i,pair,locale;for(i=0;i<cookies.length;i++){pair=cookies[i].split('=');if(pair[0]==='locale'){locale=pair[1];break;}}
return locale;};I18n.init=function(){this.locale=getLocaleFromCookie();};I18n.translate=function(key,opts){if(typeof key!="string"){var a=[],i;for(i=0;i<key.length;i++){a.push(this.translate(key[i],opts));}
return a;}else{opts=opts||{};opts.defaultValue=opts.defaultValue||null;key=keyToArray(opts.scope).concat(keyToArray(key));var value=this.lookup(key,opts.defaultValue);if(typeof value!="string"&&value)value=this.pluralize(value,opts.count);if(typeof value=="string")value=interpolate(value,opts);return value;}};I18n.t=I18n.translate;I18n.lookup=function(keys,defaults){var i=0,value=this.translations[locale()];defaults=typeof defaults=="string"?[defaults]:(defaults||[]);while(keys[i]){value=value&&value[keys[i]];i++;}
if(value){return value;}else{if(defaults.length==0){return null;}else if(defaults[0].substr(0,1)==':'){return this.lookup(keys.slice(0,keys.length-1).concat(keyToArray(defaults[0].substr(1))),defaults.slice(1));}else{return defaults[0];}}};I18n.pluralize=function(value,count){if(!count)return value;return count==1?value.one:value.other;};})();I18n.init();function MarkerManager(map,opt_opts){var me=this;me.map_=map;me.mapZoom_=map.getZoom();me.projection_=map.getCurrentMapType().getProjection();opt_opts=opt_opts||{};me.tileSize_=MarkerManager.DEFAULT_TILE_SIZE_;var maxZoom=MarkerManager.DEFAULT_MAX_ZOOM_;if(opt_opts.maxZoom!=undefined){maxZoom=opt_opts.maxZoom;}
me.maxZoom_=maxZoom;me.trackMarkers_=opt_opts.trackMarkers;var padding;if(typeof opt_opts.borderPadding=="number"){padding=opt_opts.borderPadding;}else{padding=MarkerManager.DEFAULT_BORDER_PADDING_;}
me.swPadding_=new GSize(-padding,padding);me.nePadding_=new GSize(padding,-padding);me.borderPadding_=padding;me.gridWidth_=[];me.grid_=[];me.grid_[maxZoom]=[];me.numMarkers_=[];me.numMarkers_[maxZoom]=0;GEvent.bind(map,"moveend",me,me.onMapMoveEnd_);me.removeOverlay_=function(marker){map.removeOverlay(marker);me.shownMarkers_--;};me.addOverlay_=function(marker){map.addOverlay(marker);me.shownMarkers_++;};me.resetManager_();me.shownMarkers_=0;me.shownBounds_=me.getMapGridBounds_();};MarkerManager.DEFAULT_TILE_SIZE_=1024;MarkerManager.DEFAULT_MAX_ZOOM_=17;MarkerManager.DEFAULT_BORDER_PADDING_=100;MarkerManager.MERCATOR_ZOOM_LEVEL_ZERO_RANGE=256;MarkerManager.prototype.resetManager_=function(){var me=this;var mapWidth=MarkerManager.MERCATOR_ZOOM_LEVEL_ZERO_RANGE;for(var zoom=0;zoom<=me.maxZoom_;++zoom){me.grid_[zoom]=[];me.numMarkers_[zoom]=0;me.gridWidth_[zoom]=Math.ceil(mapWidth/me.tileSize_);mapWidth<<=1;}};MarkerManager.prototype.clearMarkers=function(){var me=this;me.processAll_(me.shownBounds_,me.removeOverlay_);me.resetManager_();};MarkerManager.prototype.getTilePoint_=function(latlng,zoom,padding){var pixelPoint=this.projection_.fromLatLngToPixel(latlng,zoom);return new GPoint(Math.floor((pixelPoint.x+padding.width)/this.tileSize_),Math.floor((pixelPoint.y+padding.height)/this.tileSize_));};MarkerManager.prototype.addMarkerBatch_=function(marker,minZoom,maxZoom){var mPoint=marker.getPoint();if(this.trackMarkers_){GEvent.bind(marker,"changed",this,this.onMarkerMoved_);}
var gridPoint=this.getTilePoint_(mPoint,maxZoom,GSize.ZERO);for(var zoom=maxZoom;zoom>=minZoom;zoom--){var cell=this.getGridCellCreate_(gridPoint.x,gridPoint.y,zoom);cell.push(marker);gridPoint.x=gridPoint.x>>1;gridPoint.y=gridPoint.y>>1;}};MarkerManager.prototype.isGridPointVisible_=function(point){var me=this;var vertical=me.shownBounds_.minY<=point.y&&point.y<=me.shownBounds_.maxY;var minX=me.shownBounds_.minX;var horizontal=minX<=point.x&&point.x<=me.shownBounds_.maxX;if(!horizontal&&minX<0){var width=me.gridWidth_[me.shownBounds_.z];horizontal=minX+width<=point.x&&point.x<=width-1;}
return vertical&&horizontal;}
MarkerManager.prototype.onMarkerMoved_=function(marker,oldPoint,newPoint){var me=this;var zoom=me.maxZoom_;var changed=false;var oldGrid=me.getTilePoint_(oldPoint,zoom,GSize.ZERO);var newGrid=me.getTilePoint_(newPoint,zoom,GSize.ZERO);while(zoom>=0&&(oldGrid.x!=newGrid.x||oldGrid.y!=newGrid.y)){var cell=me.getGridCellNoCreate_(oldGrid.x,oldGrid.y,zoom);if(cell){if(me.removeFromArray(cell,marker)){me.getGridCellCreate_(newGrid.x,newGrid.y,zoom).push(marker);}}
if(zoom==me.mapZoom_){if(me.isGridPointVisible_(oldGrid)){if(!me.isGridPointVisible_(newGrid)){me.removeOverlay_(marker);changed=true;}}else{if(me.isGridPointVisible_(newGrid)){me.addOverlay_(marker);changed=true;}}}
oldGrid.x=oldGrid.x>>1;oldGrid.y=oldGrid.y>>1;newGrid.x=newGrid.x>>1;newGrid.y=newGrid.y>>1;--zoom;}
if(changed){me.notifyListeners_();}};MarkerManager.prototype.removeMarker=function(marker){var me=this;var zoom=me.maxZoom_;var changed=false;var point=marker.getPoint();var grid=me.getTilePoint_(point,zoom,GSize.ZERO);while(zoom>=0){var cell=me.getGridCellNoCreate_(grid.x,grid.y,zoom);if(cell){me.removeFromArray(cell,marker);}
if(zoom==me.mapZoom_){if(me.isGridPointVisible_(grid)){me.removeOverlay_(marker);changed=true;}}
grid.x=grid.x>>1;grid.y=grid.y>>1;--zoom;}
if(changed){me.notifyListeners_();}};MarkerManager.prototype.addMarkers=function(markers,minZoom,opt_maxZoom){var maxZoom=this.getOptMaxZoom_(opt_maxZoom);for(var i=markers.length-1;i>=0;i--){this.addMarkerBatch_(markers[i],minZoom,maxZoom);}
this.numMarkers_[minZoom]+=markers.length;};MarkerManager.prototype.getOptMaxZoom_=function(opt_maxZoom){return opt_maxZoom!=undefined?opt_maxZoom:this.maxZoom_;}
MarkerManager.prototype.getMarkerCount=function(zoom){var total=0;for(var z=0;z<=zoom;z++){total+=this.numMarkers_[z];}
return total;};MarkerManager.prototype.addMarker=function(marker,minZoom,opt_maxZoom){var me=this;var maxZoom=this.getOptMaxZoom_(opt_maxZoom);me.addMarkerBatch_(marker,minZoom,maxZoom);var gridPoint=me.getTilePoint_(marker.getPoint(),me.mapZoom_,GSize.ZERO);if(me.isGridPointVisible_(gridPoint)&&minZoom<=me.shownBounds_.z&&me.shownBounds_.z<=maxZoom){me.addOverlay_(marker);me.notifyListeners_();}
this.numMarkers_[minZoom]++;};GBounds.prototype.containsPoint=function(point){var outer=this;return(outer.minX<=point.x&&outer.maxX>=point.x&&outer.minY<=point.y&&outer.maxY>=point.y);}
MarkerManager.prototype.getGridCellCreate_=function(x,y,z){var grid=this.grid_[z];if(x<0){x+=this.gridWidth_[z];}
var gridCol=grid[x];if(!gridCol){gridCol=grid[x]=[];return gridCol[y]=[];}
var gridCell=gridCol[y];if(!gridCell){return gridCol[y]=[];}
return gridCell;};MarkerManager.prototype.getGridCellNoCreate_=function(x,y,z){var grid=this.grid_[z];if(x<0){x+=this.gridWidth_[z];}
var gridCol=grid[x];return gridCol?gridCol[y]:undefined;};MarkerManager.prototype.getGridBounds_=function(bounds,zoom,swPadding,nePadding){zoom=Math.min(zoom,this.maxZoom_);var bl=bounds.getSouthWest();var tr=bounds.getNorthEast();var sw=this.getTilePoint_(bl,zoom,swPadding);var ne=this.getTilePoint_(tr,zoom,nePadding);var gw=this.gridWidth_[zoom];if(tr.lng()<bl.lng()||ne.x<sw.x){sw.x-=gw;}
if(ne.x-sw.x+1>=gw){sw.x=0;ne.x=gw-1;}
var gridBounds=new GBounds([sw,ne]);gridBounds.z=zoom;return gridBounds;};MarkerManager.prototype.getMapGridBounds_=function(){var me=this;return me.getGridBounds_(me.map_.getBounds(),me.mapZoom_,me.swPadding_,me.nePadding_);};MarkerManager.prototype.onMapMoveEnd_=function(){var me=this;me.objectSetTimeout_(this,this.updateMarkers_,0);};MarkerManager.prototype.objectSetTimeout_=function(object,command,milliseconds){return window.setTimeout(function(){command.call(object);},milliseconds);};MarkerManager.prototype.refresh=function(){var me=this;if(me.shownMarkers_>0){me.processAll_(me.shownBounds_,me.removeOverlay_);}
me.processAll_(me.shownBounds_,me.addOverlay_);me.notifyListeners_();};MarkerManager.prototype.updateMarkers_=function(){var me=this;me.mapZoom_=this.map_.getZoom();var newBounds=me.getMapGridBounds_();if(newBounds.equals(me.shownBounds_)&&newBounds.z==me.shownBounds_.z){return;}
if(newBounds.z!=me.shownBounds_.z){me.processAll_(me.shownBounds_,me.removeOverlay_);me.processAll_(newBounds,me.addOverlay_);}else{me.rectangleDiff_(me.shownBounds_,newBounds,me.removeCellMarkers_);me.rectangleDiff_(newBounds,me.shownBounds_,me.addCellMarkers_);}
me.shownBounds_=newBounds;me.notifyListeners_();};MarkerManager.prototype.notifyListeners_=function(){GEvent.trigger(this,"changed",this.shownBounds_,this.shownMarkers_);};MarkerManager.prototype.processAll_=function(bounds,callback){for(var x=bounds.minX;x<=bounds.maxX;x++){for(var y=bounds.minY;y<=bounds.maxY;y++){this.processCellMarkers_(x,y,bounds.z,callback);}}};MarkerManager.prototype.processCellMarkers_=function(x,y,z,callback){var cell=this.getGridCellNoCreate_(x,y,z);if(cell){for(var i=cell.length-1;i>=0;i--){callback(cell[i]);}}};MarkerManager.prototype.removeCellMarkers_=function(x,y,z){this.processCellMarkers_(x,y,z,this.removeOverlay_);};MarkerManager.prototype.addCellMarkers_=function(x,y,z){this.processCellMarkers_(x,y,z,this.addOverlay_);};MarkerManager.prototype.rectangleDiff_=function(bounds1,bounds2,callback){var me=this;me.rectangleDiffCoords(bounds1,bounds2,function(x,y){callback.apply(me,[x,y,bounds1.z]);});};MarkerManager.prototype.rectangleDiffCoords=function(bounds1,bounds2,callback){var minX1=bounds1.minX;var minY1=bounds1.minY;var maxX1=bounds1.maxX;var maxY1=bounds1.maxY;var minX2=bounds2.minX;var minY2=bounds2.minY;var maxX2=bounds2.maxX;var maxY2=bounds2.maxY;for(var x=minX1;x<=maxX1;x++){for(var y=minY1;y<=maxY1&&y<minY2;y++){callback(x,y);}
for(var y=Math.max(maxY2+1,minY1);y<=maxY1;y++){callback(x,y);}}
for(var y=Math.max(minY1,minY2);y<=Math.min(maxY1,maxY2);y++){for(var x=Math.min(maxX1+1,minX2)-1;x>=minX1;x--){callback(x,y);}
for(var x=Math.max(minX1,maxX2+1);x<=maxX1;x++){callback(x,y);}}};MarkerManager.prototype.removeFromArray=function(array,value,opt_notype){var shift=0;for(var i=0;i<array.length;++i){if(array[i]===value||(opt_notype&&array[i]==value)){array.splice(i--,1);shift++;}}
return shift;};var Menu=Class.create();Menu.prototype={initialize:function(idOrElement,name,customConfigFunction){this.name=name;this.type="menu";this.closeDelayTimer=null;this.closingMenuItem=null;this.config();if(typeof customConfigFunction=="function"){this.customConfig=customConfigFunction;this.customConfig();}
this.rootContainer=new MenuContainer(idOrElement,this);},config:function(){this.collapseBorders=true;this.quickCollapse=true;this.closeDelayTime=500;}}
var MenuContainer=Class.create();MenuContainer.prototype={initialize:function(idOrElement,parent){this.type="menuContainer";this.menuItems=[];this.init(idOrElement,parent);},init:function(idOrElement,parent){this.element=$(idOrElement);this.parent=parent;this.parentMenu=(this.type=="menuContainer")?((parent)?parent.parent:null):parent;this.root=parent instanceof Menu?parent:parent.root;this.id=this.element.id;if(this.type=="menuContainer"){if(this.element.hasClassName("level1"))this.menuType="horizontal";else if(this.element.hasClassName("level2"))this.menuType="dropdown";else this.menuType="flyout";if(this.menuType=="flyout"||this.menuType=="dropdown"){this.isOpen=false;Element.setStyle(this.element,{position:"absolute",top:"0px",left:"0px",visibility:"hidden"});}else{this.isOpen=true;}}else{this.isOpen=this.parentMenu.isOpen;}
var childNodes=this.element.childNodes;if(childNodes==null)return;for(var i=0;i<childNodes.length;i++){var node=childNodes[i];if(node.nodeType==1){if(this.type=="menuContainer"){if(node.tagName.toLowerCase()=="li"){this.menuItems.push(new MenuItem(node,this));}}else{if(node.tagName.toLowerCase()=="ul"){this.subMenu=new MenuContainer(node,this);}}}}},getBorders:function(element){var ltrb=["Left","Top","Right","Bottom"];var result={};for(var i=0;i<ltrb.length;++i){if(this.element.currentStyle)
var value=parseInt(this.element.currentStyle["border"+ltrb[i]+"Width"]);else if(window.getComputedStyle)
var value=parseInt(window.getComputedStyle(this.element,"").getPropertyValue("border-"+ltrb[i].toLowerCase()+"-width"));else
var value=parseInt(this.element.style["border"+ltrb[i]]);result[ltrb[i].toLowerCase()]=isNaN(value)?0:value;}
return result;},open:function(){if(this.root.closeDelayTimer)window.clearTimeout(this.root.closeDelayTimer);this.parentMenu.closeAll(this);this.isOpen=true;if(this.menuType=="dropdown"){Element.setStyle(this.element,{left:(Position.positionedOffset(this.parent.element)[0])+"px",top:(Position.positionedOffset(this.parent.element)[1]+Element.getHeight(this.parent.element))+"px"});}else if(this.menuType=="flyout"){var parentMenuBorders=this.parentMenu?this.parentMenu.getBorders():new Object();var thisBorders=this.getBorders();if((Position.positionedOffset(this.parentMenu.element)[0]+this.parentMenu.element.offsetWidth+this.element.offsetWidth+20)>(window.innerWidth?window.innerWidth:document.body.offsetWidth)){Element.setStyle(this.element,{left:(-this.element.offsetWidth-(this.root.collapseBorders?0:parentMenuBorders["left"]))+"px"});}else{Element.setStyle(this.element,{left:(this.parentMenu.element.offsetWidth-parentMenuBorders["left"]-(this.root.collapseBorders?Math.min(parentMenuBorders["right"],thisBorders["left"]):0))+"px"});}
Element.setStyle(this.element,{top:(this.parent.element.offsetTop-parentMenuBorders["top"]-this.menuItems[0].element.offsetTop)+"px"});}
Element.setStyle(this.element,{visibility:"visible"});},close:function(){Element.setStyle(this.element,{visibility:"hidden"});this.isOpen=false;this.closeAll();},closeAll:function(trigger){for(var i=0;i<this.menuItems.length;++i){this.menuItems[i].closeItem(trigger);}}}
var MenuItem=Class.create();Object.extend(Object.extend(MenuItem.prototype,MenuContainer.prototype),{initialize:function(idOrElement,parent){var menuItem=this;this.type="menuItem";this.subMenu;this.init(idOrElement,parent);if(this.subMenu){this.element.onmouseover=function(){menuItem.subMenu.open();}}else{if(this.root.quickCollapse){this.element.onmouseover=function(){menuItem.parentMenu.closeAll();}}}
var linkTag=this.element.getElementsByTagName("A")[0];if(linkTag){linkTag.onfocus=this.element.onmouseover;this.link=linkTag;this.text=linkTag.text;}
if(this.subMenu){this.element.onmouseout=function(){if(menuItem.root.openDelayTimer)window.clearTimeout(menuItem.root.openDelayTimer);if(menuItem.root.closeDelayTimer)window.clearTimeout(menuItem.root.closeDelayTimer);eval(menuItem.root.name+".closingMenuItem = menuItem");menuItem.root.closeDelayTimer=window.setTimeout(menuItem.root.name+".closingMenuItem.subMenu.close()",menuItem.root.closeDelayTime);}}},openItem:function(){this.isOpen=true;if(this.subMenu){this.subMenu.open();}},closeItem:function(trigger){this.isOpen=false;if(this.subMenu){if(this.subMenu!=trigger)this.subMenu.close();}}});var menu;function configMenu(){this.closeDelayTime=300;}
function initMenu(){menu=new Menu('root','menu',configMenu);}
Event.observe(window,'load',initMenu,false);var RedBox={openRedBox:function(url)
{map.disableScrollWheelZoom();new Ajax.Updater('redbox_hidden_content',url,{asynchronous:true,evalScripts:true,onComplete:function(request){RedBox.addHiddenContent('redbox_hidden_content');},onLoading:function(request){if($('RB_window')&&$('RB_window').getStyle('display')!="none"){}
else{RedBox.loading();}}})},openRedBoxHTML:function(rbClass)
{map.disableScrollWheelZoom();if($('RB_window')&&$('RB_window').getStyle('display')!="none"){}
else{RedBox.loading();}
RedBox.addHiddenContent('redbox_hidden_content');if(rbClass!=null){$('RB_window').addClassName(rbClass);}},openRedBoxInPlace:function(rbClass){map.disableScrollWheelZoom();this.setOverlaySize();new Effect.Appear('RB_overlay',{duration:0.4,to:0.6,queue:'end'});new Effect.Appear('RB_window',{duration:0.4,queue:'end'});this.setWindowPosition();if(rbClass!=null){$('RB_window').addClassName(rbClass);}},showInline:function(id)
{this.showOverlay();new Effect.Appear('RB_window',{duration:0.4,queue:'end'});Element.scrollTo('RB_window');this.cloneWindowContents(id);},loading:function()
{this.showOverlay();Element.show('RB_loading');this.setWindowPosition();},addHiddenContent:function(id)
{this.removeChildrenFromNode($('RB_window'));this.moveChildren($(id),$('RB_window'));Element.hide('RB_loading');new Effect.Appear('RB_window',{duration:0.4,queue:'end'});this.setWindowPosition();},close:function()
{if($('RB_window')){new Effect.Fade('RB_window',{duration:0.4});}
if($('RB_overlay')){new Effect.Fade('RB_overlay',{duration:0.4});}
map.enableScrollWheelZoom();redboxOpenedWindowUrl=null;},showOverlay:function()
{if($('RB_redbox'))
{Element.update('RB_redbox',"");new Insertion.Top($('RB_redbox'),'<div id="RB_window" style="display: none;"></div><div id="RB_overlay" style="display: none;" onclick="displayMap()"></div>');}
else
{new Insertion.Bottom(document.body,'<div id="RB_redbox" align="center"><div id="RB_window" style="display: none;"></div><div id="RB_overlay" style="display: none;"></div></div>');}
new Insertion.Top('RB_overlay','<div id="RB_loading" style="display: none"></div>');this.setOverlaySize();new Effect.Appear('RB_overlay',{duration:0.4,to:0.6,queue:'end'});},setOverlaySize:function()
{if(window.innerHeight&&window.scrollMaxY)
{yScroll=window.innerHeight+window.scrollMaxY;}
else if(document.body.scrollHeight>document.body.offsetHeight)
{yScroll=document.body.scrollHeight;}
else
{yScroll=document.body.offsetHeight;}
$("RB_overlay").style['height']=yScroll+"px";},setWindowPosition:function()
{var pagesize=this.getPageSize();var dimensions=Element.getDimensions($("RB_window"));var width=dimensions.width;var height=dimensions.height;$("RB_window").style['left']=((pagesize[0]-width)/2)+"px";$("RB_window").style['top']=((pagesize[1]-height)/2)+"px";},getPageSize:function(){var de=document.documentElement;var w=window.innerWidth||self.innerWidth||(de&&de.clientWidth)||document.body.clientWidth;var h=window.innerHeight||self.innerHeight||(de&&de.clientHeight)||document.body.clientHeight;arrayPageSize=new Array(w,h)
return arrayPageSize;},removeChildrenFromNode:function(node)
{while(node.hasChildNodes())
{node.removeChild(node.firstChild);}},moveChildren:function(source,destination)
{while(source.hasChildNodes())
{destination.appendChild(source.firstChild);}},cloneWindowContents:function(id)
{var content=$(id).cloneNode(true);content.style['display']='block';$('RB_window').appendChild(content);this.setWindowPosition();},displayRBContents:function(data){var rb_content=$('RB_window_content').innerHTML=data;}}
var FormUpdater=Class.create({initialize:function(fieldsPrefix,form){this.fieldIdx=0;this.fieldsPrefix=fieldsPrefix;if(form){this.form=$(form);}},setForm:function(form){this.form=$(form);},update:function(params){var field;for(key in params){field=new Element('input',{'type':'hidden','name':this.fieldsPrefix+'['+this.fieldIdx+']['+key+']','value':params[key]});this.form.appendChild(field);}
this.fieldIdx++;}});var FriendsSet=Class.create();FriendsSet.id=0;Object.extend(FriendsSet.prototype,Enumerable);Object.extend(FriendsSet.prototype,{initialize:function(options){this.id=FriendsSet.id++;this.options={formUpdater:null,friendsListContainer:null,afterUpdate:null};Object.extend(this.options,options||{});this.options.friendsListContainer=$(this.options.friendsListContainer);this.friends=new Array();},getHtmlId:function(){return'friends_list_'+this.id.toString();},add:function(friend){if(this.friends.any(function(f){return f.equals(friend);})){return false;}
this.friends.push(friend);this.updateForm(friend,{action:'add'});this.updateFriendsList();return true;},remove:function(id){var removedFriend=null;var friend=new Friend(id,null,null);for(i=0;i<this.friends.length;i++){if(removedFriend){this.friends[i-1]=this.friends[i];}else{if(this.friends[i].equals(friend)){removedFriend=this.friends[i];}}}
if(removedFriend){this.friends.length--;this.updateForm(friend,{action:'del'});this.updateFriendsList();}},toHtml:function(){var me=this;var html='<ul id="message_participants">';this.each(function(f){html+=f.toHtml();});html+='</ul>';return html;},setFormUpdater:function(formUpdater){this.options.formUpdater=formUpdater;},getFormUpdater:function(){return this.options.formUpdater;},setFriendsListContainer:function(friendsListContainer){this.options.friendsListContainer=$(friendsListContainer);},getFriendsListContainer:function(){return this.options.friendsListContainer;},setAfterUpdate:function(f){this.options.afterUpdate=f;},updateForm:function(friend,params){if(this.options.formUpdater){params.user_id=friend.id;this.options.formUpdater.update(params);}},updateFriendsList:function(){var me=this;if(this.options.friendsListContainer){this.options.friendsListContainer.innerHTML=this.toHtml();$('message_participants').childElements().invoke('observe','click',function(event){var id=Event.element(event).classNames().find(function(e){return e.startsWith('id_');}).substr(3);me.remove(id);});}
if(typeof this.options.afterUpdate=='function'){this.options.afterUpdate(this);}},_each:function(iterator){return this.friends._each(iterator);}});var Friend=Class.create({initialize:function(id,type,name,data){this.id=id;this.type=type;this.name=name;this.data=data;},equals:function(other){if(typeof other.id=='undefined'){return false;}
return this.id==other.id;},toHtml:function(friendsSet){var divClass='type_'+this.type.underscore()
+' id_'+this.id;var icon='';switch(this.type){case'RegisteredUser':icon='icon_user';break;case'Group':icon='icon_group';break;}
return'<li class="'+divClass+'" title="Click to delete!">'
+'<span class="icon '+icon+'">&nbsp;</span>'
+this.name
+'</li>';}});var FriendsAutocompleter=Class.create(Autocompleter.Local,{getUpdatedChoices:function(){this.updateChoices(this.options.selector(this));},updateElement:function(selectedElement){var me=this;var id=selectedElement.classNames().find(function(e){return e.startsWith('id_');}).substr(3);var type=selectedElement.classNames().find(function(e){return e.startsWith('type_');}).substr(5);var thing=this.options.array.find(function(e){return e.type==type&&e.id==id;});var friends=[];if(type=='Group'){thing.members.each(function(e){var friend=me.options.array.find(function(f){return f.type!='Group'&&f.id==e.id;});if(friend){friends.push(new Friend(friend.id,friend.type,friend.name));}});}else{friends=[thing];}
if(friends.length>0){friends.each(function(e){me.options.set.add(new Friend(e.id,e.type,e.name));});this.element.value='';this.element.focus();}},setOptions:function(options){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,ignoreCase:true,fullSearch:false,set:null,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.name.toLowerCase().indexOf(entry.toLowerCase()):elem.name.indexOf(entry);while(foundPos!=-1){var icon='';switch(elem.type){case'RegisteredUser':icon='icon_user';break;case'Group':icon='icon_group';break;}
var htmlClass='type_'+elem.type+" id_"+elem.id;if(foundPos==0&&elem.name.length!=entry.length){ret.push("<li class=\""+htmlClass+"\"><span class=\"icon "+icon+"\">&nbsp;</span><strong>"+elem.name.substr(0,entry.length)+"</strong>"
+elem.name.substr(entry.length)+"</li>");break;}else if(entry.length>=instance.options.partialChars&&instance.options.partialSearch&&foundPos!=-1){if(instance.options.fullSearch||/\s/.test(elem.name.substr(foundPos-1,1))){partial.push("<li class=\""+htmlClass+"\">"+elem.name.substr(0,foundPos)+"<strong>"
+elem.name.substr(foundPos,entry.length)+"</strong>"
+elem.name.substr(foundPos+entry.length)+"</li>");break;}}
foundPos=instance.options.ignoreCase?elem.name.toLowerCase().indexOf(entry.toLowerCase(),foundPos+1):elem.name.indexOf(entry,foundPos+1);}}
if(partial.length)
ret=ret.concat(partial.slice(0,instance.options.choices-ret.length));return"<ul>"+ret.join('')+"</ul>";}},options||{});},markPrevious:function(){if(this.index>0)this.index--;else this.index=this.entryCount-1;},markNext:function(){if(this.index<this.entryCount-1)this.index++;else this.index=0;}});function friendspicker_normalize(friends,groups){var autocompleterList=new Array();for(var i=0;i<friends.length;i++){var friend=friends[i];autocompleterList.push({id:friend.id,name:friend.name,type:friend['class']});}
for(var i=0;i<groups.length;i++){var group=groups[i];var groupMembers=[];group.members.each(function(m){groupMembers.push({id:m.id,type:m['class']});});autocompleterList.push({id:group.id,name:group.name,type:'Group',members:groupMembers});}
return autocompleterList;}
var Messaging=Class.create({initialize:function(){this.initialized=false;this.button=null;this.span=null;this.list=null;this.listFadeTimeout=null;this.listAppearTimeout=null;this.updateTimeout=null;this.displayedMessageUpdater=null;this.markersManager=null;this.newMessageForm=null;this.bounds=null;this.updateInProgress=false;this.documentTitle=null;this.markers=[];this.hiddenMarkers=[];this.outOfMap=[];this.displayMarkers=true;this.currentView='message';this.currentMessageId=null;},init:function(){this.button=$('messaging_button');this.span=$$('#messaging_button span').first();this.list=$('messages_list');this.markersManager=new MarkerManager(map);this.documentTitle=document.title;this.list.setStyle('left: '+this.button.positionedOffset().left+'px');this.button.observe('mouseover',function(){messaging.showList(true);});this.list.observe('mouseover',function(){messaging.showList(true);});this.button.observe('mouseout',function(){messaging.showList(false);});this.list.observe('mouseout',function(){messaging.showList(false);});this.initialized=true;this.searchMessages();},displayMessage:function(lat,lng,id){var me=this;var point=new GLatLng(lat,lng);this.currentMessageId=id;map.panTo(point);var openFn=function(){var moveMap=true;GEvent.addListener(map,"moveend",function(){if(moveMap)map.panBy(new GSize(0,35));moveMap=false;});$('messages_container').scrollTop=$('messages_container').scrollHeight;me.displayCurrentView();me.displayedMessageUpdater=new Messaging.DisplayedMessageUpdater('/messages/view_update/'+id,me);};map.openInfoWindow(point,$('messages_thread'),{noCloseOnClick:true,onOpenFn:openFn,onCloseFn:function(){me.displayedMessageUpdater.stop();me.stopReading();$('messages_pool').innerHTML='<div id="messages_thread"></div>';}});gSpinner.hide();},stopReading:function(){if(this.currentMessageId!=null){new Ajax.Request('/messages/stop_reading',{method:'get',parameters:{id:this.currentMessageId}});this.currentMessageId=null;}},displayCurrentView:function(){if(this.currentView=='message'){$('messages_container').show();$('messages_participants').hide();}else{$('messages_container').hide();$('messages_participants').show();}},searchMessages:function(){if(isUserRegistered&&!this.updateInProgress){this.updateInProgress=true;new Ajax.Request('/messages/search_js',{method:'get',parameters:{swlat:map.getBounds().getSouthWest().lat(),swlng:map.getBounds().getSouthWest().lng(),nelat:map.getBounds().getNorthEast().lat(),nelng:map.getBounds().getNorthEast().lng()},onComplete:function(){messaging.updateInProgress=false;}});}},updateMarkers:function(markers){if(typeof markers!='undefined'){clearTimeout(this.updateTimeout);this.markers=markers;}
if(!this.initialized){return;}
var unread=this.markers.select(function(m){return!m.is_read;}).length;if(unread>0){document.title='('+unread+') '+this.documentTitle;this.span.innerHTML=unread;this.button.removeClassName('messaging_no');this.button.addClassName('messaging_yes');}else{document.title=this.documentTitle;this.span.innerHTML='';this.button.removeClassName('messaging_yes');this.button.addClassName('messaging_no');}
this.showMarkers(this.displayMarkers);this.updateTimeout=setTimeout(function(){messaging.searchMessages()},60000);},showMarkers:function(show){this.markersManager.clearMarkers();this.outOfMap=[];var displayedMarkers=0;if(show){var googleMarkers=[];var swlat=map.getBounds().getSouthWest().lat();var swlng=map.getBounds().getSouthWest().lng();var nelat=map.getBounds().getNorthEast().lat();var nelng=map.getBounds().getNorthEast().lng();this.markers.each(function(m){if(m.lat==null||m.lng==null){messaging.outOfMap.push(m);}else if(m.lat<swlat||m.lat>nelat||m.lng<swlng||m.lng>nelng){messaging.outOfMap.push(m);}else if(m.is_hidden){messaging.outOfMap.push(m);}else if(!messaging.hiddenMarkers.include(m.id)){var googleMarker=new Messaging.Marker(new GLatLng(m.lat,m.lng),m);googleMarker.mid=m.id;googleMarker.timeout=null;GEvent.addListener(googleMarker,"dblclick",function(){if(this.timeout!=null){clearTimeout(this.timeout);this.timeout=null;gSpinner.hide();}
messaging.hideMarker(this);});GEvent.addListener(googleMarker,"click",function(){if(this.timeout==null){var marker=this;this.timeout=setTimeout(function(){gSpinner.show();messaging.goToMessage(marker.getLatLng().lat(),marker.getLatLng().lng(),marker.mid)},750);}});googleMarkers.push(googleMarker);displayedMarkers++;}});this.markersManager.addMarkers(googleMarkers.reverse(),0);this.markersManager.refresh();messagesList=[];this.outOfMap.each(function(m){if(!m.is_read){var from='';var link='';if(m.place!=null){from=', from <a href="#page=place-'+m.place_id+'">'+m.place+'</a>';link='<a href="#" onclick="map.setCenter(new GLatLng('+m.lat+','+m.lng+'));return false;">'+m.user+'</a>';}else if(m.lat==null||m.lng==null){link='<a href="#" onclick="displayMyspace({tab:\'newsfeed\',thread:'+m.id+'});return false;">'+m.user+'</a>';from=', <span class="geoloc">'+I18n.t('messaging.nongeoloc')+'</span>';}else if(m.is_hidden){link='<a href="#" onclick="messaging.goToMessage('+m.lat+', '+m.lng+', '+m.id+');return false;">'+m.user+'</a>';from=', <span class="geoloc">'+I18n.t('messaging.hidden')+'</span>';}else{link='<a href="#" onclick="map.setCenter(new GLatLng('+m.lat+','+m.lng+'));return false;">'+m.user+'</a>';from=', <span class="geoloc">'+I18n.t('messaging.outofscope')+'</span>';}
messagesList.push('<li><img src="'+m.icon+'" /> '+link+' at '+m.time
+'<span class="small">'+from+'</span></li>');displayedMarkers++;}});if(messagesList.length>0){this.list.innerHTML='<strong>'+I18n.t('messaging.out_of_map')+'</strong><ul>'+messagesList.join('')+'</ul>';}else{this.list.hide();this.list.innerHTML='';}}
return displayedMarkers;},hideMarker:function(marker){this.hiddenMarkers.push(marker.mid);marker.hide();},isMarkerHidden:function(id){this.hiddenMarkers.any(id)},showList:function(show){if(show&&messaging.displayMarkers&&this.list.innerHTML!=''){if(this.listFadeTimeout!=null){clearTimeout(this.listFadeTimeout);this.listFadeTimeout=null;}
if(!this.list.visible()){this.list.appear({duration:0.5,to:0.95});}}else{if(this.list.visible()&&this.listFadeTimeout==null){this.listFadeTimeout=setTimeout(function(){messaging.list.fade({duration:0.5,from:0.95});messaging.listFadeTimeout=null;},100);}}},goToMessage:function(lat,lng,id){var me=this;map.closeInfoWindow();new Ajax.Updater('messages_thread','/messages/view/'+id,{onComplete:function(){me.displayMessage(lat,lng,id)}});},createNewMessageForm:function(friends,groups){this.newMessageForm=new Messaging.NewMessageForm(friends,groups);},displayNewMessageForm:function(id,lat,lng){if(this.newMessageForm){this.newMessageForm.display(id,lat,lng);}},toggleMessageView:function(see_participants,see_messages){if(this.currentView=='message'){$('messages_toggle_view_link').innerHTML=see_messages;this.currentView='participants';}else{$('messages_toggle_view_link').innerHTML=see_participants;this.currentView='message'}
this.displayCurrentView();},toggleMessaging:function(){this.displayMarkers=!this.displayMarkers;if(this.displayMarkers){this.button.removeClassName('messaging_off');this.button.addClassName('messaging_on');}else{this.button.removeClassName('messaging_on');this.button.addClassName('messaging_off');this.hiddenMarkers=[];displayNotice(I18n.t('messaging.disabled'));}
if(this.displayMarkers&&this.showMarkers(this.displayMarkers)==0){displayNotice(I18n.t('messaging.enabled'));}
this.showList(this.displayMarkers);this.showMarkers(this.displayMarkers);}});Messaging.DisplayedMessageUpdater=Class.create({initialize:function(url,messaging,interval,decay){this.url=url;this.messaging=messaging;this.interval=interval||2;this.decay=decay||2;this.currentInterval=this.interval;this.lastResponse="";this.currentlyExecuting=false;this.running=false;this.start();},start:function(){this.running=true;this.timeout=setTimeout(this.onTimerEvent.bind(this),this.currentInterval*1000);},stop:function(){this.running=false;clearTimeout(this.timeout);},reset:function(){this.stop();this.currentInterval=this.interval;this.start();},forceUpdate:function(){this.stop();this.onTimerEvent(true);},onTimerEvent:function(reset){if(!this.currentlyExecuting){try{var me=this;this.currentlyExecuting=true;new Ajax.Request(this.url,{method:'get',onComplete:function(transport){if(me.lastResponse==transport.responseText){me.currentInterval=Math.min(30,me.currentInterval*me.decay);}else{me.currentInterval=me.interval;me.lastResponse=transport.responseText;}
var messages_container=$('messages_container');var scrollLeft=messages_container.scrollLeft;var scrollTop=messages_container.scrollTop;var scroll=messages_container.scrollTop==(messages_container.scrollHeight-messages_container.getHeight());$('messages_info').innerHTML=me.lastResponse;messages_container=$('messages_container');messages_container.scrollLeft=scrollLeft;if(scroll){messages_container.scrollTop=messages_container.scrollHeight;}else{messages_container.scrollTop=scrollTop;}
me.messaging.displayCurrentView();if(me.running&&!reset){me.start();}else if(reset){me.reset();}}});}finally{this.currentlyExecuting=false;}}}});Messaging.NewMessageForm=Class.create({initialize:function(friends,groups){this.iAmHereForm=null;this.friendsSet=null;this.autocompleterList=[];this.setAutocompleterList(friends,groups);},setAutocompleterList:function(friends,groups){for(var i=0;i<friends.length;i++){var friend=friends[i];this.autocompleterList.push({id:friend.id,name:friend.name,type:friend['class']});}
for(var i=0;i<groups.length;i++){var group=groups[i];var groupMembers=[];group.members.each(function(m){groupMembers.push({id:m.id,type:m['class']});});this.autocompleterList.push({id:group.id,name:group.name,type:'Group',members:groupMembers});}},display:function(id,lat,lng){introDestroy();RedBox.close();var point=new GLatLng(lat,lng);if(this.iAmHereForm==null){this.iAmHereForm=$('message_send').innerHTML;$('message_send').remove();}
if(this.friendsSet==null){this.friendsSet=new FriendsSet({formUpdater:new FormUpdater('message[participants]')});}
var me=this;map.openInfoWindow(point,this.iAmHereForm,{noCloseOnClick:true,onOpenFn:function(){me.friendsSet.getFormUpdater().setForm('message_send_form');me.friendsSet.setFriendsListContainer('message_friends_list_container');me.friendsSet.setAfterUpdate(function(set){var email=$('also_send_by_mail');var help=$('message_friends_list_help');if(set.size()==0){help.show();if(email!=null){email.hide();}}else{help.hide();if(email!=null){email.show();}}});if(me.friendsSet.size()>0){me.friendsSet.updateFriendsList();}
new FriendsAutocompleter($('message_friends_entry'),$('message_friends_suggestions'),me.autocompleterList,{partialChars:1,fullSearch:true,set:me.friendsSet});},onCloseFn:function(){if($('RB_overlay')){new Effect.Appear('RB_overlay',{duration:0.4,queue:'end'});}
if($('RB_window')){new Effect.Appear('RB_window',{duration:0.4,queue:'end'});}}});}});Messaging.Icon=function(){this.image='/images/messaging/icon/image.png';this.shadow='/images/messaging/icon/shadow.png';this.printImage='/images/messaging/icon/print_image.gif';this.mozPrintImage='/images/messaging/icon/moz_print_image.gif';this.printShadow='/images/messaging/icon/print_shadow.gif';this.transparent='/images/messaging/icon/transparent.png';this.iconSize=new GSize(72,107);this.shadowSize=new GSize(144,103);this.iconAnchor=new GPoint(21,109);this.imageMap=[2,2,70,2,70,82,56,83,21,107,32,83,2,82];}
Messaging.Icon.prototype=new GIcon();Messaging.Marker=function(latLng,marker){var unread;if(!marker.is_read){unread='<span style="color:red">&nbsp;•&nbsp;</span>';}else{unread='';}
var labelText="<div style=\"background-color: white\"><img src=\""+marker['picture']+"\" /><br />"
+unread+marker['time']+unread+'</div>';LabeledMarker.call(this,latLng,{icon:new Messaging.Icon(),labelText:labelText,labelClass:'messaging_marker_user_picture',labelOffset:new GSize(-15,-103)});}
Messaging.Marker.prototype=new LabeledMarker(new GLatLng(0,0),{});var messaging=new Messaging();function messagesContentKeypress(event){e=Event.element(event);if(event.keyCode==Event.KEY_RETURN){if(event.shiftKey){e.value+="\n";}else{$('message_send_form').request({asynchronous:true,evalScripts:true,onComplete:function(request){onAjaxFormComplete('message_send_form');messaging.displayedMessageUpdater.forceUpdate();},onLoading:function(request){onAjaxFormLoading('message_send_form');}});$('new_message_content').value='';$('new_message_content').focus();}
return false;}}
function messagesFriendsEntryKeypress(event){if(event.keyCode==Event.KEY_RETURN){return false;}
return true;}
var UpdateForm=function(id_rdv){this.index=0;this.form=$('rendezvous_form');}
UpdateForm.prototype={addRdvField:function(params){var field;for(key in params){field=new Element('input',{'type':'hidden','name':'rendezvous[updates]['+this.index+']['+key+']','value':params[key]});this.form.appendChild(field);}
this.index+=1;lightenSaveButton();},sendUpdate:function(){this.form.onsubmit();}}
var Party=Class.create();Party.prototype={initialize:function(currentUser,ownerUser,editable_person,editable_place,editable_time,newRecord){this.dayBlocks=new Array();this.people=new Array();this.places=new Array();this.currentUser=currentUser;this.isOwner=Boolean(ownerUser!=null&&ownerUser==currentUser);this.editable_person=Boolean(editable_person);this.editable_place=Boolean(editable_place);this.editable_time=Boolean(editable_time);this.newRecord=Boolean(newRecord);this.first=true;this.unnotified_people=new Array();},createRendezVousFromData:function(timeSlotsArray,peopleArray,choices,placesArray,placeChoices){var rendezvous=this;timeSlotsArray.each(function(timeSlotElement){var timeslot=convertRubyDateStringtoJSDate(timeSlotElement);rendezvous.addDayBlock(timeslot.format('dd.MM.yyyy HH:mm'));});placesArray.each(function(place){rendezvous.addPlace(place.id,place.name,place.class_name,place.logo_public_filename,place.email_booking_link);});peopleArray.each(function(participant){rendezvous.addPerson(participant.name,participant.class_name,participant.id,true);});this.people.each(function(person,personIdx){person.setChoices(choices[personIdx]);person.setChoicesPlaces(placeChoices[personIdx]);});this.drawParty();this.UpdateForm=new UpdateForm()
if(this.newRecord){for(var i=0;i<this.people.length;i++){this.UpdateForm.addRdvField({target:'person',action:'add',user_id:this.people[i].id,user_name:this.people[i].name});}
for(var i=0;i<this.dayBlocks.length;i++){for(var j=0;j<this.dayBlocks[i].hourBlocks.length;j++){var time=this.dayBlocks[i].day+" "+this.dayBlocks[i].hourBlocks[j].hour;this.UpdateForm.addRdvField({target:'time',action:'add','when':time});}}
for(var i=0;i<this.places.length;i++){this.UpdateForm.addRdvField({target:'place_event',action:'add',place_event_type:this.places[i].type,place_event_id:this.places[i].id});}}},addDayBlock:function(dateString){var dateAndTime=/(\d{1,2}[.-]\d{1,2}[.-]\d{1,4})\s+(\d{1,2}:\d{1,2})/.exec(dateString);if(dateAndTime==null)return;var day=dateAndTime[1];var time=dateAndTime[2];var rendezvous=this;var done=false;rendezvous.dayBlocks.each(function(d,i){if(day==d.day){rendezvous.addHourBlock(i,time);done=true;throw $break;}});if(done)return;var nbDayBlocks=this.dayBlocks.size();this.dayBlocks[nbDayBlocks]=new DayBlock(nbDayBlocks,day);this.dayBlocks[nbDayBlocks].addHour(nbDayBlocks,time);this.people.each(function(person){person.addChoice(nbDayBlocks);});if(this.UpdateForm){this.UpdateForm.addRdvField({target:'time',action:'add','when':dateString});}
this.reorderDay();this.drawParty();},deleteDayBlock:function(order){if(this.UpdateForm){for(var hourIndex=0;hourIndex<this.dayBlocks[order].hourBlocks.length;hourIndex++){var time=this.dayBlocks[order].day+" "+this.dayBlocks[order].hourBlocks[hourIndex].hour;this.UpdateForm.addRdvField({target:'time',action:'del','when':time});}}
var index=0;for(var i=0;i<order;i++){index+=this.dayBlocks[i].hourBlocks.length;}
var nbHour=this.dayBlocks[order].hourBlocks.length;this.dayBlocks=this.dayBlocks.without(this.dayBlocks[order]);for(var i=order;i<this.dayBlocks.length;i++){this.dayBlocks[i].order--;}
for(var i=0;i<this.people.length;i++){for(var j=0;j<nbHour;j++){this.people[i].choices=this.people[i].choices.without(this.people[i].choices[index]);}
for(var j=index;j<this.people[i].choices.length;j++){this.people[i].choices[j].dayBlockId--;}}
this.drawParty();},addHourBlock:function(dayBlockId,hourString){var done=this.dayBlocks[dayBlockId].hourBlocks.any(function(h){return(h.hour==hourString);});if(done)return;this.dayBlocks[dayBlockId].addHour(dayBlockId,hourString);hourBlockId=this.dayBlocks[dayBlockId].hourBlocks.size()-1;this.people.each(function(person){person.addChoice(dayBlockId,hourBlockId);});if(this.UpdateForm){var time=this.dayBlocks[dayBlockId].day+" "+this.dayBlocks[dayBlockId].hourBlocks[hourBlockId].hour;this.UpdateForm.addRdvField({target:'time',action:'add','when':time});}
this.reorderHour(dayBlockId,this.dayBlocks[dayBlockId].hourBlocks.size()-1);this.drawParty();},deleteHourBlock:function(dayBlockId,order){if(this.UpdateForm){var time=this.dayBlocks[dayBlockId].day+" "+this.dayBlocks[dayBlockId].hourBlocks[order].hour;this.UpdateForm.addRdvField({target:'time',action:'del','when':time});}
if(this.dayBlocks[dayBlockId].hourBlocks.length==1){this.deleteDayBlock(dayBlockId);}else{this.dayBlocks[dayBlockId].hourBlocks=this.dayBlocks[dayBlockId].hourBlocks.without(this.dayBlocks[dayBlockId].hourBlocks[order]);for(var i=order;i<this.dayBlocks[dayBlockId].hourBlocks.length;i++){this.dayBlocks[dayBlockId].hourBlocks[i].order--;}
var indexChoice=order;for(var i=0;i<dayBlockId;i++){indexChoice+=this.dayBlocks[i].hourBlocks.length;}
for(var j=0;j<this.people.length;j++){this.people[j].choices=this.people[j].choices.without(this.people[j].choices[indexChoice]);for(var i=0;i<(this.dayBlocks[dayBlockId].hourBlocks.length-order);i++){this.people[j].choices[indexChoice+i].hourBlockId--;}}
if(this.dayBlocks[dayBlockId].hourBlocks.length>1){this.dayBlocks[dayBlockId].width=(this.dayBlocks[dayBlockId].hourBlocks.length*58)-2;}
this.drawParty();}},updateDayBlock:function(dayBlockId,dateString){db=this.dayBlocks[dayBlockId];if(db.day==dateString){return;}
if(dateString){var hasVote=this.people.any(function(person){return person.choices.any(function(choice){return(choice.dayBlockId==db.order&&choice.value!=0);});});if(hasVote){if(!confirm(I18n.t('rendezvous.confirm.reset_all_votes_day'))){return;}}}else{if(!confirm(I18n.t('rendezvous.confirm.delete_day'))){return;}}
if(dateString){db.hourBlocks.each(function(hourBlock){var newDate=dateString+' '+hourBlock.hour;this.addDayBlock(newDate);}.bind(this));}
this.deleteDayBlock(db.order);},updateHourBlock:function(dayBlockId,hourBlockId,dateString){db=this.dayBlocks[dayBlockId];hb=db.hourBlocks[hourBlockId];var time=db.day+' '+hb.hour;if(time==dateString){return;}
if(dateString){var hasVote=this.people.any(function(person){return person.choices.any(function(choice){return(choice.dayBlockId==db.order&&choice.hourBlockId==hb.order&&choice.value!=0);});});if(hasVote){if(!confirm(I18n.t('rendezvous.confirm.reset_all_votes_time_slot'))){return;}}}else{if(!confirm(I18n.t('rendezvous.confirm.delete_time_slot'))){return;}}
this.deleteHourBlock(db.order,hb.order);if(dateString){this.addDayBlock(dateString);}},getCookieStoredName:function(){var beginindex,endindex;beginindex=document.cookie.indexOf("allow_edit");if(beginindex<0)return"";beginindex+="allow_edit".length+1;endindex=beginindex;while(document.cookie.charAt(endindex)!=";"&&endindex<=document.cookie.length){endindex++;}
return document.cookie.substring(beginindex,endindex);},addPerson:function(name,type,id,skipDrawParty){if(!name||name.blank()){name=$F('contacts_user_entry');if(!name||name.blank()){return;}}
name=name.strip();var done=this.people.any(function(p){return(p.name==name&&p.type==type&&p.id==id);});if(done){return;}
var nbPeople=this.people.size();var hourBInDayB=this.getNbHourBlocksInDayBlocks();var nbPlaceEvents=this.places.size();this.people[nbPeople]=new Person(nbPeople,hourBInDayB,name,nbPlaceEvents,type,id);if(!skipDrawParty){var y=$('people_datetimes_places').offsetHeight+27;$('people_datetimes_places').setStyle({height:''+y+'px'});var field=$('contacts_user_entry');field.clear().focus();this.drawParty();}
if(this.UpdateForm){this.UpdateForm.addRdvField({target:'person',action:'add',user_id:id,user_name:name});}},undoAddPerson:function(name,type,id){var success=false;var nPeople=this.people.length;this.deletePerson(name,id,type);if(this.people.length<nPeople&&this.isOwner){success=true;}
if(!success&&this.UpdateForm){for(var i=this.UpdateForm.index-1;i>=0;--i){var targetField=$$('input[type=hidden][name="rendezvous[updates]['+i+'][target]"][value=person]')[0];var nameField=$$('input[type=hidden][name="rendezvous[updates]['+i+'][user_name]"][value="'+name+'"]')[0];var idField=$$('input[type=hidden][name="rendezvous[updates]['+i+'][user_id]"][value="'+id+'"]')[0];var actionField=$$('input[type=hidden][name="rendezvous[updates]['+i+'][action]"][value=add]')[0];if(targetField&&nameField&&(idField||id===null)&&actionField){targetField.value="noop";success=true;break;}}}
return success;},deletePerson:function(name,id,type){var found=false;for(var i=0;i<this.people.length;i++){if(found){this.people[i].order--;}else{if(this.people[i].name==name&&this.people[i].id==id&&this.people[i].type==type){this.people=this.people.without(this.people[i]);found=true;--i;}}}
this.drawParty();if(this.UpdateForm){this.UpdateForm.addRdvField({target:'person',action:'del',user_id:id,user_name:name});}
if(type!="AnonymousUser")
this.unnotified_people=this.unnotified_people.without(name);},promptForAnonymousUsersEmail:function(name){killPopup();var nameDivId='person_'+name.gsub(/\W/,'').underscore();coTop=$(nameDivId).cumulativeOffset().top-$(nameDivId).cumulativeScrollOffset().top;coLeft=$(nameDivId).cumulativeOffset().left-$(nameDivId).cumulativeScrollOffset().left;var popup=new Control.Window("/rendezvous/new_visitor",{parameters:{"visitor[name]":name},className:"new_visitor_popup",closeOnClick:false,position:[coLeft,coTop],offsetTop:(200+coTop)>document.body.offsetHeight?-170:0,offsetLeft:135,afterOpen:function(){this.container.down('#close_new_visitor_popup').observe('click',popup.close.bindAsEventListener(popup));this.container.down('input[type=text]').focus();}});popup.open();},secretLinkPopup:function(key,activationCode,registered){killPopup();coTop=$('rendezvous_save_button').cumulativeOffset().top-$('rendezvous_save_button').cumulativeScrollOffset().top;coLeft=$('rendezvous_save_button').cumulativeOffset().left;if(registered)
var h=120;else
var h=220;new Ajax.Request('/rendezvous/secret_link_popup',{parameters:{"key":key,"code":activationCode},onComplete:function(transport){var popupDiv=new Element("div",{id:"secret_link_popup"});popupDiv.innerHTML=transport.responseText;$$('body')[0].appendChild(popupDiv);var popup=new Control.Window(popupDiv,{className:"rdvPopup",closeOnClick:false,position:[coLeft,coTop],height:h,offsetTop:(200+coTop)>document.body.offsetHeight?-h:0,offsetLeft:135,draggable:popupDiv.down('#secret_link_popup_header'),constrainToViewport:true,afterOpen:function(){popup.ensureInBounds();}});popup.open();}});},invitePopup:function(){$('email_field_error_message').hide();$('visitor_email').clear();$('visitor_email').focus();$('rdv_invite_link').hide();$('rdv_add_me_link').show();$('rdv_popup_anonymous').hide();$('rdv_popup_visitor').hide();$('rdv_popup_invite').show();$('visitor_email_field').show();$('control_window_2').setStyle({height:'120px'});},addMePopup:function(){$('rdv_add_me_link').hide();$('rdv_invite_link').show();$('visitor_email_field').hide();$('rdv_popup_invite').hide();$('rdv_popup_visitor').hide();$('rdv_popup_anonymous').show();$('control_window_2').setStyle({height:'200px'});$$('div.rdv_popup_button').invoke('show');},visitorPopup:function(){$('email_field_error_message').hide();$('visitor_email').clear();$('visitor_email').focus();$('rdv_popup_anonymous').hide();$('rdv_popup_visitor').show();$('visitor_email_field').show();$('control_window_2').setStyle({height:'120px'});},killAndLogin:function(name){killPopup();this.deletePerson(name,null,'AnonymousUser');$('menu_login_form').show();$('login').focus();},visitorCreated:function(visitor){if(this.undoAddPerson(visitor.name,"AnonymousUser",null)){this.addPerson(visitor.name,"Visitor",visitor.id);}
if(typeof(contacts)!='undefined'){contacts.push({id:visitor.id,"class":"Visitor",name:visitor.name});}},visitorDeleted:function(visitor){this.deletePerson(visitor.name,visitor.id,"Visitor");if(Object.isArray(contacts)){contacts=contacts.reject(function(c){return(c.id==visitor.id&&c.name==visitor.name&&c['class']==visitor['class']);});}},drawParty:function(){var _scrollLeft=$('options_choices')?$('options_choices').scrollLeft:0;$('people_datetimes_places').replace(this.getCode());$('options_choices').scrollLeft=_scrollLeft;var elems=$$('div.rdv_close_button');elems.each(function(s){s.observe('click',cancelPropagation);});Event.observe($('options_choices'),'scroll',this.showGradients);},getCode:function(){var current_user=this.currentUser;var y=(this.people.size())*27+105;var code="<div id=\"people_datetimes_places\" style='height:"+y.toString()+"px;'>"+"  <div id=\"people_list\">";this.people.each(function(person){code+=person.getPersonName();});code+="  </div>";code+="    <div id=\"rdv_gradL\" class=\"rdv_grad\" style=\"display: none;height: "+(y-5).toString()+"px;\"></div>";var pcw=this.getPeopleChoicesWidth();if(pcw>480){code+="    <div id=\"rdv_gradR\" class=\"rdv_grad\" style=\"height: "+(y-5).toString()+"px;\"></div>";}else{code+="    <div id=\"rdv_gradR\" class=\"rdv_grad\" style=\"display: none;height: "+(y-5).toString()+"px;\"></div>";}
var height_div=(this.people.size())*27+118;code+="  <div id='options_choices' style='height:"+height_div.toString()+"px;'> ";code+="    <div id=\"datetimes_places_events\" style=\"width: "+pcw.toString()+"px;\">";nbDayBlocks=this.dayBlocks.size();this.dayBlocks.each(function(dayBlockElement){code+=dayBlockElement.getCode(nbDayBlocks);});this.places.each(function(place){code+=place.getCode();});code+="    </div>";code+="    <div id=\"people_choices\" style=\"width: "+pcw.toString()+"px;\">";var hourBInDayB=this.getNbHourBlocksInDayBlocks();this.people.each(function(person){code+="<div class=\"person_choices";if(person.id==current_user)
code+=" current_user";code+="\" id=\"person_choices_"+person.name+"\">";code+=person.getPersonChoices(hourBInDayB);code+=person.getPersonChoicesPlaceEvents();code+="</div>";});code+="<div class=\"person_choices\" id=\"sum_choices\">";code+=this.getSumsCode();code+="</div>";code+="    </div>"+"  </div>"+"</div>";return code;},getPeopleChoicesWidth:function(){var width=0;this.dayBlocks.each(function(db){if(db.hourBlocks.size()>1){width+=db.hourBlocks.size()*58;}else{width+=116;}});width+=this.places.size()*127;return width;},getSumsCode:function(){persons=this.people;if(persons.length<=0)return"";var code="";var index=0;this.dayBlocks.each(function(db){for(var i=db.hourBlocks.size();i>0;i--){var yes=0;var no=0;persons.each(function(person){if(person.choices[index].value==1)
yes++;else
if(person.choices[index].value==-1)
no++;});code+="<div class=\"choice ";if(yes==no){code+="choice_0";}
else
if(yes>no){code+="choice_1";}
else{code+="choice_-1";}
if(db.hourBlocks.size()==1){code+="\" style=\"width: 104px;";code+="\">"+I18n.t('rendezvous.choice_1')+": "+yes+" "+I18n.t('rendezvous.choice_-1')+": "+no+"</div>";}else{code+="\">"+I18n.t('rendezvous.choice_1').substr(0,1)+":"+yes+" "+I18n.t('rendezvous.choice_-1').substr(0,1)+":"+no+"</div>";}
index++;}});index=0;this.places.each(function(p){var sum=0;persons.each(function(person){sum+=person.place_event_choices[index].value;});avg=sum/persons.length;code+="<div class=\"choice ";if(avg<=-1.5){code+="choice_-2";}else if(avg>-1.5&&avg<=-0.5){code+="choice_-1";}else if(avg>-0.5&&avg<=0.5){code+="choice_0";}else if(avg>0.5&&avg<=1.5){code+="choice_1";}else{code+="choice_2";}
code+="\" style=\"width: 115px;\">"+sum+"</div>"
index++;});return code;},addPlace:function(placeId,placeName,placeType,placeBrand,bookLink){var nbPlaces=this.places.size();this.places[nbPlaces]=new Place(nbPlaces,placeName,placeId,placeType,placeBrand,bookLink);},addNewPlace:function(placeId,placeName,placeType,placeBrand,bookLink){var done=this.places.any(function(p){return(p.id==placeId);});if(done)return;this.addPlace(placeId,placeName,placeType,placeBrand,bookLink);this.people.each(function(person){person.addPlaceEventChoice();})
this.drawParty();openSideBarLeft();if(this.UpdateForm){this.UpdateForm.addRdvField({target:'place_event',action:'add',place_event_type:placeType,place_event_id:placeId});}},deletePlace:function(name,id,type){var found=false;var index;for(var i=0;i<this.places.length;i++){if(found){this.places[i].order--;}else{if(this.places[i].name==name&&this.places[i].id==id&&this.places[i].type==type){index=i;this.places=this.places.without(this.places[i]);found=true;i--;}}}
for(var i=0;i<this.people.length;i++){this.people[i].place_event_choices=this.people[i].place_event_choices.without(this.people[i].place_event_choices[index]);for(var j=index;j<this.people[i].place_event_choices.length;j++){this.people[i].place_event_choices[j].placeOrder--;}}
if(this.UpdateForm){this.UpdateForm.addRdvField({target:'place_event',action:'del',place_event_type:type,place_event_id:id});}
this.drawParty();},getNbHourBlocksInDayBlocks:function(){var hourBInDayB=new Array();this.dayBlocks.each(function(dayElement,index){hourBInDayB[index]=dayElement.hourBlocks.size();});return hourBInDayB;},displayDayOptions:function(dayBlockId){var div=$('edit_day_'+dayBlockId);var day=this.dayBlocks[dayBlockId].day;div.appendChild(Builder.node('input',{type:'hidden',id:'modify_day_field',value:day}));new CalendarDateSelect('modify_day_field',{year_range:[(new Date).getFullYear(),(new Date).getFullYear()+10],after_close:function(){party.updateDayBlock(dayBlockId,this.value);},valid_date_check:function(date){return(date.stripTime()>=(new Date()).stripTime());}});},displayHourOptions:function(dayBlockId,hourBlockId){var div=$('edit_hour_'+dayBlockId+'_'+hourBlockId);var time=this.dayBlocks[dayBlockId].day+' '+this.dayBlocks[dayBlockId].hourBlocks[hourBlockId].hour;div.appendChild(Builder.node('input',{type:'hidden',id:'modify_hour_field',value:time}));new CalendarDateSelect('modify_hour_field',{time:true,year_range:[(new Date).getFullYear(),(new Date).getFullYear()+10],after_show:function(){$$('div.cds_buttons')[0].addClassName('cds_buttons_nodate');$$('div.cds_header').invoke('hide');$$('div.cds_body').invoke('hide');s=$$('span.button_seperator')[0];s.previous('a').hide();s.hide();},after_close:function(){party.updateHourBlock(dayBlockId,hourBlockId,this.value);},valid_date_check:function(date){return(date.stripTime()>=(new Date()).stripTime());}});},reorderDay:function(){this.dayBlocks=this.dayBlocks.sortBy(function(d){splittedTime=d.day.split('.');return(parseInt(splittedTime[0],10)+parseInt(splittedTime[1],10)*31+parseInt(splittedTime[2])*372);})
var reorder_array=new Array();this.dayBlocks.each(function(dayBlockElement,index){oldOrder=dayBlockElement.order;newOrder=index;reorder_array[oldOrder]=newOrder-oldOrder;dayBlockElement.order=newOrder;});this.people.each(function(person){person.choices.each(function(choiceElement){choiceElement.dayBlockId+=reorder_array[choiceElement.dayBlockId];});person.choices=person.choices.sortBy(function(s){return(s.dayBlockId*100+s.hourBlockId)});});},reorderHour:function(dayBlockId){this.dayBlocks[dayBlockId].hourBlocks=this.dayBlocks[dayBlockId].hourBlocks.sortBy(function(s){splitted_time=s.hour.split(':');return(parseInt(splitted_time[0],10)*60+parseInt(splitted_time[1],10));});var reoder_array=new Array();this.dayBlocks[dayBlockId].hourBlocks.each(function(hourBlockElement,index){oldOrder=hourBlockElement.order;newOrder=index;reoder_array[oldOrder]=newOrder-oldOrder;hourBlockElement.order=newOrder;});this.people.each(function(person){var hourBlockIdx=0;person.choices.each(function(choiceElement){if(choiceElement.dayBlockId==dayBlockId){choiceElement.hourBlockId+=reoder_array[hourBlockIdx++];}});person.choices=person.choices.sortBy(function(s){return(s.dayBlockId*100+s.hourBlockId)});});},displayPersonOptions:function(personName,personId,personType){var nameDivId='person_'+personName.gsub(/\W/,'').underscore();var popupId='person_popup_'+personName.gsub(/\W/,'').underscore();var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':popupId},[Builder.node('a',{id:popupId+'_delete'},[Builder.node('img',{src:"/images/"+I18n.locale+"/button_delete_"+I18n.locale+".png",alt:I18n.t('rendezvous.delete_person'),title:I18n.t('rendezvous.delete_person')})]),Builder.node('a',{id:popupId+'_back'},[Builder.node('img',{src:"/images/"+I18n.locale+"/button_back_"+I18n.locale+".png",alt:I18n.t('rendezvous.back'),title:I18n.t('rendezvous.back')})])]);$$('body')[0].appendChild(popupDiv);var popup=new Control.Window(popupDiv,{position:$(nameDivId).cumulativeOffset(),offsetTop:25-$('sideBarLeftContents').scrollTop,draggable:popupDiv,constrainToViewport:true,afterOpen:function(){popup.ensureInBounds();}});popup.open();popupDiv.down('#'+popupId+'_delete').observe('click',function(){popup.close();party.deletePerson(personName,personId,personType);});popupDiv.down('#'+popupId+'_back').observe('click',function(){popup.close();});},displaySavePopup:function(){var up=this.unnotified_people;if(up.length<1){$('rendezvous_submit').value='save';if($('rendezvous_form').onsubmit())$('rendezvous_form').submit();return false;}
var nameDivId='save_button';var popupId='rendezvous_save_popup';var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':popupId},[Builder.node('div',{'className':'rdv_close_button'},Builder.node('a',{'onclick':"killPopup()"},Builder.node('img',{'src':'/images/close.png','alt':I18n.t('rendezvous.close_popup'),'title':I18n.t('rendezvous.close_popup')}))),Builder.node('p',I18n.t('rendezvous.save_or_send')),Builder.node('ul',function(){t=[];up.each(function(person){t.push(Builder.node('li',person))});return t;}()),Builder.node('input',{id:popupId+'_send',type:'submit',value:I18n.t('shared.yes')}),Builder.node('input',{id:popupId+'_save',type:'submit',value:I18n.t('shared.no')})]);$$('body')[0].appendChild(popupDiv);var popup=new Control.Window(popupDiv,{position:$('save_button').cumulativeOffset(),offsetTop:-150-$('sideBarLeftContents').scrollTop,offsetLeft:-68,width:200,draggable:popupDiv,constrainToViewport:true,afterOpen:function(){popup.ensureInBounds();}});popup.open();popupDiv.down('#'+popupId+'_save').observe('click',function(){$('rendezvous_submit').value='save';if($('rendezvous_form').onsubmit())$('rendezvous_form').submit();popup.close();});popupDiv.down('#'+popupId+'_send').observe('click',function(){$('rendezvous_submit').value='send';if($('rendezvous_form').onsubmit())$('rendezvous_form').submit();party.unnotified_people=new Array();popup.close();});},helpPopup:function(parent,popupDiv,w){if(w==null)
var w=200;$$('body')[0].appendChild(popupDiv);var popup=new Control.Window(popupDiv,{position:$(parent).cumulativeOffset(),offsetTop:-10-$('sideBarLeftContents').scrollTop,offsetLeft:-10,width:w,draggable:popupDiv,constrainToViewport:true,afterOpen:function(){popup.ensureInBounds();}});popup.open();},helpVideo:function(parent){var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':'rendezvous_help_video_popup'},[Builder.node('div',{'className':'rdv_close_button'},Builder.node('a',{'onclick':"killPopup()"},Builder.node('img',{'src':'/images/close.png','alt':I18n.t('rendezvous.close_popup'),'title':I18n.t('rendezvous.close_popup')}))),Builder.node('h2',I18n.t('rendezvous.help.help')),Builder.node('a',{'id':'rendezvous_help_video','href':'http://www.usefulweb.ch/videos/rdv_'+I18n.locale+'.flv'})]);$$('body')[0].appendChild(popupDiv);var popup=new Control.Window(popupDiv,{position:$(parent).cumulativeOffset(),offsetTop:-50-$('sideBarLeftContents').scrollTop,offsetLeft:-100,width:360,draggable:popupDiv,constrainToViewport:true,afterOpen:function(){popup.ensureInBounds();}});popup.open();flowplayer("rendezvous_help_video","/flowplayer/flowplayer/flowplayer-3.1.5.swf",{clip:{autoPlay:true},plugins:{controls:null}});},helpDate:function(parent){var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':'rendezvous_help_date_popup'},[Builder.node('div',{'className':'rdv_close_button'},Builder.node('a',{'onclick':"killPopup()"},Builder.node('img',{'src':'/images/close.png','alt':I18n.t('rendezvous.close_popup'),'title':I18n.t('rendezvous.close_popup')}))),Builder.node('p',I18n.t('rendezvous.help.date_1')),Builder.node('p',[I18n.t('rendezvous.help.date_2'),Builder.node('span',{'class':'icon icon_add'})])]);this.helpPopup(parent,popupDiv);},helpPerson:function(parent){var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':'rendezvous_help_person_popup'},[Builder.node('div',{'className':'rdv_close_button'},Builder.node('a',{'onclick':"killPopup()"},Builder.node('img',{'src':'/images/close.png','alt':I18n.t('rendezvous.close_popup'),'title':I18n.t('rendezvous.close_popup')}))),Builder.node('p',I18n.t('rendezvous.help.person_1')),Builder.node('p',I18n.t('rendezvous.help.person_2'))]);this.helpPopup(parent,popupDiv);},helpAnonymous:function(parent){var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':'rendezvous_help_anon_popup'},[Builder.node('div',{'className':'rdv_close_button'},Builder.node('a',{'onclick':"killPopup()"},Builder.node('img',{'src':'/images/close.png','alt':I18n.t('rendezvous.close_popup'),'title':I18n.t('rendezvous.close_popup')}))),Builder.node('p',I18n.t('rendezvous.help.anonymous_1')),Builder.node('p',I18n.t('rendezvous.help.anonymous_2'))]);this.helpPopup(parent,popupDiv);},helpCanAdd:function(parent){var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':'rendezvous_help_canadd_popup'},[Builder.node('div',{'className':'rdv_close_button'},Builder.node('a',{'onclick':"killPopup()"},Builder.node('img',{'src':'/images/close.png','alt':I18n.t('rendezvous.close_popup'),'title':I18n.t('rendezvous.close_popup')}))),Builder.node('p',I18n.t('rendezvous.help.can_add'))]);this.helpPopup(parent,popupDiv);},helpPlace:function(parent){var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':'rendezvous_help_place_popup'},[Builder.node('div',{'className':'rdv_close_button'},Builder.node('a',{'onclick':"killPopup()"},Builder.node('img',{'src':'/images/close.png','alt':I18n.t('rendezvous.close_popup'),'title':I18n.t('rendezvous.close_popup')}))),Builder.node('p',I18n.t('rendezvous.help.place_1')),Builder.node('ul',[Builder.node('li',[I18n.t('rendezvous.help.place_2'),Builder.node('br'),Builder.node('img',{'src':'/images/rendezvous/help/'+I18n.locale+'_add_place.png'})]),Builder.node('li',I18n.t('rendezvous.help.place_3')),Builder.node('li',I18n.t('rendezvous.help.place_4')),Builder.node('li',I18n.t('rendezvous.help.place_5')),])]);this.helpPopup(parent,popupDiv,300);},helpSecretLink:function(parent){var popupDiv=Builder.node('div',{'className':'rdvPopup popup','id':'rendezvous_help_secret_popup'},[Builder.node('div',{'className':'rdv_close_button'},Builder.node('a',{'onclick':"killPopup()"},Builder.node('img',{'src':'/images/close.png','alt':I18n.t('rendezvous.close_popup'),'title':I18n.t('rendezvous.close_popup')}))),Builder.node('p',I18n.t('rendezvous.help.secret_link'))]);this.helpPopup(parent,popupDiv);},toggleRdvChoice:function(pPersonType,pPersonId,pPersonName,pDayBlockId,pHourBlockId,pValue){var person=this.people.find(function(p){return(p.id==pPersonId&&p.type==pPersonType&&p.name==pPersonName);});var choice=person.choices.find(function(c){return(c.dayBlockId==pDayBlockId&&c.hourBlockId==pHourBlockId);});choice.value=pValue;if(party.UpdateForm){var time=party.dayBlocks[pDayBlockId].day+" "+party.dayBlocks[pDayBlockId].hourBlocks[pHourBlockId].hour;party.UpdateForm.addRdvField({target:'vote',user_id:pPersonId,user_name:pPersonName,vote_target:'time',vote_time:time,vote_value:choice.value});}
this.drawParty();},toggleRdvPlaceEventChoice:function(pPersonType,pPersonId,pPersonName,pPlaceOrder,pValue){var person=this.people.find(function(p){return(p.id==pPersonId&&p.type==pPersonType&&p.name==pPersonName);});var choice=person.place_event_choices.find(function(c){return(c.placeOrder==pPlaceOrder);});choice.value=pValue;if(party.UpdateForm){var place=this.places[pPlaceOrder];party.UpdateForm.addRdvField({target:'vote',user_id:pPersonId,user_name:pPersonName,vote_target:'place_event',vote_place_event:place.id,vote_place_event_type:place.type,vote_value:choice.value});}
this.drawParty();},showGradients:function(){var element=$('options_choices');var gradR=$('rdv_gradR');var gradL=$('rdv_gradL');if(element.scrollLeft==element.scrollWidth-element.clientWidth){gradR.hide();}else{gradR.show();}
if(element.scrollLeft!=0){gradL.show();}else{gradL.hide();}}};var DayBlock=Class.create();DayBlock.prototype={initialize:function(order,dayString){this.width=114;this.day=dayString;this.order=order;this.hourBlocks=new Array();},addHour:function(dayBlockId,hourString){var nbHourBlocks=this.hourBlocks.size();this.hourBlocks[nbHourBlocks]=new HourBlock(nbHourBlocks,hourString);if(nbHourBlocks>1){this.width=114+58*(nbHourBlocks-1);}},getCode:function(nbDayBlocks){var code='<div id="day_block_'+this.order+'" class="day_block">'
+'<div class="day_line">'
+'<div id="day_'+this.order+'" class="day" style="width:'+(this.width-2)+'px;">'
+'<div class="edit_date" id="edit_day_'+this.order+'">';if(party.isOwner||party.newRecord){code+='<a href="#" class="editable" onclick="killPopup();party.displayDayOptions('+this.order+');return false">'
+this.day
+'</a>';}else{code+=this.day;}
code+='</div>';if(party.editable_time||party.isOwner||party.newRecord){var suggested_time=this.day+' '+this.hourBlocks[this.hourBlocks.length-1].hour;code+='<div class="add_delete_day">'
+'<div class="add_day">'
+'<a href="#" onclick="createCalendarDateSelect('+this.order+'); return false;">'
+'<span class="icon icon_add" title="'+I18n.t('rendezvous.add_date')+'"></span>'
+'</a>'
+'<input type="hidden" id="add_day_field_'+this.order+'" value="'+suggested_time+'" />'
+'</div>';if(party.isOwner||party.newRecord){code+='<div class="delete_day">'
+'<a href="#" onclick="if (confirm(I18n.t(\'rendezvous.confirm.delete_day\'))) { party.deleteDayBlock('+this.order+'); }; return false;">'
+'<span class="icon icon_delete" title="'+I18n.t('rendezvous.remove_date')+'"></span>'
+'</a>'
+'<input type="hidden" id="add_day_field_'+this.order+'" value="'+suggested_time+'" />'
+'</div>'}
code+='</div>';}
code+='</div>'
+'</div>';nbHourBlocks=this.hourBlocks.size();dayBlockId=this.order;this.hourBlocks.each(function(hourBlockElement){code+=hourBlockElement.getCode(nbHourBlocks,dayBlockId);});code+='</div>';return code;}};function createCalendarDateSelect(order){new CalendarDateSelect($('add_day_field_'+order),{clear_button:false,close_button:true,time:true,year_range:[(new Date).getFullYear(),(new Date).getFullYear()+10],after_show:function(){s=$$('span.button_seperator')[0];s.previous('a').hide();s.hide();},after_close:function(){party.addDayBlock($(this).value,true);},valid_date_check:function(date){return(date.stripTime()>=(new Date()).stripTime());}});}
var HourBlock=Class.create();HourBlock.prototype={initialize:function(nbHourBlocks,hourString){this.order=nbHourBlocks;this.hour=hourString;},getCode:function(nbHourBlocks,dayBlockId){var code="<div id=\"hour_block_"+this.order+"\" class=\"hour_block\">"+"  <div class=\"hour_line\">"+"    <div class=\"hour_slot\" ";if(nbHourBlocks==1)code+="style=\"width: 112px\"";code+=" >"+"      <div class=\"edit_hour\" id=\"edit_hour_"+dayBlockId+"_"+this.order+"\">";if(party.isOwner||party.newRecord){code+="        <a href=\"javascript:killPopup();party.displayHourOptions("+dayBlockId+","+this.order+")\" class=\"editable\"> "+
this.hour+"        </a> ";}else{code+=this.hour;}
code+="      </div> ";code+="    </div>"+"  </div>"+"</div>";return code;}};var Person=Class.create();Person.prototype={initialize:function(nbPeople,hourBInDayB,name,nbPlaceEvents,type,id){this.order=nbPeople;this.name=name;this.type=type;this.id=id;this.choices=new Array();this.initChoice(hourBInDayB);this.place_event_choices=new Array();this.initChoicePlaceEvents(nbPlaceEvents);},initChoice:function(hourBInDayB){var choiceIdx=0;var choices_tmp=new Array();hourBInDayB.each(function(nbHourBlocksInDayBlock,dayBlockIdx){$R(1,nbHourBlocksInDayBlock).each(function(s,hourBlockIdx){choices_tmp[choiceIdx++]=new Choice(dayBlockIdx,hourBlockIdx);});});this.choices=choices_tmp;},initChoicePlaceEvents:function(nbPlaceEvents){var choiceIdx=0;var pe_choices_tmp=new Array();$R(1,nbPlaceEvents).each(function(s,placeEventIdx){pe_choices_tmp[choiceIdx++]=new ChoicePlaceEvent(placeEventIdx);});this.place_event_choices=pe_choices_tmp;},addChoice:function(dayBlockId,hourBlockId){var nbChoices=this.choices.size();if(hourBlockId==null){hourBlockId=0;}
this.choices[nbChoices]=new Choice(dayBlockId,hourBlockId);this.choices=this.choices.sortBy(function(s){return(s.dayBlockId*100+s.hourBlockId);});},addPlaceEventChoice:function(){var nbPeChoices=this.place_event_choices.size();this.place_event_choices[nbPeChoices]=new ChoicePlaceEvent(nbPeChoices);},getPersonName:function(){var divId='person_'+this.name.gsub(/\W/,'').underscore();var code="<div class=\"person_name";code+=" "+this.type.underscore()+"_icon";if(this.id==party.currentUser)
code+=" current_user";code+="\" id=\""+divId+"\">";if(party.isOwner||party.newRecord){code+=" <a class=\"editable\" href='javascript:party.displayPersonOptions("+this.name.toJSON()+", "+(this.id?this.id.toJSON():'null')+", "+this.type.toJSON()+")'> "+
this.name+" </a>";}else{code+=this.name;}
code+="</div>";return code;},getPersonChoices:function(hourBInDayB){var code="";var person_name=this.name;var person=this;var hourBInDayBIdx=0;var current_person=this;this.choices.each(function(choiceElement){if(choiceElement.hourBlockId==0&&choiceElement.dayBlockId!=0){hourBInDayBIdx++;}
code+="<div class=\"choice choice_"+choiceElement.value;if(hourBInDayB[hourBInDayBIdx]==1){code+="\" style=\"width: 104px;";}
code+="\">";if(current_person.canEdit()||current_person.id==party.currentUser||(party.newRecord&&current_person.type=='AnonymousUser')){code+=" <select onchange=\"party.toggleRdvChoice('"+person.type+"', "+(person.id?"'"+person.id+"'":'null')+", '"+person.name+"', "+choiceElement.dayBlockId+", "+choiceElement.hourBlockId+", "+"this.value"+")\" >";var i=1;for(i=1;i>-2;i--)
{code+="<option "
if(choiceElement.value==i)
code+="selected ";code+="value=\""+i+"\">"+I18n.t('rendezvous.choice_'+i)+"</option>";}
code+="</select>";}else{if(!party.currentUser&&person.type=='RegisteredUser'){code+="  <a class=\"editable\" href=\"javascript:displayLoginToModifyChoiceNotice()\">";code+=I18n.t('rendezvous.choice_'+choiceElement.value)+"\n";code+="  </a>2"}else{code+="  <div>"
code+=I18n.t('rendezvous.choice_'+choiceElement.value)+"\n";code+="  </div>"}}
code+="</div>";});return code;},getPersonChoicesPlaceEvents:function(){var code="";var current_person=this;var person_name=this.name;var person=this;this.place_event_choices.each(function(peChoiceElement){code+="<div class=\"choice choice_"+peChoiceElement.value;code+="\" style=\"width: 115px;\">";if(current_person.canEdit()||current_person.id==party.currentUser||(party.newRecord&&current_person.type=='AnonymousUser')){code+=" <select onchange=\"party.toggleRdvPlaceEventChoice('"+person.type+"', "+(person.id?"'"+person.id+"'":'null')+", '"+person.name+"', "+peChoiceElement.placeOrder+", "+"parseInt(this.value)"+")\" >";var i=2;for(i=2;i>-3;i--)
{code+="<option "
if(peChoiceElement.value==i)
code+="selected ";code+="value=\""+i+"\">"+I18n.t('rendezvous.place_event_choice_'+i)+"</option>";}
code+="</select>";}else{if(!party.currentUser&&person.type=='RegisteredUser'){code+="  <a class=\"editable\" href=\"javascript:displayLoginToModifyChoiceNotice()\">";code+=I18n.t('rendezvous.place_event_choice_'+peChoiceElement.value)+"\n";code+="  </a>4"}else{code+="  <div>"
code+=I18n.t('rendezvous.place_event_choice_'+peChoiceElement.value)+"\n";code+="  </div>"}}
code+="</div>"});return code;},canEdit:function(){if(this.type=='AnonymousUser'){var cookieName=party.getCookieStoredName();var cookieTokens=[];var nameTokens=[];cookieTokens=cookieName.split('%2C');var isNameInCookie=(cookieTokens.indexOf(this.name.sub(" ","+",10))>-1);return isNameInCookie;}
return false;},setChoices:function(choicesParam){this.choices.each(function(choiceElement,choiceIdx){choiceElement.value=choicesParam[choiceIdx];});},setChoicesPlaces:function(choicesParam){this.place_event_choices.each(function(choiceElement,choiceIdx){choiceElement.value=choicesParam[choiceIdx];});}};var Choice=Class.create();Choice.prototype={initialize:function(dayBlockId,hourBlockId){this.dayBlockId=dayBlockId;this.hourBlockId=hourBlockId;this.value=0;}};var Place=Class.create();Place.prototype={initialize:function(nbPlaces,placeName,placeId,placeType,placeBrand,bookLink){this.id=placeId;this.order=nbPlaces;this.name=placeName;this.type=placeType;this.background=placeBrand;this.booking=bookLink;},getCode:function(){code="";code+="<div class=\"day_block\">"+"  <div id=\"place_option_"+this.id+"\" class=\"place_option\""
if(this.background!=null&&this.background.length>0){code+=" style=\"background-image: url('"+this.background+"')\"";}
if(this.type=="Place"){code+=" onclick=\"gotoPlace("+this.id+");\">";}else{code+=" onclick=\"gotoEvent("+this.id+");\">";}
code+="  <span title='"+I18n.t('rendezvous.click_for_details')+"' class='icon icon_zoom'></span>";code+="  <div class='rdv_close_button'>";if(party.isOwner||party.newRecord){code+="  <a onclick=\"party.deletePlace('"+this.name+"',"+this.id+",'"+this.type+"');return false;\" href='#'>"+"    <img title=\""+I18n.t('rendezvous.remove_place_or_event')+"\" src='/images/close.png' alt='"+I18n.t('rendezvous.remove_place_or_event')+"' />"+"  </a>";}
code+="  </div>";if(this.background!=null&&this.background.length>0){}else if(this.type=="Place"){code+="<a class=\"place_link\" href=\"javascript:gotoPlace("+this.id+");\"/>"+
this.name+"</a>"}else{code+="<a class=\"place_link\" href=\"javascript:gotoEvent("+this.id+");\"/>"+
this.name+"</a>"}
if(this.booking!=null&&!this.booking.empty()){code+="<a class=\"place_book_link\" href=\""+this.booking+"\">"+I18n.t('place.book')+"</a>"}
code+="  </div>"+"</div>";return code;}};var ChoicePlaceEvent=Class.create();ChoicePlaceEvent.prototype={initialize:function(placeOrder){this.placeOrder=placeOrder;this.value=0;}};function setSize(){if($$('div.person_choices').size()<=0)
return false;var peopleChoicesWidth=$$('div.person_choices')[0].childElements().inject(0,function(acc,el){return acc+el.getWidth()+2;});$('people_choices').setStyle({width:peopleChoicesWidth+'px'});}
function delaySetSize(){if($('datetimes_places_events').offsetWidth==0){setTimeout('delaySetSize()',500);}else{setSize();}}
function convertRubyDateStringtoJSDate(dateString){var year=dateString.substr(0,4);var month=dateString.substr(5,2);var day=dateString.substr(8,2);var hours=dateString.substr(11,2);var minutes=dateString.substr(14,2);var result=new Date(year,month-1,day,hours,minutes);return result;}
function displayLoginToModifyChoiceNotice(){displayNotice(I18n.t('rendezvous.login_to_modify_choice_notice'));$('menu_login_form').appear();}
Autocompleter.Contacts=Class.create(Autocompleter.Base,{initialize:function(element,update,options){this.baseInitialize(element,update,options);},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;var createListItem=function(contact,text){var res="";res+="<li class=\""+contact['class'].underscore()+"_icon\" "+"id=\""+contact['class'].underscore()+'_'+contact.id+"\">";res+=text;res+="</li>";return res;};for(var i=0;i<contacts.length&&ret.length<instance.options.choices;i++){var contact=contacts[i];var elem=contact.name;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(createListItem(contact,"<strong>"+elem.substr(0,entry.length)+"</strong>"+
elem.substr(entry.length)));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(createListItem(contact,elem.substr(0,foundPos)+"<strong>"+elem.substr(foundPos,entry.length)+"</strong>"+
elem.substr(foundPos+entry.length)));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||{});},updateElement:function(selectedElement){if(this.options.updateElement){this.options.updateElement.call(this,selectedElement);return;}
var elementId=$(selectedElement).readAttribute('id');var match=/(\w+)_(\d+)/.exec(elementId);var contactClass=match[1].capitalize().dasherize().camelize();var contactId=match[2];if(contactClass=="ContactList"){this.addContactList(contactId);}else{var contact=contacts.find(function(c){return(c['class']==contactClass&&c.id==contactId);});party.addPerson(contact.name,contact['class'],contact.id);if(contact['class']!="AnonymousUser"&&party.unnotified_people.indexOf(contact.name)<0)
party.unnotified_people.push(contact.name);}
this.oldElementValue=this.element.value='';this.element.focus();if(this.options.afterUpdateElement){this.options.afterUpdateElement.call(this,this.element,selectedElement);}},addContactList:function(clId){var list=contactLists.find(function(l){return(l.id==clId);});list.members.each(function(m){var contact=contacts.find(function(c){return(c['class']==m['class']&&c.id==m.id);});party.addPerson(contact.name,contact['class'],contact.id,true);if(contact['class']!="AnonymousUser"&&party.unnotified_people.indexOf(contact.name)<0)
party.unnotified_people.push(contact.name);});party.drawParty();}});function contactsUserEntryKeyPressed(e){if(e.keyCode==Event.KEY_TAB||e.keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&e.keyCode==0)){callCreateVisitor();}}
function callCreateVisitor(){if(!party.first)
return;var visitorName=$F('contacts_user_entry').strip();if(visitorName.empty())return;new Ajax.Request('/rendezvous/create_visitor',{asynchronous:false,parameters:{"visitor[name]":visitorName},onLoading:function(){gSpinner.show()}});}
function bookmarkLink(title,url){if(window.sidebar){window.sidebar.addPanel(title,url,"");}else if(window.external){window.external.AddFavorite(url,title);}}
function displaySaveButton(button){if(button==null)
button=$('rendezvous_save_button');button.appear();}
function dimSaveButton(button){if(button==null)
button=$('rendezvous_save_button');if(!button.hasClassName('greyed')){button.addClassName('greyed');xtdom.addEventListener(button,'click',preventEditing,true);button.down('span').innerHTML=I18n.t('rendezvous.saved_button_title');}}
function lightenSaveButton(button){if(button==null)
button=$('rendezvous_save_button');if(button.hasClassName('greyed')){button.removeClassName('greyed');button.removeEventListener('click',preventEditing,true);button.down('span').innerHTML=I18n.t('rendezvous.save_button_title');}}
function preventEditing(e){return;if(e.preventDefault)
e.preventDefault();else
e.returnResult=false;if(e.stopPropagation)
e.stopPropagation();else
e.cancelBubble=true;return false;}
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;}});function updateStarRating(id,value){$(id).value=value;$(id+'_current_rating').style.width=''+(value/5.0*100)+'%'}
var tl;var MilTimeline={onXMLLoaded:function(xml,url){var es=this.getBand(0).getEventSource();es.loadXML(xml,url);this.finishedEventLoading();this.addLimitDecorators();this.finishedEventLoading();},addLimitDecorators:function(){var i;var es=this.getBand(0).getEventSource();var negativeInfinity=new Date(-4000,0,0);var positiveInfinity=new Date(4000,0,0);if(es.getCount()>0){var eventsStart=es.getEarliestDate().valueOf()-3*24*60*60*1000;var eventsStop=es.getLatestDate().valueOf()+3*24*60*60*1000;var beforeEventsDecorator;var afterEventsDecorator;for(i=0;i<this.getBandCount();++i){beforeEventsDecorator=new Timeline.SpanHighlightDecorator({startDate:negativeInfinity,endDate:eventsStart,color:"#ffc080",opacity:50});beforeEventsDecorator.initialize(this.getBand(i),this);afterEventsDecorator=new Timeline.SpanHighlightDecorator({startDate:eventsStop,endDate:positiveInfinity,color:"#ffc080",opacity:50});afterEventsDecorator.initialize(this.getBand(i),this);this.getBand(i)._decorators.push(beforeEventsDecorator);this.getBand(i)._decorators.push(afterEventsDecorator);}
this.timeline_start=eventsStart;this.timeline_stop=eventsStop;}else{var noEventsDecorator;for(i=0;i<this.getBandCount();++i){noEventsDecorator=new Timeline.SpanHighlightDecorator({startDate:negativeInfinity,endDate:positiveInfinity,color:"#ffc080",opacity:50});noEventsDecorator.initialize(this.getBand(i),this);this.getBand(i)._decorators.push(noEventsDecorator);}}}};MilTimeline.LocalizedLabeller=Class.create();Object.extend(MilTimeline.LocalizedLabeller.prototype,Timeline.GregorianDateLabeller.prototype);MilTimeline.LocalizedLabeller.addMethods({initialize:function(locale,timezone){Timeline.GregorianDateLabeller.call(this,locale,timezone);},labelPrecise:function(date){date=SimileAjax.DateTime.removeTimeZoneOffset(date,this._timeZone);return date.format(Date.i18n(this._locale).formats.dateTimeMedium,this._locale);}});function loadTimeline(loadurl,divname){var eventSource=new Timeline.DefaultEventSource();var theme=Timeline.ClassicTheme.create();theme.autoWidth=true;var localizedLabeller=new MilTimeline.LocalizedLabeller(Timeline.serverLocale,2);var bandInfos=[Timeline.createBandInfo({date:new Date(),eventSource:eventSource,intervalPixels:60,intervalUnit:Timeline.DateTime.DAY,layout:"original",theme:theme,timeZone:2,width:160}),Timeline.createBandInfo({date:new Date(),eventSource:eventSource,intervalPixels:100,intervalUnit:Timeline.DateTime.MONTH,layout:"overview",timeZone:2,width:40})];bandInfos[1].syncWith=0;bandInfos[1].highlight=true;bandInfos[0].labeller=bandInfos[1].labeller=localizedLabeller;tl=Timeline.create(document.getElementById(divname),bandInfos);Object.extend(tl,MilTimeline);Timeline.loadXML(loadurl,tl.onXMLLoaded.bind(tl));}
if(typeof(Control)=='undefined')
Control={};var $proc=function(proc){return typeof(proc)=='function'?proc:function(){return proc};};var $value=function(value){return typeof(value)=='function'?value():value;};Object.Event={extend:function(object){object._objectEventSetup=function(event_name){this._observers=this._observers||{};this._observers[event_name]=this._observers[event_name]||[];};object.observe=function(event_name,observer){if(typeof(event_name)=='string'&&typeof(observer)!='undefined'){this._objectEventSetup(event_name);if(!this._observers[event_name].include(observer))
this._observers[event_name].push(observer);}else
for(var e in event_name)
this.observe(e,event_name[e]);};object.stopObserving=function(event_name,observer){this._objectEventSetup(event_name);if(event_name&&observer)
this._observers[event_name]=this._observers[event_name].without(observer);else if(event_name)
this._observers[event_name]=[];else
this._observers={};};object.observeOnce=function(event_name,outer_observer){var inner_observer=function(){outer_observer.apply(this,arguments);this.stopObserving(event_name,inner_observer);}.bind(this);this._objectEventSetup(event_name);this._observers[event_name].push(inner_observer);};object.notify=function(event_name){this._objectEventSetup(event_name);var collected_return_values=[];var args=$A(arguments).slice(1);try{for(var i=0;i<this._observers[event_name].length;++i)
collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i],args)||null);}catch(e){if(e==$break)
return false;else
throw e;}
return collected_return_values;};if(object.prototype){object.prototype._objectEventSetup=object._objectEventSetup;object.prototype.observe=object.observe;object.prototype.stopObserving=object.stopObserving;object.prototype.observeOnce=object.observeOnce;object.prototype.notify=function(event_name){if(object.notify){var args=$A(arguments).slice(1);args.unshift(this);args.unshift(event_name);object.notify.apply(object,args);}
this._objectEventSetup(event_name);var args=$A(arguments).slice(1);var collected_return_values=[];try{if(this.options&&this.options[event_name]&&typeof(this.options[event_name])=='function')
collected_return_values.push(this.options[event_name].apply(this,args)||null);for(var i=0;i<this._observers[event_name].length;++i)
collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i],args)||null);}catch(e){if(e==$break)
return false;else
throw e;}
return collected_return_values;};}}};Element.addMethods({observeOnce:function(element,event_name,outer_callback){var inner_callback=function(){outer_callback.apply(this,arguments);Element.stopObserving(element,event_name,inner_callback);};Element.observe(element,event_name,inner_callback);}});Object.extend(Event,(function(){var cache=Event.cache;function getEventID(element){if(element._prototypeEventID)return element._prototypeEventID[0];arguments.callee.id=arguments.callee.id||1;return element._prototypeEventID=[++arguments.callee.id];}
function getDOMEventName(eventName){if(eventName&&eventName.include(':'))return"dataavailable";if(!Prototype.Browser.IE){eventName={mouseenter:'mouseover',mouseleave:'mouseout'}[eventName]||eventName;}
return eventName;}
function getCacheForID(id){return cache[id]=cache[id]||{};}
function getWrappersForEventName(id,eventName){var c=getCacheForID(id);return c[eventName]=c[eventName]||[];}
function createWrapper(element,eventName,handler){var id=getEventID(element);var c=getWrappersForEventName(id,eventName);if(c.pluck("handler").include(handler))return false;var wrapper=function(event){if(!Event||!Event.extend||(event.eventName&&event.eventName!=eventName))
return false;Event.extend(event);handler.call(element,event);};if(!(Prototype.Browser.IE)&&['mouseenter','mouseleave'].include(eventName)){wrapper=wrapper.wrap(function(proceed,event){var rel=event.relatedTarget;var cur=event.currentTarget;if(rel&&rel.nodeType==Node.TEXT_NODE)
rel=rel.parentNode;if(rel&&rel!=cur&&!rel.descendantOf(cur))
return proceed(event);});}
wrapper.handler=handler;c.push(wrapper);return wrapper;}
function findWrapper(id,eventName,handler){var c=getWrappersForEventName(id,eventName);return c.find(function(wrapper){return wrapper.handler==handler});}
function destroyWrapper(id,eventName,handler){var c=getCacheForID(id);if(!c[eventName])return false;c[eventName]=c[eventName].without(findWrapper(id,eventName,handler));}
function destroyCache(){for(var id in cache)
for(var eventName in cache[id])
cache[id][eventName]=null;}
if(window.attachEvent){window.attachEvent("onunload",destroyCache);}
return{observe:function(element,eventName,handler){element=$(element);var name=getDOMEventName(eventName);var wrapper=createWrapper(element,eventName,handler);if(!wrapper)return element;if(element.addEventListener){element.addEventListener(name,wrapper,false);}else{element.attachEvent("on"+name,wrapper);}
return element;},stopObserving:function(element,eventName,handler){element=$(element);var id=getEventID(element),name=getDOMEventName(eventName);if(!handler&&eventName){getWrappersForEventName(id,eventName).each(function(wrapper){element.stopObserving(eventName,wrapper.handler);});return element;}else if(!eventName){Object.keys(getCacheForID(id)).each(function(eventName){element.stopObserving(eventName);});return element;}
var wrapper=findWrapper(id,eventName,handler);if(!wrapper)return element;if(element.removeEventListener){element.removeEventListener(name,wrapper,false);}else{element.detachEvent("on"+name,wrapper);}
destroyWrapper(id,eventName,handler);return element;},fire:function(element,eventName,memo){element=$(element);if(element==document&&document.createEvent&&!element.dispatchEvent)
element=document.documentElement;var event;if(document.createEvent){event=document.createEvent("HTMLEvents");event.initEvent("dataavailable",true,true);}else{event=document.createEventObject();event.eventType="ondataavailable";}
event.eventName=eventName;event.memo=memo||{};if(document.createEvent){element.dispatchEvent(event);}else{element.fireEvent(event.eventType,event);}
return Event.extend(event);}};})());Object.extend(Event,Event.Methods);Element.addMethods({fire:Event.fire,observe:Event.observe,stopObserving:Event.stopObserving});Object.extend(document,{fire:Element.Methods.fire.methodize(),observe:Element.Methods.observe.methodize(),stopObserving:Element.Methods.stopObserving.methodize()});(function(){function wheel(event){var delta;if(event.wheelDelta)
delta=event.wheelDelta/120;else if(event.detail)
delta=-event.detail/3;if(!delta)
return;var custom_event=Event.element(event).fire('mouse:wheel',{delta:delta});if(custom_event.stopped){Event.stop(event);return false;}}
document.observe('mousewheel',wheel);document.observe('DOMMouseScroll',wheel);})();var IframeShim=Class.create({initialize:function(){this.element=new Element('iframe',{style:'position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);display:none',src:'javascript:void(0);',frameborder:0});$(document.body).insert(this.element);},hide:function(){this.element.hide();return this;},show:function(){this.element.show();return this;},positionUnder:function(element){var element=$(element);var offset=element.cumulativeOffset();var dimensions=element.getDimensions();this.element.setStyle({left:offset[0]+'px',top:offset[1]+'px',width:dimensions.width+'px',height:dimensions.height+'px',zIndex:element.getStyle('zIndex')-1}).show();return this;},setBounds:function(bounds){for(prop in bounds)
bounds[prop]+='px';this.element.setStyle(bounds);return this;},destroy:function(){if(this.element)
this.element.remove();return this;}});var Resizables={instances:[],observers:[],register:function(resizable){if(this.instances.length==0){this.eventMouseUp=this.endResize.bindAsEventListener(this);this.eventMouseMove=this.updateResize.bindAsEventListener(this);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);}
this.instances.push(resizable);},unregister:function(resizable){this.instances=this.instances.reject(function(d){return d==resizable});if(this.instances.length==0){Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);}},activate:function(resizable){if(resizable.options.delay){this._timeout=setTimeout(function(){Resizables._timeout=null;Resizables.activeResizable=resizable;}.bind(this),resizable.options.delay);}else{this.activeResizable=resizable;}},deactivate:function(){this.activeResizable=null;},updateResize:function(event){if(!this.activeResizable)return;var pointer=[Event.pointerX(event),Event.pointerY(event)];if(this._lastPointer&&(this._lastPointer.inspect()==pointer.inspect()))return;this._lastPointer=pointer;this.activeResizable.updateResize(event,pointer);},endResize:function(event){if(this._timeout){clearTimeout(this._timeout);this._timeout=null;}
if(!this.activeResizable)return;this._lastPointer=null;this.activeResizable.endResize(event);this.activeResizable=null;},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,resizable,event){if(this[eventName+'Count']>0)
this.observers.each(function(o){if(o[eventName])o[eventName](eventName,resizable,event);});if(resizable.options[eventName])resizable.options[eventName](resizable,event);},_cacheObserverCallbacks:function(){['onStart','onEnd','onResize'].each(function(eventName){Resizables[eventName+'Count']=Resizables.observers.select(function(o){return o[eventName];}).length;});}}
var Resizable=Class.create();Resizable._resizing={};Resizable.prototype={initialize:function(element){var defaults={handle:false,snap:false,delay:0,minHeight:false,minwidth:false,maxHeight:false,maxWidth:false}
this.element=$(element);var options=Object.extend(defaults,arguments[1]||{});if(options.handle&&typeof options.handle=='string')
this.handle=$(options.handle);else if(options.handle)
this.handle=options.handle;if(!this.handle)this.handle=this.element;this.options=options;this.dragging=false;this.eventMouseDown=this.initResize.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Resizables.register(this);},destroy:function(){Event.stopObserving(this.handle,"mousedown",this.eventMouseDown);},currentDelta:function(){return([parseInt(Element.getStyle(this.element,'width')||'0'),parseInt(Element.getStyle(this.element,'height')||'0')]);},initResize:function(event){if(typeof Resizable._resizing[this.element]!='undefined'&&Resizable._resizing[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;this.pointer=[Event.pointerX(event),Event.pointerY(event)];this.size=[parseInt(this.element.getStyle('width'))||0,parseInt(this.element.getStyle('height'))||0];Resizables.activate(this);Event.stop(event);}},startResize:function(event){this.resizing=true;if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,'z-index')||0);this.element.style.zIndex=this.options.zindex;}
Resizables.notify('onStart',this,event);Resizable._resizing[this.element]=true;},updateResize:function(event,pointer){if(!this.resizing)this.startResize(event);Resizables.notify('onResize',this,event);this.draw(pointer);if(this.options.change)this.options.change(this);if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);},finishResize:function(event,success){this.resizing=false;Resizables.notify('onEnd',this,event);if(this.options.zindex)this.element.style.zIndex=this.originalZ;Resizable._resizing[this.element]=false;Resizables.deactivate(this);},endResize:function(event){if(!this.resizing)return;this.finishResize(event,true);Event.stop(event);},draw:function(point){var p=[0,1].map(function(i){return(this.size[i]+point[i]-this.pointer[i]);}.bind(this));if(this.options.snap){if(typeof this.options.snap=='function'){p=this.options.snap(p[0],p[1],this);}else{if(this.options.snap instanceof Array){p=p.map(function(v,i){return Math.round(v/this.options.snap[i])*this.options.snap[i]}.bind(this))}else{p=p.map(function(v){return Math.round(v/this.options.snap)*this.options.snap}.bind(this))}}}
var minWidth=(typeof(this.options.minWidth)=='function')?this.options.minWidth(this.element):this.options.minWidth;var maxWidth=(typeof(this.options.maxWidth)=='function')?this.options.maxWidth(this.element):this.options.maxWidth;var minHeight=(typeof(this.options.minHeight)=='function')?this.options.minHeight(this.element):this.options.minHeight;var maxHeight=(typeof(this.options.maxHeight)=='function')?this.options.maxHeight(this.element):this.options.maxHeight;if(minWidth&&p[0]<=minWidth)p[0]=minWidth;if(maxWidth&&p[0]>=maxWidth)p[0]=maxWidth;if(minHeight&&p[1]<=minHeight)p[1]=minHeight;if(maxHeight&&p[1]>=maxHeight)p[1]=maxHeight;var style=this.element.style;if((!this.options.constraint)||(this.options.constraint=='horizontal')){style.width=p[0]+"px";}
if((!this.options.constraint)||(this.options.constraint=='vertical')){style.height=p[1]+"px";}
if(style.visibility=="hidden")style.visibility="";}};if(typeof(Draggable)!='undefined'){Draggable.prototype.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(typeof this.options.snap=='function'){p=this.options.snap(p[0],p[1],this);}else{if(this.options.snap instanceof Array){p=p.map(function(v,i){return Math.round(v/this.options.snap[i])*this.options.snap[i]}.bind(this))}else{p=p.map(function(v){return Math.round(v/this.options.snap)*this.options.snap}.bind(this))}}}
if(this.options.onDraw)
this.options.onDraw.bind(this)(p);else{var style=this.element.style;if(this.options.constrainToViewport){var viewport_dimensions=document.viewport.getDimensions();var container_dimensions=this.element.getDimensions();var margin_top=parseInt(this.element.getStyle('margin-top'));var margin_left=parseInt(this.element.getStyle('margin-left'));var boundary=[[0-margin_left,0-margin_top],[(viewport_dimensions.width-container_dimensions.width)-margin_left,(viewport_dimensions.height-container_dimensions.height)-margin_top]];if((!this.options.constraint)||(this.options.constraint=='horizontal')){if((p[0]>=boundary[0][0])&&(p[0]<=boundary[1][0]))
this.element.style.left=p[0]+"px";else
this.element.style.left=((p[0]<boundary[0][0])?boundary[0][0]:boundary[1][0])+"px";}
if((!this.options.constraint)||(this.options.constraint=='vertical')){if((p[1]>=boundary[0][1])&&(p[1]<=boundary[1][1]))
this.element.style.top=p[1]+"px";else
this.element.style.top=((p[1]<=boundary[0][1])?boundary[0][1]:boundary[1][1])+"px";}}else{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="";}};}
if(typeof(Prototype)=="undefined")
throw"Control.Window requires Prototype to be loaded.";if(typeof(IframeShim)=="undefined")
throw"Control.Window requires IframeShim to be loaded.";if(typeof(Object.Event)=="undefined")
throw"Control.Window requires Object.Event to be loaded.";Control.Window=Class.create({initialize:function(container,options){Control.Window.windows.push(this);this.container=false;this.isOpen=false;this.href=false;this.sourceContainer=false;this.ajaxRequest=false;this.remoteContentLoaded=false;this.numberInSequence=Control.Window.windows.length+1;this.indicator=false;this.effects={fade:false,appear:false};this.indicatorEffects={fade:false,appear:false};this.options=Object.extend({beforeOpen:Prototype.emptyFunction,afterOpen:Prototype.emptyFunction,beforeClose:Prototype.emptyFunction,afterClose:Prototype.emptyFunction,height:null,width:null,className:false,position:'center',offsetLeft:0,offsetTop:0,iframe:false,hover:false,indicator:false,closeOnClick:false,iframeshim:true,fade:false,fadeDuration:0.75,draggable:false,onDrag:Prototype.emptyFunction,resizable:false,minHeight:false,minWidth:false,maxHeight:false,maxWidth:false,onResize:Prototype.emptyFunction,constrainToViewport:false,method:'post',parameters:{},onComplete:Prototype.emptyFunction,onSuccess:Prototype.emptyFunction,onFailure:Prototype.emptyFunction,onException:Prototype.emptyFunction,onRemoteContentLoaded:Prototype.emptyFunction,insertRemoteContentAt:false},options||{});this.indicator=this.options.indicator?$(this.options.indicator):false;if(container){if(typeof(container)=="string"&&container.match(Control.Window.uriRegex))
this.href=container;else{this.container=$(container);this.createDefaultContainer(container);if(this.container&&((this.container.readAttribute('href')&&this.container.readAttribute('href')!='')||(this.options.hover&&this.options.hover!==true))){if(this.options.hover&&this.options.hover!==true)
this.sourceContainer=$(this.options.hover);else{this.sourceContainer=this.container;this.href=this.container.readAttribute('href');var rel=this.href.match(/^#(.+)$/);if(rel&&rel[1]){this.container=$(rel[1]);this.href=false;}else
this.container=false;}
this.sourceContainerOpenHandler=function(event){this.open(event);event.stop();return false;}.bindAsEventListener(this);this.sourceContainerCloseHandler=function(event){this.close(event);}.bindAsEventListener(this);this.sourceContainerMouseMoveHandler=function(event){this.position(event);}.bindAsEventListener(this);if(this.options.hover){this.sourceContainer.observe('mouseenter',this.sourceContainerOpenHandler);this.sourceContainer.observe('mouseleave',this.sourceContainerCloseHandler);if(this.options.position=='mouse')
this.sourceContainer.observe('mousemove',this.sourceContainerMouseMoveHandler);}else
this.sourceContainer.observe('click',this.sourceContainerOpenHandler);}}}
this.createDefaultContainer(container);if(this.options.insertRemoteContentAt===false)
this.options.insertRemoteContentAt=this.container;var styles={margin:0,position:'absolute',zIndex:Control.Window.initialZIndexForWindow()};if(this.options.width)
styles.width=$value(this.options.width)+'px';if(this.options.height)
styles.height=$value(this.options.height)+'px';this.container.setStyle(styles);if(this.options.className)
this.container.addClassName(this.options.className);this.positionHandler=this.position.bindAsEventListener(this);this.outOfBoundsPositionHandler=this.ensureInBounds.bindAsEventListener(this);this.bringToFrontHandler=this.bringToFront.bindAsEventListener(this);this.container.observe('mousedown',this.bringToFrontHandler);this.container.hide();this.closeHandler=this.close.bindAsEventListener(this);if(this.options.iframeshim){this.iFrameShim=new IframeShim();this.iFrameShim.hide();}
this.applyResizable();this.applyDraggable();Event.observe(window,'resize',this.outOfBoundsPositionHandler);this.notify('afterInitialize');},open:function(event){if(this.isOpen){this.bringToFront();return false;}
if(this.notify('beforeOpen')===false)
return false;if(this.options.closeOnClick){if(this.options.closeOnClick===true)
this.closeOnClickContainer=$(document.body);else if(this.options.closeOnClick=='container')
this.closeOnClickContainer=this.container;else if(this.options.closeOnClick=='overlay'){Control.Overlay.load();this.closeOnClickContainer=Control.Overlay.container;}else
this.closeOnClickContainer=$(this.options.closeOnClick);this.closeOnClickContainer.observe('click',this.closeHandler);}
if(this.href&&!this.options.iframe&&!this.remoteContentLoaded){this.remoteContentLoaded=true;if(this.href.match(/\.(jpe?g|gif|png|tiff?)$/i)){var img=new Element('img');img.observe('load',function(img){this.getRemoteContentInsertionTarget().insert(img);this.position();if(this.notify('onRemoteContentLoaded')!==false){if(this.options.indicator)
this.hideIndicator();this.finishOpen();}}.bind(this,img));img.writeAttribute('src',this.href);}else{if(!this.ajaxRequest){if(this.options.indicator)
this.showIndicator();this.ajaxRequest=new Ajax.Request(this.href,{method:this.options.method,parameters:this.options.parameters,onComplete:function(request){this.notify('onComplete',request);this.ajaxRequest=false;}.bind(this),onSuccess:function(request){this.getRemoteContentInsertionTarget().insert(request.responseText);this.notify('onSuccess',request);if(this.notify('onRemoteContentLoaded')!==false){if(this.options.indicator)
this.hideIndicator();this.finishOpen();}}.bind(this),onFailure:function(request){this.notify('onFailure',request);if(this.options.indicator)
this.hideIndicator();}.bind(this),onException:function(request,e){this.notify('onException',request,e);if(this.options.indicator)
this.hideIndicator();}.bind(this)});}}
return true;}else if(this.options.iframe&&!this.remoteContentLoaded){this.remoteContentLoaded=true;if(this.options.indicator)
this.showIndicator();this.getRemoteContentInsertionTarget().insert(Control.Window.iframeTemplate.evaluate({href:this.href}));var iframe=this.container.down('iframe');iframe.onload=function(){this.notify('onRemoteContentLoaded');if(this.options.indicator)
this.hideIndicator();iframe.onload=null;}.bind(this);}
this.finishOpen(event);return true},close:function(event){if(!this.isOpen||this.notify('beforeClose',event)===false)
return false;if(this.options.closeOnClick)
this.closeOnClickContainer.stopObserving('click',this.closeHandler);if(this.options.fade){this.effects.fade=new Effect.Fade(this.container,{queue:{position:'front',scope:'Control.Window'+this.numberInSequence},from:1,to:0,duration:this.options.fadeDuration/2,afterFinish:function(){if(this.iFrameShim)
this.iFrameShim.hide();this.isOpen=false;this.notify('afterClose');}.bind(this)});}else{this.container.hide();if(this.iFrameShim)
this.iFrameShim.hide();}
if(this.ajaxRequest)
this.ajaxRequest.transport.abort();if(!(this.options.draggable||this.options.resizable)&&this.options.position=='center')
Event.stopObserving(window,'resize',this.positionHandler);if(!this.options.draggable&&this.options.position=='center')
Event.stopObserving(window,'scroll',this.positionHandler);if(this.options.indicator)
this.hideIndicator();if(!this.options.fade){this.isOpen=false;this.notify('afterClose');}
return true;},position:function(event){if(this.options.position=='mouse'){var xy=[Event.pointerX(event),Event.pointerY(event)];this.container.setStyle({top:xy[1]+$value(this.options.offsetTop)+'px',left:xy[0]+$value(this.options.offsetLeft)+'px'});return;}
var container_dimensions=this.container.getDimensions();var viewport_dimensions=document.viewport.getDimensions();Position.prepare();var offset_left=(Position.deltaX+Math.floor((viewport_dimensions.width-container_dimensions.width)/2));var offset_top=(Position.deltaY+((viewport_dimensions.height>container_dimensions.height)?Math.floor((viewport_dimensions.height-container_dimensions.height)/2):0));if(this.options.position=='center'){this.container.setStyle({top:(container_dimensions.height<=viewport_dimensions.height)?((offset_top!=null&&offset_top>0)?offset_top:0)+'px':0,left:(container_dimensions.width<=viewport_dimensions.width)?((offset_left!=null&&offset_left>0)?offset_left:0)+'px':0});}else if(this.options.position=='relative'){var xy=this.sourceContainer.cumulativeOffset();var top=xy[1]+$value(this.options.offsetTop);var left=xy[0]+$value(this.options.offsetLeft);this.container.setStyle({top:(container_dimensions.height<=viewport_dimensions.height)?(this.options.constrainToViewport?Math.max(0,Math.min(viewport_dimensions.height-(container_dimensions.height),top)):top)+'px':0,left:(container_dimensions.width<=viewport_dimensions.width)?(this.options.constrainToViewport?Math.max(0,Math.min(viewport_dimensions.width-(container_dimensions.width),left)):left)+'px':0});}else if(this.options.position.length){var top=$value(this.options.position[1])+$value(this.options.offsetTop);var left=$value(this.options.position[0])+$value(this.options.offsetLeft);this.container.setStyle({top:(container_dimensions.height<=viewport_dimensions.height)?(this.options.constrainToViewport?Math.max(0,Math.min(viewport_dimensions.height-(container_dimensions.height),top)):top)+'px':0,left:(container_dimensions.width<=viewport_dimensions.width)?(this.options.constrainToViewport?Math.max(0,Math.min(viewport_dimensions.width-(container_dimensions.width),left)):left)+'px':0});}
if(this.iFrameShim)
this.updateIFrameShimZIndex();},ensureInBounds:function(){if(!this.isOpen)
return;var viewport_dimensions=document.viewport.getDimensions();var container_offset=this.container.cumulativeOffset();var container_dimensions=this.container.getDimensions();if(container_offset.left+container_dimensions.width>viewport_dimensions.width){this.container.setStyle({left:(Math.max(0,viewport_dimensions.width-container_dimensions.width))+'px'});}
if(container_offset.top+container_dimensions.height>viewport_dimensions.height){this.container.setStyle({top:(Math.max(0,viewport_dimensions.height-container_dimensions.height))+'px'});}},bringToFront:function(){Control.Window.bringToFront(this);this.notify('bringToFront');},destroy:function(){this.container.stopObserving('mousedown',this.bringToFrontHandler);if(this.draggable){Draggables.removeObserver(this.container);this.draggable.handle.stopObserving('mousedown',this.bringToFrontHandler);this.draggable.destroy();}
if(this.resizable){Resizables.removeObserver(this.container);this.resizable.handle.stopObserving('mousedown',this.bringToFrontHandler);this.resizable.destroy();}
if(this.container&&!this.sourceContainer)
this.container.remove();if(this.sourceContainer){if(this.options.hover){this.sourceContainer.stopObserving('mouseenter',this.sourceContainerOpenHandler);this.sourceContainer.stopObserving('mouseleave',this.sourceContainerCloseHandler);if(this.options.position=='mouse')
this.sourceContainer.stopObserving('mousemove',this.sourceContainerMouseMoveHandler);}else
this.sourceContainer.stopObserving('click',this.sourceContainerOpenHandler);}
if(this.iFrameShim)
this.iFrameShim.destroy();Event.stopObserving(window,'resize',this.outOfBoundsPositionHandler);Control.Window.windows=Control.Window.windows.without(this);this.notify('afterDestroy');},applyResizable:function(){if(this.options.resizable){if(typeof(Resizable)=="undefined")
throw"Control.Window requires resizable.js to be loaded.";var resizable_handle=null;if(this.options.resizable===true){resizable_handle=new Element('div',{className:'resizable_handle'});this.container.insert(resizable_handle);}else
resizable_handle=$(this.options.resziable);this.resizable=new Resizable(this.container,{handle:resizable_handle,minHeight:this.options.minHeight,minWidth:this.options.minWidth,maxHeight:this.options.constrainToViewport?function(element){return(document.viewport.getDimensions().height-parseInt(element.style.top||0))-(element.getHeight()-parseInt(element.style.height||0));}:this.options.maxHeight,maxWidth:this.options.constrainToViewport?function(element){return(document.viewport.getDimensions().width-parseInt(element.style.left||0))-(element.getWidth()-parseInt(element.style.width||0));}:this.options.maxWidth});this.resizable.handle.observe('mousedown',this.bringToFrontHandler);Resizables.addObserver(new Control.Window.LayoutUpdateObserver(this,function(){if(this.iFrameShim)
this.updateIFrameShimZIndex();this.notify('onResize');}.bind(this)));}},applyDraggable:function(){if(this.options.draggable){if(typeof(Draggables)=="undefined")
throw"Control.Window requires dragdrop.js to be loaded.";var draggable_handle=null;if(this.options.draggable===true){draggable_handle=new Element('div',{className:'draggable_handle'});this.container.insert(draggable_handle);}else
draggable_handle=$(this.options.draggable);this.draggable=new Draggable(this.container,{handle:draggable_handle,constrainToViewport:this.options.constrainToViewport,zindex:this.container.getStyle('z-index'),starteffect:function(){if(Prototype.Browser.IE){this.old_onselectstart=document.onselectstart;document.onselectstart=function(){return false;};}}.bind(this),endeffect:function(){document.onselectstart=this.old_onselectstart;}.bind(this)});this.draggable.handle.observe('mousedown',this.bringToFrontHandler);Draggables.addObserver(new Control.Window.LayoutUpdateObserver(this,function(){if(this.iFrameShim)
this.updateIFrameShimZIndex();this.notify('onDrag');}.bind(this)));}},createDefaultContainer:function(container){if(!this.container){this.container=new Element('div',{id:'control_window_'+this.numberInSequence});$(document.body).insert(this.container);if(typeof(container)=="string"&&$(container)==null&&!container.match(/^#(.+)$/)&&!container.match(Control.Window.uriRegex))
this.container.update(container);}},finishOpen:function(event){this.bringToFront();if(this.options.fade){if(typeof(Effect)=="undefined")
throw"Control.Window requires effects.js to be loaded."
if(this.effects.fade)
this.effects.fade.cancel();this.effects.appear=new Effect.Appear(this.container,{queue:{position:'end',scope:'Control.Window.'+this.numberInSequence},from:0,to:1,duration:this.options.fadeDuration/2,afterFinish:function(){if(this.iFrameShim)
this.updateIFrameShimZIndex();this.isOpen=true;this.notify('afterOpen');}.bind(this)});}else
this.container.show();this.position(event);if(!(this.options.draggable||this.options.resizable)&&this.options.position=='center')
Event.observe(window,'resize',this.positionHandler,false);if(!this.options.draggable&&this.options.position=='center')
Event.observe(window,'scroll',this.positionHandler,false);if(!this.options.fade){this.isOpen=true;this.notify('afterOpen');}
return true;},showIndicator:function(){this.showIndicatorTimeout=window.setTimeout(function(){if(this.options.fade){this.indicatorEffects.appear=new Effect.Appear(this.indicator,{queue:{position:'front',scope:'Control.Window.indicator.'+this.numberInSequence},from:0,to:1,duration:this.options.fadeDuration/2});}else
this.indicator.show();}.bind(this),Control.Window.indicatorTimeout);},hideIndicator:function(){if(this.showIndicatorTimeout)
window.clearTimeout(this.showIndicatorTimeout);this.indicator.hide();},getRemoteContentInsertionTarget:function(){return typeof(this.options.insertRemoteContentAt)=="string"?this.container.down(this.options.insertRemoteContentAt):$(this.options.insertRemoteContentAt);},updateIFrameShimZIndex:function(){if(this.iFrameShim)
this.iFrameShim.positionUnder(this.container);}});Object.extend(Control.Window,{windows:[],baseZIndex:9999,indicatorTimeout:250,iframeTemplate:new Template('<iframe src="#{href}" width="100%" height="100%" frameborder="0"></iframe>'),uriRegex:/^(\/|\#|https?\:\/\/|[\w]+\/)/,bringToFront:function(w){Control.Window.windows=Control.Window.windows.without(w);Control.Window.windows.push(w);Control.Window.windows.each(function(w,i){var z_index=Control.Window.baseZIndex+i;w.container.setStyle({zIndex:z_index});if(w.isOpen){if(w.iFrameShim)
w.updateIFrameShimZIndex();}
if(w.options.draggable)
w.draggable.options.zindex=z_index;});},open:function(container,options){var w=new Control.Window(container,options);w.open();return w;},initialZIndexForWindow:function(w){return Control.Window.baseZIndex+(Control.Window.windows.length-1);}});Object.Event.extend(Control.Window);Control.Window.LayoutUpdateObserver=Class.create({initialize:function(w,observer){this.w=w;this.element=$(w.container);this.observer=observer;},onStart:Prototype.emptyFunction,onEnd:function(event_name,instance){if(instance.element==this.element&&this.iFrameShim)
this.w.updateIFrameShimZIndex();},onResize:function(event_name,instance){if(instance.element==this.element)
this.observer(this.element);},onDrag:function(event_name,instance){if(instance.element==this.element)
this.observer(this.element);}});Control.Overlay={id:'control_overlay',loaded:false,container:false,lastOpacity:0,styles:{position:'fixed',top:0,left:0,width:'100%',height:'100%',zIndex:9998},ieStyles:{position:'absolute',top:0,left:0,zIndex:9998},effects:{fade:false,appear:false},load:function(){if(Control.Overlay.loaded)
return false;Control.Overlay.loaded=true;Control.Overlay.container=new Element('div',{id:Control.Overlay.id});$(document.body).insert(Control.Overlay.container);if(Prototype.Browser.IE){Control.Overlay.container.setStyle(Control.Overlay.ieStyles);Event.observe(window,'scroll',Control.Overlay.positionOverlay);Event.observe(window,'resize',Control.Overlay.positionOverlay);Control.Overlay.observe('beforeShow',Control.Overlay.positionOverlay);}else
Control.Overlay.container.setStyle(Control.Overlay.styles);Control.Overlay.iFrameShim=new IframeShim();Control.Overlay.iFrameShim.hide();Event.observe(window,'resize',Control.Overlay.positionIFrameShim);Control.Overlay.container.hide();return true;},unload:function(){if(!Control.Overlay.loaded)
return false;Event.stopObserving(window,'resize',Control.Overlay.positionOverlay);Control.Overlay.stopObserving('beforeShow',Control.Overlay.positionOverlay);Event.stopObserving(window,'resize',Control.Overlay.positionIFrameShim);Control.Overlay.iFrameShim.destroy();Control.Overlay.container.remove();Control.Overlay.loaded=false;return true;},show:function(opacity,fade){if(Control.Overlay.notify('beforeShow')===false)
return false;Control.Overlay.lastOpacity=opacity;Control.Overlay.positionIFrameShim();Control.Overlay.iFrameShim.show();if(fade){if(typeof(Effect)=="undefined")
throw"Control.Window requires effects.js to be loaded."
if(Control.Overlay.effects.fade)
Control.Overlay.effects.fade.cancel();Control.Overlay.effects.appear=new Effect.Appear(Control.Overlay.container,{queue:{position:'end',scope:'Control.Overlay'},afterFinish:function(){Control.Overlay.notify('afterShow');},from:0,to:Control.Overlay.lastOpacity,duration:(fade===true?0.75:fade)/2});}else{Control.Overlay.container.setStyle({opacity:opacity||1});Control.Overlay.container.show();Control.Overlay.notify('afterShow');}
return true;},hide:function(fade){if(Control.Overlay.notify('beforeHide')===false)
return false;if(Control.Overlay.effects.appear)
Control.Overlay.effects.appear.cancel();Control.Overlay.iFrameShim.hide();if(fade){Control.Overlay.effects.fade=new Effect.Fade(Control.Overlay.container,{queue:{position:'front',scope:'Control.Overlay'},afterFinish:function(){Control.Overlay.notify('afterHide');},from:Control.Overlay.lastOpacity,to:0,duration:(fade===true?0.75:fade)/2});}else{Control.Overlay.container.hide();Control.Overlay.notify('afterHide');}
return true;},positionIFrameShim:function(){if(Control.Overlay.container.visible())
Control.Overlay.iFrameShim.positionUnder(Control.Overlay.container);},positionOverlay:function(){Control.Overlay.container.setStyle({width:document.body.clientWidth+'px',height:document.body.clientHeight+'px'});}};Object.Event.extend(Control.Overlay);Control.ToolTip=Class.create(Control.Window,{initialize:function($super,container,tooltip,options){$super(tooltip,Object.extend(Object.extend(Object.clone(Control.ToolTip.defaultOptions),options||{}),{position:'mouse',hover:container}));}});Object.extend(Control.ToolTip,{defaultOptions:{offsetLeft:10}});Control.Modal=Class.create(Control.Window,{initialize:function($super,container,options){Control.Modal.InstanceMethods.beforeInitialize.bind(this)();$super(container,Object.extend(Object.clone(Control.Modal.defaultOptions),options||{}));}});Object.extend(Control.Modal,{defaultOptions:{overlayOpacity:0.5,closeOnClick:'overlay'},current:false,open:function(container,options){var modal=new Control.Modal(container,options);modal.open();return modal;},close:function(){if(Control.Modal.current)
Control.Modal.current.close();},InstanceMethods:{beforeInitialize:function(){Control.Overlay.load();this.overlayFinishedOpening=false;this.observe('beforeOpen',Control.Modal.Observers.beforeOpen.bind(this));this.observe('afterOpen',Control.Modal.Observers.afterOpen.bind(this));this.observe('afterClose',Control.Modal.Observers.afterClose.bind(this));}},Observers:{beforeOpen:function(){if(!this.overlayFinishedOpening){Control.Overlay.observeOnce('afterShow',function(){this.overlayFinishedOpening=true;this.open();}.bind(this));Control.Overlay.show(this.options.overlayOpacity,this.options.fade?this.options.fadeDuration:false);throw $break;}else
Control.Window.windows.without(this).invoke('close');},afterOpen:function(){Control.Modal.current=this;},afterClose:function(){Control.Overlay.hide(this.options.fade?this.options.fadeDuration:false);Control.Modal.current=false;this.overlayFinishedOpening=false;}}});Control.LightBox=Class.create(Control.Window,{initialize:function($super,container,options){this.allImagesLoaded=false;if(options.modal){var options=Object.extend(Object.clone(Control.LightBox.defaultOptions),options||{});options=Object.extend(Object.clone(Control.Modal.defaultOptions),options);options=Control.Modal.InstanceMethods.beforeInitialize.bind(this)(options);$super(container,options);}else
$super(container,Object.extend(Object.clone(Control.LightBox.defaultOptions),options||{}));this.hasRemoteContent=this.href&&!this.options.iframe;if(this.hasRemoteContent)
this.observe('onRemoteContentLoaded',Control.LightBox.Observers.onRemoteContentLoaded.bind(this));else
this.applyImageObservers();this.observe('beforeOpen',Control.LightBox.Observers.beforeOpen.bind(this));},applyImageObservers:function(){var images=this.getImages();this.numberImagesToLoad=images.length;this.numberofImagesLoaded=0;images.each(function(image){image.observe('load',function(image){++this.numberofImagesLoaded;if(this.numberImagesToLoad==this.numberofImagesLoaded){this.allImagesLoaded=true;this.onAllImagesLoaded();}}.bind(this,image));image.hide();}.bind(this));},onAllImagesLoaded:function(){this.getImages().each(function(image){this.showImage(image);}.bind(this));if(this.hasRemoteContent){if(this.options.indicator)
this.hideIndicator();this.finishOpen();}else
this.open();},getImages:function(){return this.container.select(Control.LightBox.imageSelector);},showImage:function(image){image.show();}});Object.extend(Control.LightBox,{imageSelector:'img',defaultOptions:{},Observers:{beforeOpen:function(){if(!this.hasRemoteContent&&!this.allImagesLoaded)
throw $break;},onRemoteContentLoaded:function(){this.applyImageObservers();if(!this.allImagesLoaded)
throw $break;}}});var xtigerProcessor=null;function computeSynchronousRequestsTimeout(){if(xtiger.cross.UA.IE){return 100;}
return 0;}
function viewTab(id,type,tab){new Ajax.Updater(tab,'/xtiger/load_tab',{method:'get',evalScripts:true,asynchronous:true,parameters:{id:id,type:type,tab:tab,lang:$F('view_newlang_'+tab)},onLoading:function(){gSpinner.show();$('xt_content_'+tab).hide();},onComplete:function(){$('xt_content_'+tab).show();gSpinner.hide();if($(tab).hasClassName('edit')){$(tab).removeClassName('edit');$(tab).addClassName('visu');}}});}
function editTab(id,type,tab,template){gSpinner.show();$('xt_content_'+tab).hide();setTimeout(function(){var lang=$F('edit_newlang_'+tab);var url="/xtiger/translate"
+"?id="+id
+"&type="+type
+"&template="+template
+"&lang="+lang;var result=new xtiger.util.Logger();var xtDoc=xtiger.cross.loadDocument(url,result);if(xtDoc){var iurl="/xtiger/load_instance"
+"?id="+id
+"&type="+type
+"&tab="+tab
+"&lang="+lang;xtigerProcessor=new xtiger.util.Form('/xtiger_bundles');xtigerProcessor.setTemplateSource(xtDoc.documentElement);xtigerProcessor.setTargetDocument(document,'xt_content_'+tab,true);xtigerProcessor.enableTabGroupNavigation();xtigerProcessor.transform(result);xtigerProcessor.loadDataFromUrl(iurl);}
if(result.inError()){}
if($(tab).hasClassName('visu')){$(tab).removeClassName('visu');$(tab).addClassName('edit');}
$('save_xtiger_'+tab).setAttribute('onclick',"saveTab("+id+", '"+type+"', '"+tab+"', '"+template+"'); return false;");$('xt_content_'+tab).show();gSpinner.hide();},computeSynchronousRequestsTimeout());}
function saveTab(id,type,tab,template){gSpinner.show();setTimeout(function(){var lang=$F('edit_newlang_'+tab);var url="/xtiger/save"
+"?id="+id
+"&template="+template
+"&tab="+tab
+"&lang="+lang
+"&type="+type;xtigerProcessor.postDataToUrl(url,xtiger.cross.getXHRObject());var viewSelect=$('view_newlang_'+tab);var addIt=true;for(var i=0;i<viewSelect.options.length;i++){if(viewSelect.options[i].value==lang){viewSelect.options[i].setAttribute('selected','selected');addIt=false;}else{viewSelect.options[i].removeAttribute('selected');}}
if(addIt){var option=new Element('option',{value:lang});option.innerHTML=lang;viewSelect.appendChild(option);viewSelect.selectedIndex=viewSelect.options.length-1;}
if(viewSelect.options.length>1){viewSelect.up().show();}
viewTab(id,type,tab,template);},computeSynchronousRequestsTimeout());}
function reloadXT(id,type,tab,template){var select=$('edit_newlang_'+tab);var otherSelect=$('view_newlang_'+tab);if(otherSelect!=null){$(otherSelect).value=$F(select);}
editTab(id,type,tab,template);}
function finishTransmission(status,msg){var pwin=window.parent;var manager=xtiger.factory('upload').getInstance(document);if(manager){manager.reportEoT(status,msg);}}
function addHStoMenu(menu_pictures){menu_pictures.each(function(pic){var thumbnail=$$('.xtt-photo[src="'+pic[1]+'"]')[0];if(thumbnail!=undefined&&thumbnail.parentNode.nodeName!='A'){var hs_link=new Element('a',{'class':'highslide',href:pic[0],onclick:'return hs.expand(this)'});hs_link.appendChild(thumbnail.cloneNode(true));thumbnail.replace(hs_link);}});}
if(typeof xtiger=="undefined"||!xtiger){var xtiger={};xtiger.COMPONENT=1;xtiger.REPEAT=2;xtiger.USE=3;xtiger.BAG=4;xtiger.ATTRIBUTE=5;xtiger.SERVICE=6;xtiger.UNKNOWN=-1;}
xtiger.parser={};xtiger.editor={};xtiger.service={};xtiger.cross={};xtiger.util={};if(typeof xtdom=="undefined"||!xtdom){xtdom={};}
xtiger.util.Session=function(){this.store={};}
xtiger.util.Session.prototype={save:function(name,object){this.store[name]=object;},load:function(name){return this.store[name];}}
xtiger.session=function(doc){if(!doc._xtigerSession){doc._xtigerSession=new xtiger.util.Session();}
return doc._xtigerSession;}
xtiger.util.Resources=function(){this.bundles={};xtiger.bundles={};}
xtiger.util.Resources.prototype={_mountBundle:function(name,baseurl){var bsrc=this.bundles[name];var bdest=xtiger.bundles[name];for(var k in bsrc){bdest[k]=baseurl+name+'/'+bsrc[k];}},addBundle:function(name,bundle){this.bundles[name]=bundle;xtiger.bundles[name]={};for(var k in bundle){xtiger.bundles[name][k]=bundle[k];}},setBase:function(baseUrl){if(baseUrl.charAt(baseUrl.length-1)!='/'){baseUrl=baseUrl+'/';}
for(var bkey in this.bundles){this._mountBundle(bkey,baseUrl);}}}
xtiger.resources=new xtiger.util.Resources();xtiger.util.FactoryRegistry=function(){this.store={};}
xtiger.util.FactoryRegistry.prototype={registerFactory:function(name,factory){if(this.store[name]){alert("Error (AXEL) attempt to register an already registered factory : '"+name+"' !");}else{this.store[name]=factory;}},getFactoryFor:function(name){if(!this.store[name]){alert("Fatal Error (AXEL) unkown factory required : '"+name+"' \nYour editor will NOT be generated !");}else{return this.store[name];}}}
xtiger.registry=new xtiger.util.FactoryRegistry();xtiger.factory=function(name){return xtiger.registry.getFactoryFor(name);}
xtdom.counterId=0;xtdom.genId=function(){return xtdom.counterId++;}
xtdom.createTextNode=function(doc,text){return doc.createTextNode(text);}
xtdom.hasAttribute=function(node,name){return node.hasAttribute(name);}
xtdom.removeElement=function(element){var _parent=element.parentNode;if(!_parent)
return;_parent.removeChild(element);}
xtdom.containsXT=function(node){if(node.nodeType==xtdom.ELEMENT_NODE){if(xtdom.isXT(node)){return true;}else{if(node.childNodes&&node.childNodes.length>0){for(var i=0;i<node.childNodes.length;i++)
if(xtdom.containsXT(node.childNodes[i])){return true;}}}}
return false;}
xtdom.getMenuMarkerXT=function(node){var res=false;var results=xtdom.getElementsByTagNameXT(node,'menu-marker');if(results.length>0){res=results[0];}
return res;}
xtdom.getTagNameXT=function(node){var key=(xtiger.ATTRIBUTE==xtdom.getNodeTypeXT(node))?'name':'label';return node.getAttribute(key);}
xtdom.extractDefaultContentXT=function(node){var dump=false;if(xtiger.ATTRIBUTE==xtdom.getNodeTypeXT(node)){dump=node.getAttribute('default');}else if(node.childNodes){for(var i=0;i<node.childNodes.length;i++){var str;var cur=node.childNodes[i];if(cur.nodeType==xtdom.ELEMENT_NODE){str=cur.innerHTML;}else{str=cur.nodeValue;}
if(dump){dump+=str;}else{dump=str;}}}
return dump;}
xtdom.getFirstElementChildOf=function(node){var res;for(var i=0;i<node.childNodes.length;i++){if(node.childNodes[i].nodeType==xtdom.ELEMENT_NODE){res=node.childNodes[i];break;}}
return res;}
xtdom.moveNodesAfter=function(nodes,target){var n;if(target.nextSibling){var next=target.nextSibling;while(n=nodes.shift()){next.parentNode.insertBefore(n,next);}}else{while(n=nodes.shift()){target.parentNode.appendChild(n);}}}
xtdom.moveChildrenOfAfter=function(parentSrc,target){var n;if(target.nextSibling){var next=target.nextSibling;while(n=parentSrc.firstChild){parentSrc.removeChild(n);next.parentNode.insertBefore(n,next);}}else{while(n=parentSrc.firstChild){parentSrc.removeChild(n);target.parentNode.appendChild(n);}}}
xtdom.importChildOfInto=function(targetDoc,srcNode,destNode){for(var i=0;i<srcNode.childNodes.length;i++){var src=srcNode.childNodes[i];var copy=xtdom.importNode(targetDoc,srcNode.childNodes[i],true);destNode.appendChild(copy);}}
xtdom.replaceNodeByChildOf=function(former,newer,accu){var parent=former.parentNode;var n;while(n=newer.firstChild){newer.removeChild(n);parent.insertBefore(n,former,true);if(accu){accu.push(n);}}
parent.removeChild(former);}
xtdom.removeChildrenOf=function(aNode){aNode.innerHTML="";}
xtdom.moveChildOfInto=function(former,newer,accu){var n;while(n=former.firstChild){former.removeChild(n);newer.appendChild(n);if(accu){accu.push(n);}}}
xtdom.getInlineDisplay=function(aNode){var res='';if((aNode.style)&&(aNode.style.display)){res=aNode.style.display;}
return res;}
xtdom.getSelectedOpt=function(sel){for(var i=0;i<sel.options.length;i++){if(sel.options[i].selected){break;}}
return i;}
xtdom.setSelectedOpt=function(sel,index){sel.selectedIndex=index;}
xtdom.addClassName=function(node,name){if(node.className){if(node.className.search(name)==-1){if(node.className.length==0){node.className=name;}else{node.className+=" "+name;}}}else{node.className=name;}}
xtdom.removeClassName=function(node,name){if(node.className){var index=node.className.search(name);if(index!=-1){node.className=node.className.substr(0,index)+node.className.substr(index+name.length);}}}
xtdom.replaceClassNameBy=function(node,formerName,newName){var index=node.className.search(formerName);if(index!=-1){node.className=node.className.substr(0,index)+newName+node.className.substr(index+formerName.length);}else{xtdom.addClassName(node,newName);}}
xtdom.getComputedStyle=function(aNode,aStyle){if(!aNode||!aNode.ownerDocument)
return null;var _doc=aNode.ownerDocument;if(window.getComputedStyle){return window.getComputedStyle(aNode,null).getPropertyValue(aStyle);}
else if(aNode.currentStyle){aStyle=aStyle.replace(/\-(\w)/g,function(strMatch,p1){return p1.toUpperCase();});return aNode.currentStyle[aStyle];}
return null;}
xtdom.findPos=function(obj){var curleft=curtop=0;if(obj.offsetParent){curleft=obj.offsetLeft
curtop=obj.offsetTop
if(document.defaultView)
var position=document.defaultView.getComputedStyle(obj,null).getPropertyValue('position');else if(document.uniqueID)
var position=obj.currentStyle.position;if(obj.scrollTop&&(position=='absolute')){curtop-=obj.scrollTop;}
if(obj.scrollLeft&&(position=='absolute')){curleft-=obj.scrollLeft;}
while(obj=obj.offsetParent){curleft+=obj.offsetLeft
curtop+=obj.offsetTop
if(document.defaultView)
var position=document.defaultView.getComputedStyle(obj,null).getPropertyValue('position');else if(document.uniqueID)
var position=obj.currentStyle.position;if(obj.scrollTop&&(position=='absolute')){curtop-=obj.scrollTop;}
if(obj.scrollLeft&&(position=='absolute')){curleft-=obj.scrollLeft;}}}
return[curleft,curtop];};xtdom.findPosAsSibling=function(aDocument,aElement){var _curleft=_curtop=0;var _obj=aElement;if(_obj.offsetParent){_curleft+=_obj.offsetLeft;_curtop+=_obj.offsetTop;while(_obj=_obj.offsetParent){if(aDocument.defaultView)
var _pos=aDocument.defaultView.getComputedStyle(_obj,null).getPropertyValue('position');else if(a)
if(_obj.scrollTop&&_pos=='absolute'){_curtop-=_obj.scrollTop;}
if(_obj.scrollLeft&&(_pos=='absolute')){_curleft-=_obj.scrollLeft;}
if(_pos=='absolute'||_pos=='fixed'||_pos=='relative')
break;_curleft+=_obj.offsetLeft;_curtop+=_obj.offsetTop;}}
return[_curleft,_curtop];}
xtdom.isOffsetAncestorOf=function(aNode,anAncestor){var _n=aNode.offsetParent;while(_n!=null){if(_n===anAncestor)
return true;_n=_n.offsetParent;}
return false;}
xtdom.findPostitionFrom=function(aNode,aContainer){if(!aNode||!aContainer)
return null;var _document=aNode.ownerDocument;var _offsetAncestor=aContainer;while(!xtdom.isOffsetAncestor(aNode,_offsetAncestor))
_offsetAncestor=_offsetAncestor.offsetParent;}
xtiger.util.DOMDataSource=function(sources){var d;this.xml=null;this.flow={};this.stack=[];if(sources){if(sources.constructor==={}.constructor){for(var k in sources){d=sources[k];if(d){(k=='document')?this.initFromDocument(d):this.initFlowFromDocument(d,k);}}}else{this.initFromDocument(sources);}}}
xtiger.util.DOMDataSource.prototype={hasData:function(){return(null!=this.xml);},_setRootNode:function(n){this.xml=n;},_setFlowNode:function(name,n){this.flow[name]=[0,n];},_initFromTide:function(tide){var c=tide.childNodes;for(var i=0;i<c.length;i++){var cur=c.item(i);if(cur.nodeType==xtdom.ELEMENT_NODE){if(this.xml==null){this._setRootNode(cur);}else{this._setFlowNode(xtdom.getLocalName(cur),cur);}}}},initFromDocument:function(doc){this.xml=null;if(doc&&doc.documentElement){var root=doc.documentElement;var tideOn=root.nodeName=='tide'||root.nodeName=='xt:tide';if(tideOn){this._initFromTide(root);}else{this._setRootNode(root);}}
return(this.xml!=null);},initFlowFromDocument:function(doc,name){var xml=(doc&&doc.documentElement)?this._setFlowNode(name,doc.documentElement):false;return xml!=false;},initFromString:function(str){var res=true;try{var parser=xtiger.cross.makeDOMParser();var doc=parser.parseFromString(str,"text/xml");this.initFromDocument(doc);}catch(e){alert('Exception : '+e.message);res=false;}
return res;},openFlow:function(name,curPoint,label){if(this.flow[name]){if(0===this.flow[name][0]){if(label&&(name==label)){this.flow[name]=[name,this.flow[name][1]];}else{this.flow[name]=this.makeRootVector(this.flow[name][1]);}}
this.stack.push([name,curPoint]);return this.flow[name];}
return false;},closeFlow:function(name,curPoint){var saved=(this.stack.length>0)?this.stack[this.stack.length-1]:false;if(saved&&(name==saved[0])){this.stack.pop();if(this.stack.length>0){this.flow[name]=curPoint;}
return saved[1];}
return false;},nameFor:function(point){if(point instanceof Array){return xtdom.getLocalName(point[0]);}else{return null;}},lengthFor:function(point){if(point instanceof Array){return point.length-1;}else{return 0;}},makeRootVector:function(rootNode){var res=[rootNode];if(rootNode){var c=rootNode.childNodes;for(var i=0;i<c.length;i++){var cur=c.item(i);if(cur.nodeType==xtdom.ELEMENT_NODE){res.push(cur);}}}
return res;},getRootVector:function(){return this.makeRootVector(this.xml);},hasDataFor:function(name,point){var res=false;if('@'==name.charAt(0)){if(point!==-1){res=xtdom.hasAttribute(point[0],name.substr(1));}}else if((point instanceof Array)&&(point.length>1)){if(point[1]&&(point[1].nodeType==xtdom.ELEMENT_NODE)){var nodeName=xtdom.getLocalName(point[1]);var found=name.search(nodeName);res=(found!=-1)&&(((found+nodeName.length)==name.length)||(name.charAt(found+nodeName.length)==' '));}}
return res;},getDataFor:function(point){if((point instanceof Array)&&(point.length>1)){return point[1];}else{return null;}},isEmpty:function(point){var res=false;if((point instanceof Array)&&(point.length>1)){if(point.length==2){if(typeof(point[1])=='string'){res=(point[1].search(/\S/)==-1);}}}else{res=true;}
return res;},getPointAtIndex:function(name,index,point){var res;var n=point.splice(index,1)[0];var c=n.childNodes;if((c.length==1)&&(c.item(0).nodeType==xtdom.TEXT_NODE)){var content=c.item(0).data;res=[n,content];}else{res=[n];for(var i=0;i<c.length;i++){var cur=c.item(i);if(cur.nodeType==xtdom.ELEMENT_NODE){res.push(cur);}}
if(res.length==1){res.push(null);}}
return res;},hasVectorFor:function(name,point){if(point instanceof Array){for(var i=1;i<point.length;i++){if((point[i]!==null)&&(point[i].nodeType==xtdom.ELEMENT_NODE)&&(xtdom.getLocalName(point[i])==name)){return true;}}}
return false;},getVectorFor:function(name,point){if(point instanceof Array){for(var i=1;i<point.length;i++){if((point[i]!==null)&&(point[i].nodeType==xtdom.ELEMENT_NODE)&&(xtdom.getLocalName(point[i])==name)){return this.getPointAtIndex(name,i,point);}}}
return-1;},hasAttributeFor:function(name,point){return(point instanceof Array)&&(point[0].getAttribute(name)!=null);},getAttributeFor:function(name,point){var res=-1
if(point instanceof Array){var n=point[0];var attr=n.getAttribute(name);if(attr){n.removeAttribute(name);res=[n,attr];}}
return res;},hasVectorForAnyOf:function(names,point){if(point instanceof Array){for(var i=1;i<point.length;i++){for(var j=0;j<names.length;j++){if((point[i]!==null)&&(point[i].nodeType==xtdom.ELEMENT_NODE)&&xtdom.getLocalName(point[i])==names[j]){return true;}}}}
return false;},getVectorForAnyOf:function(names,point){if(point instanceof Array){for(var i=1;i<point.length;i++){for(var j=0;j<names.length;j++){if((point[i]!==null)&&(point[i].nodeType==xtdom.ELEMENT_NODE)&&xtdom.getLocalName(point[i])==names[j]){return this.getPointAtIndex(names[j],i,point);}}}}
return-1;}}
xtiger.util.PseudoNode=function(type,value){this.type=type;this.discard=false;if(type==xtiger.util.PseudoNode.ELEMENT_NODE){this.name=value;this.attributes=null;this.content=null;}else{this.content=value;}}
xtiger.util.PseudoNode.TEXT_NODE=0;xtiger.util.PseudoNode.ELEMENT_NODE=1;xtiger.util.PseudoNode.NEWLINE='\n';xtiger.util.PseudoNode.prototype={indent:['','  '],discardNodeIfEmpty:function(){this.discard=true;},addChild:function(c){if(xtiger.util.PseudoNode.TEXT_NODE==c.type){this.content=c;}else{if(!this.content){this.content=[];}
if(this.content instanceof Array){this.content.push(c);}else{alert('Attempt to save mixed content in template !');}}},addAttribute:function(name,value){if(!this.attributes){this.attributes={};}
this.attributes[name]=value;},getIndentForLevel:function(level){if(typeof this.indent[level]!='string'){var spacer=this.indent[level-1];spacer+=this.indent[1];this.indent[level]=spacer;}
return this.indent[level];},dumpAttributes:function(){var text='';for(var k in this.attributes){text+=' ';text+=k;text+='="';text+=xtiger.util.encodeEntities(this.attributes[k]);text+='"';}
return text;},dump:function(level){if(xtiger.util.PseudoNode.TEXT_NODE==this.type){return xtiger.util.encodeEntities(this.content);}else{var text=this.getIndentForLevel(level);if(this.content){text+='<';text+=this.name;if(this.attributes){text+=this.dumpAttributes();}
text+='>';if(this.content instanceof Array){text+=xtiger.util.PseudoNode.NEWLINE;for(var i=0;i<this.content.length;i++){text+=this.content[i].dump(level+1);}
text+=this.getIndentForLevel(level);}else{text+=xtiger.util.encodeEntities(this.content.content);}
text+='</';text+=this.name;text+='>';}else{text+='<';text+=this.name;if(this.attributes){text+=this.dumpAttributes();}else if(this.discard){return'';}
text+='/>';}
text+=xtiger.util.PseudoNode.NEWLINE;return text;}}}
xtiger.util.DOMLogger=function(){this.stack=[];this.curTop=null;this.curAttr=null;this.curFlow=null;this.root=null;this.flow={};this.flowStack=[];}
xtiger.util.DOMLogger.prototype={discardNodeIfEmpty:function(){if(this.curTop){this.curTop.discardNodeIfEmpty()}},openAttribute:function(name){this.curAttr=name;},openFlow:function(name,label){if(!this.flow[name]){this.flow[name]=[null,null];}
this.flowStack.push([name,this.curTop,this.curFlow]);this.curTop=this.flow[name][1];this.curFlow=name;return true;},closeFlow:function(name){var saved=(this.flowStack.length>0)?this.flowStack[this.flowStack.length-1]:false;if(saved&&(name==saved[0])){this.flowStack.pop();this.flow[name][1]=this.curTop||this.flow[name][0];this.curTop=saved[1];this.curFlow=saved[2];return true;}
return false;},closeAttribute:function(name){if(this.curAttr!=name){alert('Attempt to close an attribute '+name+' while in attribute '+this.curAttr+'!');}
this.curAttr=null;},openTag:function(name){var n=new xtiger.util.PseudoNode(xtiger.util.PseudoNode.ELEMENT_NODE,name);if(!this.root){this.root=n;}else if(this.curFlow&&(!this.flow[this.curFlow][0])){if(this.curFlow==name){this.flow[this.curFlow][0]=n;}else{var r=new xtiger.util.PseudoNode(xtiger.util.PseudoNode.ELEMENT_NODE,this.curFlow);this.flow[this.curFlow][0]=r;r.addChild(n);}}
if(this.curTop){this.curTop.addChild(n);}
this.stack.push(this.curTop);this.curTop=n;},closeTag:function(name){this.curTop=this.stack.pop();},emptyTag:function(name){this.openTag(name);this.closeTag(name);},write:function(text){if(this.curAttr){this.curTop.addAttribute(this.curAttr,text);}else{var n=new xtiger.util.PseudoNode(xtiger.util.PseudoNode.TEXT_NODE,text);this.curTop.addChild(n);}},writeAttribute:function(name,value){this.curTop.addAttribute(name,value);},_dump:function(target,level){if(target=='document'){if(this.root){return this.root.dump(level);}else{return xtiger.util.PseudoNode.prototype.indent[level]+'<document/>\n';}}else{if(this.flow[target]){return this.flow[target][0].dump(level);}else{return xtiger.util.PseudoNode.prototype.indent[level]+'<'+target+'/>\n';}}},dump:function(selector){var todo;var target=selector||'document';if((target instanceof Array)||(target=='*')){if(((target instanceof Array)&&(target[0]=='*'))||((target=='*')&&(xtiger.util.countProperties(this.flow)>0))){todo=['document'];for(var k in this.flow){todo.push(k);}}else{todo=(target=='*')?'document':target;}}else{todo=target;}
if(todo instanceof Array){var output=[];output.push('<xt:tide xmlns:xt="'+xtiger.parser.nsXTiger+'">\n');for(var i=0;i<todo.length;i++){output.push(this._dump(todo[i],1));}
output.push('</xt:tide>\n');return output.join('');}else{return this._dump(todo,0);}},close:function(){}}
xtiger.cross.UA={IE:!!(window.attachEvent&&navigator.userAgent.indexOf('Opera')===-1),opera:navigator.userAgent.indexOf('Opera')>-1,webKit:navigator.userAgent.indexOf('AppleWebKit/')>-1,gecko:navigator.userAgent.indexOf('Gecko')>-1&&navigator.userAgent.indexOf('KHTML')===-1,mobileSafari:!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)}
if(!(xtiger.cross.UA.gecko||xtiger.cross.UA.webKit||xtiger.cross.UA.IE||xtiger.cross.UA.opera||xtiger.cross.UA.mobileSafari)){xtiger.cross.log('warning','XTiger Forms could not detect user agent name, assuming a Gecko like browser');xtiger.cross.UA.gecko=true;}
xtiger.util.countProperties=function(o){var total=0;for(var k in o)if(o.hasOwnProperty(k))total++;return total;}
xtiger.util.encodeEntities=function(s){if(!s){return s;}
var res=s;if(s.indexOf('&')!=-1){res=res.replace(/&(?![a-zA-Z]{3,5};)/g,'&amp;');}
if(s.indexOf('<')!=-1){res=res.replace(/</g,'&lt;');}
if(s.indexOf('>')!=-1){res=res.replace(/>/g,'&gt;');}
return res;}
xtiger.util.decodeEntities=function(s){if(s.indexOf('&amp;')!=-1){var res=s.replace(/&amp;/g,'&');if(s.indexOf('<')!=-1){return res.replace(/&lt;/g,'<');}
return res;}
return s;}
xtiger.util.decodeParameters=function(aString,aParams){if(!aString)
return;var _tokens=aString.split(';');for(var _i=0;_i<_tokens.length;_i++){var _parsedTok=_tokens[_i].split('=');var _key=_parsedTok[0].replace(/^\s*/,'').replace(/\s*$/,'');if(_key=='class'){_key='hasClass';}
aParams[_key]=_parsedTok[1];}}
xtiger.util.mixin=function mixin(obj,props){var tobj={};for(var x in props){if((typeof tobj[x]=="undefined")||(tobj[x]!=props[x])){obj[x]=props[x];}}
if(xtiger.cross.UA.IE&&(typeof(props["toString"])=="function")&&(props["toString"]!=obj["toString"])&&(props["toString"]!=tobj["toString"]))
{obj.toString=props.toString;}
return obj;}
xtiger.util.array_map=function array_map(aArray,aCallback){if(!(typeof aArray=='object'&&typeof aCallback=='function'))
return aArray;var _buf=[];for(var _i=0;_i<aArray.length;_i++){_buf[_i]=aCallback(aArray[_i]);}
return _buf;}
xtiger.util.array_filter=function array_filter(aArray,aCallback){if(!(typeof aArray=='object'&&typeof aCallback=='function'))
return aArray;var _buf=[];for(var _i=0;_i<aArray.length;_i++){if(aCallback(aArray[_i]))
_buf.push(aArray[_i]);}
return _buf;}
xtiger.util.array_contains=function array_contains(aArray,aElement){if(typeof aArray!='object')
return false;for(var _i=0;_i<aArray.length;_i++){if(aArray[_i]==aElement)
return true;if(typeof(aArray[_i])=='object'&&typeof(aElement)=='object')
if(xtiger.util.object_compare(aArray[_i],aElement))
return true;}
return false;}
xtiger.util.object_compare=function object_compare(aObject1,aObject2){for(_prop in aObject1){if(typeof(aObject2[_prop])=='undefined')
return false;}
for(_prop in aObject1){if(aObject1[_prop]){switch(typeof(aObject1[_prop]))
{case'object':if(!xtiger.util.object_compare(aObject1[_prop],aObject2[_prop])){return false;}
break;case'function':if(typeof(aObject2[_prop])=='undefined'||(_prop!='equals'&&aObject1[_prop].toString()!=aObject2[_prop].toString())){return false;}
break;default:if(aObject1[_prop]!=aObject2[_prop]){return false;}}}
else{if(aObject2[_prop]){return false;}}}
for(_prop in aObject2){if(typeof(aObject1[_prop])=='undefined'){return false;}}
return true;}
xtiger.cross.getXHRObject=function(){var xhr=false;if(window.XMLHttpRequest){xhr=new XMLHttpRequest();}else if(window.ActiveXObject){try{xhr=new ActiveXObject('Msxml2.XMLHTTP');}catch(e){try{xhr=new ActiveXObject('Microsoft.XMLHTTP');}catch(e){}}}
if(!xhr){alert("Your browser does not support XMLHTTPRequest");}
return xhr;}
xtiger.cross.loadDocument=function(url,logger){var xhr=xtiger.cross.getXHRObject();try{xhr.open("GET",url,false);xhr.send(null);if((xhr.status==200)||(xhr.status==0)){if(xhr.responseXML){return xhr.responseXML;}else if(logger){logger.logError('$$$ loaded but it contains no XML data',url);}}else if(logger){var explain=xhr.statusText?'('+xhr.statusText+')':'';logger.logError('HTTP error while loading $$$, status code : '+xhr.status+explain,url);}}catch(e){if(logger){logger.logError('Exception while loading $$$ : '+(e.message?e.message:e.name),url);}}
return false;}
xtiger.cross.log=function(channel,msg){switch(channel){case'error':case'fatal':xtiger.cross.print('[XX] '+msg);break;case'warning':xtiger.cross.print('[!!] '+msg);break;case'info':break;case'debug':xtiger.cross.print('[dd] '+msg);break;default:}}
xtiger.cross.print=function(aMessage){try{if(typeof(opera)!='undefined'&&opera.log){opera.postError(aMessage);}
else if(typeof(console)!='undefined'){if(/^\[!!\]/.test(aMessage)&&console.warn)
console.warn(aMessage);else if(/^\[XX\]/.test(aMessage)&&console.error)
console.error(aMessage);else if(console.log)
console.log(aMessage);}
else if(typeof(window.console)!='undefined'&&window.console.log){window.console.log(aMessage);}}catch(_err){alert(aMessage+"\nUnable to print on console ("+_err.message+")");}}
if(typeof DOMParser=="undefined"){xtiger.util.DOMParser=function(){};xtiger.util.DOMParser.prototype.parseFromString=function(str,contentType){if(typeof ActiveXObject!="undefined"){var d=new ActiveXObject("MSXML.DomDocument");d.loadXML(str);return d;}else if(typeof XMLHttpRequest!="undefined"){var req=new XMLHttpRequest;req.open("GET","data:"+(contentType||"application/xml")+";charset=utf-8,"+encodeURIComponent(str),false);if(req.overrideMimeType){req.overrideMimeType(contentType);}
req.send(null);return req.responseXML;}}
xtiger.cross.makeDOMParser=function(){return new xtiger.util.DOMParser();}}else{xtiger.cross.makeDOMParser=function(){return new DOMParser();}}
if(!document.createTreeWalker){xtiger.util.TreeWalker=function(node,nodeType,filter){this.nodeList=new Array();this.nodeType=nodeType;this.filter=filter;this.nodeIndex=-1;this.currentNode=null;this.findNodes(node);}
xtiger.util.TreeWalker.prototype={nextNode:function(){this.nodeIndex+=1;if(this.nodeIndex<this.nodeList.length){this.currentNode=this.nodeList[this.nodeIndex];return true;}else{this.nodeIndex=-1;return false;}},findNodes:function(node){if(node.nodeType==this.nodeType&&this.filter(node)==xtdom.NodeFilter.FILTER_ACCEPT){this.nodeList.push(node);}
if(node.nodeType==1){for(var i=0;i<node.childNodes.length;i++){this.findNodes(node.childNodes[i]);}}}}
xtiger.cross.makeTreeWalker=function(n,type,filter){return new xtiger.util.TreeWalker(n,type,filter)}}else{if(xtiger.cross.UA.webKit){xtiger.cross.makeTreeWalker=function(n,type,filter){return document.createTreeWalker(n,type,filter,false)}}else{xtiger.cross.makeTreeWalker=function(n,type,filter){var filterFunc={acceptNode:filter};return document.createTreeWalker(n,type,filterFunc,false);}}}
xtdom.getNodeTypeXT=function(aNode){var s=aNode.nodeName.toLowerCase();if((s=='use')||(s=='xt:use')){return xtiger.USE;}else if((s=='component')||(s=='xt:component')){return xtiger.COMPONENT;}else if((s=='repeat')||(s=='xt:repeat')){return xtiger.REPEAT;}else if((s=='bag')||(s=='xt:bag')){return xtiger.BAG;}else if((s=='attribute')||(s=='xt:attribute')){return xtiger.ATTRIBUTE;}else if((s=='service')||(s=='xte:service')){return xtiger.SERVICE;}else{return xtiger.UNKNOWN;}}
xtdom.ELEMENT_NODE=1;xtdom.ATTRIBUTE_NODE=2;xtdom.TEXT_NODE=3;xtdom.CDATA_SECTION_NODE=4;xtdom.COMMENT_NODE=8
if((typeof NodeFilter=="undefined")||!NodeFilter){xtdom.NodeFilter={SHOW_ELEMENT:1,FILTER_ACCEPT:1,FILTER_SKIP:3}}else{xtdom.NodeFilter={SHOW_ELEMENT:NodeFilter.SHOW_ELEMENT,FILTER_ACCEPT:NodeFilter.FILTER_ACCEPT,FILTER_SKIP:NodeFilter.FILTER_SKIP}}
if(!xtiger.cross.UA.IE){xtdom.isXT=function isXT(node){var ns=node.namespaceURI;return(ns==xtiger.parser.nsXTiger)||(ns==xtiger.parser.nsXTiger_deprecated)||(ns==xtiger.parser.nsXTigerExt);}
xtdom.isUseXT=function isUseX(aNode){return(aNode.nodeName=='use'||aNode.nodeName=='xt:use');}
xtdom.isBagXT=function(aNode){return(aNode.nodeName=='bag'||aNode.nodeName=='xt:bag');}
xtdom.getElementsByTagNameXT=function(container,name){var res=container.getElementsByTagName(name);if(0==res.length){res=container.getElementsByTagName('xt:'+name);}
return res;}
xtdom.getLocalName=function(node){return node.localName;}
xtdom.getTextContent=function(aNode){if(aNode.textContent)
return aNode.textContent;else if(aNode.text)
return aNode.text;else
return'';}
xtdom.createElement=function(doc,tagName){return doc.createElementNS("http://www.w3.org/1999/xhtml",tagName);};xtdom.createElementNS=function(doc,tagName,ns){return doc.createElementNS(ns,tagName);};xtdom.importNode=function(doc,node,deep){return doc.importNode(node,deep);}
xtdom.cloneNode=function(doc,node,deep){return node.cloneNode(deep);}
xtdom.setAttribute=function(node,name,value){node.setAttribute(name,value);}
xtdom.getStyleAttribute=function(aNode){return aNode.getAttribute('style');}
xtdom.getEventTarget=function(ev){return ev.target;}
xtdom.addEventListener=function(node,type,listener,useCapture){node.addEventListener(type,listener,useCapture);}
xtdom.removeEventListener=function(node,type,listener,useCapture){node.removeEventListener(type,listener,useCapture);}
xtdom.removeAllEvents=function(node){alert('removeAllEvents should not be called on this browser')}
xtdom.preventDefault=function(aEvent){aEvent.preventDefault();}
xtdom.stopPropagation=function(aEvent){aEvent.stopPropagation();}}
if(xtiger.cross.UA.IE){xtdom.hasAttribute=function(node,name){return node.getAttribute(name)!=null;}
xtdom.isXT=function(node){return xtiger.parser.isXTigerName.test(node.nodeName);}
xtdom.isUseXT=function(aNode){return(aNode.nodeName=='use'||aNode.nodeName=='xt:use');}
xtdom.isBagXT=function(aNode){return(aNode.nodeName=='bag'||aNode.nodeName=='xt:bag');}
xtdom.getElementsByTagNameXT=function(container,name){var res=container.getElementsByTagName(name);if(0==res.length){res=container.getElementsByTagName('xt:'+name);}
return res;}
xtdom.getLocalName=function(node){return node.nodeName;}
xtdom.getTextContent=function(aNode){if(aNode.innerText)
return aNode.innerText;else if(aNode.text)
return aNode.text;else
return'';}
xtdom.createElement=function(doc,tagName){return doc.createElement(tagName);}
xtdom.createElementNS=function(doc,tagName,ns){if(ns==xtiger.parser.nsXTiger){return doc.createElement('xt:'+tagName);}else{return doc.createElement(ns+':'+tagName);}}
xtdom.importNode=function(doc,node,deep){switch(node.nodeType){case xtdom.ELEMENT_NODE:var newNode=xtdom.createElement(doc,node.nodeName);if(node.attributes&&node.attributes.length>0)
for(var i=0;i<node.attributes.length;i++)
xtdom.setAttribute(newNode,node.attributes[i].name,node.attributes[i].value);if(deep&&node.childNodes&&node.childNodes.length>0)
for(var i=0;i<node.childNodes.length;i++)
newNode.appendChild(xtdom.importNode(doc,node.childNodes[i],deep));return newNode;break;case xtdom.TEXT_NODE:case xtdom.CDATA_SECTION_NODE:case xtdom.COMMENT_NODE:return xtdom.createTextNode(doc,node.nodeValue);break;}}
xtdom.cloneNode=function(doc,node,deep){var clone=node.cloneNode(deep);xtdom.removeAllEvents(clone);return clone;}
xtdom.setAttribute=function(node,name,value){if(name=='class'){node.className=value;}else{node.setAttribute(name,value);}}
xtdom.getStyleAttribute=function(aNode){if(aNode.style)
return aNode.style.cssText;else if(aNode.attributes[0]&&aNode.attributes[0].nodeName=='style'){return aNode.attributes[0].nodeValue;}}
xtdom.getEventTarget=function(ev){return(ev&&ev.srcElement)?ev.srcElement:window.event.srcElement;}
xtdom.addEventListener=function(node,type,listener,useCapture){node.attachEvent('on'+type,listener);if(!node.events){node.events=new Array();}
node.events.push([type,listener]);}
xtdom.removeEventListener=function(node,type,listener,useCapture){node.detachEvent('on'+type,listener);}
xtdom.removeAllEvents=function(node){if(node.events){for(var i=0;i<node.events.length;i++){xtdom.removeEventListener(node,node.events[i][0],node.events[i][1],true);}
node.events=new Array();}}
xtdom.preventDefault=function(aEvent){aEvent.returnValue=false;}
xtdom.stopPropagation=function(aEvent){aEvent.cancelBubble=true;}}
xtiger.util.filterable=function(name,that){if(!that){xtiger.cross.log('error','filter "'+name+'" is undefined');return that;}
var _filtersRegistry={};var _pluginName=name;that.registerFilter=function registerFilter(aKey,aFilter){if(!typeof(aFilter)=="object")
return;if(_filtersRegistry[aKey])
xtiger.cross.log('warning','"'+_pluginName+'" plugin: filter "'+aKey+'" is already registred. Overwriting it.');_filtersRegistry[aKey]=aFilter;};that.registerDelegate=that.registerFilter;that.applyFilters=function applyFilters(aModel,aFiltersParam){var _baseobject={};var _filtersnames=aFiltersParam.split(' ');var _filtered=aModel;for(var _i=0;_i<_filtersnames.length;_i++){var _unfiltered=_filtered;var _filter=_filtersRegistry[_filtersnames[_i]];if(!_filter){xtiger.cross.log('warning','"'+_pluginName+'" plugin: missing filter "'+_filtersnames[_i]+'"');continue;}
var _Filtered=function(){};_Filtered.prototype=_unfiltered;_filtered=new _Filtered();if(_filter){var _remaps=_filter["->"];if(_remaps){for(var _p in _remaps){if(_baseobject[_p]===undefined||_baseobject[_p]!=_remaps[_p]){if(_remaps[_p]==null){_filtered[_p]=null;}
else{_filtered[_remaps[_p]]=_unfiltered[_p]||function(){};}}}}
xtiger.util.mixin(_filtered,_filter);}}
return _filtered;};return that;};xtiger.parser.NATIVE=0;xtiger.parser.CONSTRUCTED=1;xtiger.parser.nsXTiger="http://ns.inria.org/xtiger";xtiger.parser.nsXTigerExt="http://ns.media.epfl.ch/xtiger-extension";xtiger.parser.nsXTiger_deprecated="http://wam.inrialpes.fr/xtiger";xtiger.parser.nsXHTML="http://www.w3.org/1999/xhtml"
xtiger.parser.isXTiger=/<[^>]*[(component)(use)(repeat)(service)]/;xtiger.parser.isXTigerName=/[(component)(use)(repeat)(service)]/;xtiger.parser.Component=function(nature,tree){this.nature=nature;this.tree=tree;this.str=null;}
xtiger.parser.Component.prototype={isNative:function(){return(xtiger.parser.NATIVE==this.nature);},hasBeenExpanded:function(){return(xtiger.parser.NATIVE==this.nature)||(this.str!=null);},getSource:function(){if(!this.str){this.str=this.tree.innerHTML;}
return this.str;},getTree:function(){return this.tree;},getClone:function(doc){var res=xtdom.cloneNode(doc,this.tree,true);return res;},importStructTo:function(targetDoc){var copy=xtdom.importNode(targetDoc,this.tree,true);this.tree=copy;}}
xtiger.parser.Iterator=function(doc,transformer){this.transformer=transformer;this.unionList=new Object();this.componentLib=new Object();this.transformer.coupleWithIterator(this);this.acquireComponentStructs(doc);this.acquireUnion(doc);this.acquireHeadLabel(doc);}
xtiger.parser.Iterator.prototype={hasType:function(name){return this.componentLib[name]?true:false;},defineType:function(name,definition){this.componentLib[name]=definition;},defineUnion:function(name,definition){this.unionList[name]=definition;},getComponentForType:function(name){return this.componentLib[name];},acquireHeadLabel:function(aDocument){var l;var head=xtdom.getElementsByTagNameXT(aDocument,"head");if(head&&(head.length>0)){l=head[0].getAttributeNode('label');if(!l){head=xtdom.getElementsByTagNameXT(head[0],"head");if(head&&(head.length>0)){l=head[0].getAttributeNode('label');}}}
this.headLabel=l?l.value:undefined;},acquireComponentStructs:function(aDocument){var structs=xtdom.getElementsByTagNameXT(aDocument,"component");var mapTypes=new Array();for(var inc=0;inc<structs.length;inc++){var name=structs[inc].getAttribute('name');if(name){mapTypes.push(name);this.componentLib[name]=new xtiger.parser.Component(xtiger.parser.CONSTRUCTED,structs[inc]);}}
this.unionList['anyComponent']=mapTypes;},acquireUnion:function(template){var unions=xtdom.getElementsByTagNameXT(template,"union");for(var inc=0;inc<unions.length;inc++){var tmp;var name=unions[inc].getAttributeNode('name').value;tmp=unions[inc].getAttributeNode('include').value.split(" ");var typeIn=this.flattenUnionTypes(tmp);var typeString=" "+typeIn.join(" ")+" ";tmp=unions[inc].getAttributeNode('exclude');if(tmp){tmp=typeDel.value.split(" ");var typeDel=this.flattenUnionTypes(tmp);for(var inc2=0;inc2<typeDel.length;inc2++){typeString=typeString.replace(new RegExp(" "+typeDel[inc2]+" ")," ");}}
typeString=typeString.substring(1,typeString.length-1);this.unionList[name]=typeString.split(" ");}
this.unionList["any"]=this.unionList["anySimple"].concat(this.unionList["anyElement"],this.unionList["anyComponent"]);},flattenUnionTypes:function(types){var output=[];for(var inc=0;inc<types.length;inc++){if(this.unionList[types[inc]]!=null){var thisUnion=this.unionList[types[inc]];for(var i=0;i<thisUnion.length;i++){output.push(thisUnion[i]);}}else{output.push(types[inc]);}}
return output;},importComponentStructs:function(targetDoc){xtiger.cross.log('info','imports template component structures to target document');for(var k in this.componentLib){this.componentLib[k].importStructTo(targetDoc);}},transform:function(aNode,doc){this.curDoc=doc;this.transformer.prepareForIteration(this,doc,this.headLabel);this.transformIter(aNode);this.transformer.finishTransformation(aNode);},transformIter:function(aNode){if(aNode.nodeType==xtdom.ELEMENT_NODE){var type=xtdom.getNodeTypeXT(aNode);if(xtiger.COMPONENT==type){this.changeComponent(aNode);}else{this.transformer.saveContext(aNode);switch(type){case xtiger.USE:this.changeUse(aNode);break;case xtiger.REPEAT:this.changeRepeat(aNode);break;case xtiger.ATTRIBUTE:this.changeAttribute(aNode);break;case xtiger.BAG:this.changeBag(aNode);break;case xtiger.SERVICE:this.changeService(aNode);break;default:this.continueWithChildOf(aNode);}
this.transformer.restoreContext(aNode);}}},continueWithChildOf:function(aNode){var process=new Array();for(var i=0;i<aNode.childNodes.length;i++){if(xtdom.containsXT(aNode.childNodes[i])){process.push(aNode.childNodes[i]);}}
this.transformItems(process);},transformItems:function(nodes){if(nodes.length==0)return;var cur;if(nodes[0]=='OPAQUE'){nodes.shift();var saved=this.transformer.popContext();while(cur=nodes.shift()){this.transformer.saveContext(cur,true);this.transformIter(this.transformer.getNodeFromOpaqueContext(cur));this.transformer.restoreContext(cur,true);}
this.transformer.pushContext(saved);}else{while(cur=nodes.shift()){this.transformIter(cur);}}},changeComponent:function(componentNode){var accu=[];var container=xtdom.createElement(this.curDoc,'div');this.transformer.genComponentBody(componentNode,container);this.transformer.genComponentContent(componentNode,container,accu);this.transformItems(accu);this.transformer.finishComponentGeneration(componentNode,container);xtdom.replaceNodeByChildOf(componentNode,container);},changeRepeat:function(repeatNode){var accu=[];var container=xtdom.createElement(this.curDoc,'div');this.transformer.genRepeatBody(repeatNode,container,accu);this.transformer.genRepeatContent(repeatNode,container,accu);this.transformItems(accu);this.transformer.finishRepeatGeneration(repeatNode,container);xtdom.replaceNodeByChildOf(repeatNode,container);},changeUse:function(xtSrcNode){var accu=[];var container=xtdom.createElement(this.curDoc,'div');var kind=xtSrcNode.getAttribute('option')||'use';var types=xtSrcNode.getAttribute('types').split(" ");types=this.flattenUnionTypes(types);this.transformer.genIteratedTypeBody(kind,xtSrcNode,container,types);this.transformer.genIteratedTypeContent(kind,xtSrcNode,container,accu,types);this.transformItems(accu);this.transformer.finishIteratedTypeGeneration(kind,xtSrcNode,container,types);xtdom.replaceNodeByChildOf(xtSrcNode,container);},changeAttribute:function(xtSrcNode){var accu=null;var container=xtdom.createElement(this.curDoc,'div');var kind='attribute';var types=[xtSrcNode.getAttribute('types')||xtSrcNode.getAttribute('type')];this.transformer.genIteratedTypeBody(kind,xtSrcNode,container,types);this.transformer.genIteratedTypeContent(kind,xtSrcNode,container,accu,types);this.transformer.finishIteratedTypeGeneration(kind,xtSrcNode,container,types);xtdom.replaceNodeByChildOf(xtSrcNode,container);},changeBag:function(bagNode){var span=xtdom.createElement(this.curDoc,'span');xtdom.addClassName(span,'xtt-gen-error');var t=xtdom.createTextNode(this.curDoc,'! unsupported Bag element !');span.appendChild(t);bagNode.parentNode.insertBefore(span,bagNode,true);bagNode.parentNode.removeChild(bagNode);},changeService:function(xtSrcNode){var sFactory=xtiger.factory('service');if(sFactory){var container=xtdom.createElement(this.curDoc,'div');var handle=sFactory.createModel(container,xtSrcNode,this.curDoc);handle.xttService=sFactory.createServiceFromTree(handle,xtSrcNode,this.curDoc);xtdom.replaceNodeByChildOf(xtSrcNode,container);}else{xtiger.cross.log('warning','Missing "service" factory - services will not be generated !');}}}
xtiger.util.Form=function(baseIconsUrl){this.baseUrl=baseIconsUrl;this.doTab=false;this.loader=this.serializer=null;}
xtiger.util.Form.prototype={_report:function(status,str,logger){this.status=status;this.msg=str;if(logger&&(0==this.status)){logger.logError(str);}},setLoader:function(l){this.loader=l;},setSerializer:function(s){this.serializer=s;},enableTabGroupNavigation:function(){this.doTab=true;},setTemplateSource:function(xtDoc){this.srcDoc=xtDoc;this.srcForm=null;if(xtDoc){var bodies=xtDoc.getElementsByTagName('body');if(bodies&&(bodies.length>0)){this.srcForm=bodies[0];}else{try{xtDoc.setProperty("SelectionNamespaces","xmlns:xhtml='http://www.w3.org/1999/xhtml'");this.srcForm=xtDoc.selectSingleNode('//xhtml:body');}catch(e){}}
if(!this.srcForm){alert('Could not get <body> element from the template to transform !');}
this.curDoc=xtDoc;this.targetContainerId=false;}else{alert('The document containing the template is null or undefined !');}},setTargetDocument:function(aDoc,anId,doReplace){this.curDoc=aDoc;this.targetContainerId=anId;this.doEmptyTarget=doReplace;},transform:function(logger){if(!this.srcForm){this._report(0,'no template to transform',logger);return false;}
this.editor=new xtiger.editor.Generator(this.baseUrl);this.parser=new xtiger.parser.Iterator(this.srcDoc,this.editor);if(this.targetContainerId){var n=this.curDoc.getElementById(this.targetContainerId);if(n){if(this.doEmptyTarget){xtdom.removeChildrenOf(n);}
xtdom.importChildOfInto(this.curDoc,this.srcForm,n);this.root=n;}else{this._report(0,'transformation aborted because target container "'+this.targetContainerId+'" not found in target document',logger);return false;}
this.parser.importComponentStructs(this.curDoc);}else{this.root=this.srcForm;}
var kbd=xtiger.session(this.curDoc).load('keyboard');if(!kbd){kbd=new xtiger.editor.Keyboard();xtiger.session(this.curDoc).save('keyboard',kbd);if(this.doTab){var tab=new xtiger.editor.TabGroupManager(this.root);kbd.setTabGroupManager(tab);xtiger.session(this.curDoc).save('tabgroupmgr',tab);}}
xtiger.session(this.curDoc).save('form',this);this.parser.transform(this.root,this.curDoc);this._report(1,'document transformed',logger);return(this.status==1);},getEditor:function(){return this.editor;},getRoot:function(){return this.root;},injectStyleSheet:function(url,logger){var head=this.curDoc?this.curDoc.getElementsByTagName('head')[0]:null;if(head){var link=document.createElement('link');link.setAttribute('rel','stylesheet');link.setAttribute('type','text/css');link.setAttribute('href',url);head.appendChild(link);this._report(1,'stylesheet injected',logger);}else{this._report(0,"cannot inject editor's style sheet because target document has no head section",logger);}
return(this.status==1);},loadData:function(dataSrc,logger){if(dataSrc.hasData()){this.editor.loadData(this.root,dataSrc,this.loader);this._report(1,'data loaded',logger);}else{this._report(0,'data source empty',logger);}
return(this.status==1);},loadDataFromString:function(str,logger){var dataSource=new xtiger.util.DOMDataSource();if(dataSource.initFromString(str)){this.loadData(dataSource,logger);}else{this._report(0,'failed to parse string data source',logger);}
return(this.status==1);},loadDataFromUrl:function(url,logger){var doc,source;var res=false;doc=xtiger.cross.loadDocument(url,logger);if(doc){res=this.loadData(new xtiger.util.DOMDataSource(doc),logger);}
return res;},serializeData:function(accumulator){this.editor.serializeData(this.root,accumulator,this.serializer);},loadDataFromFile:function(url,xhr,logger){try{xhr.open("GET",url,false);xhr.send(null);if((xhr.status==200)||(xhr.status==0)){if(xhr.responseXML){this.loadData(new xtiger.util.DOMDataSource(xhr.responseXML),logger);}else{var res=xhr.responseText;res=res.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/,"");xtiger.cross.log('warning','attempt to use string parser on '+url+' instead of responseXML');if(!dataSource.initFromString(res)){this._report(0,'failed to create data source for data from file '+url+'. Most probably no documentElement',logger);}}}else{this._report(0,'failed to load XML data from file '+url+". XHR status : "+xhr.status,logger);}}catch(e){this._report(0,'failed to open XML data file '+url+". Exception : "+e.name+'/'+e.message,logger);}
return(this.status==1);},postDataToUrl:function(url,xhr,logger){var log=new xtiger.util.DOMLogger();var data=this.editor.serializeData(this.root,log,this.serializer);log.close();try{xhr.open("POST",url,false);xhr.setRequestHeader("Content-Type","application/xml; charset=UTF-8");xhr.send(log.dump('*'));if(xhr.readyState==4){if((xhr.status==200)||(xhr.status==201)||(xhr.status==0)){this._report(1,xhr.responseText,logger);}else{this._report(0,'can\'t post data to "'+url+'". Error : '+xhr.status,logger);}}else{this._report(0,'can\'t post data to "'+url+'". Error readyState is '+xhr.readyState,logger);}}catch(e){xhr.abort();this._report(0,'can\'t post data to "'+url+'". Exception : '+e.name+'/'+e.message,logger);}
return(this.status==1);},saveDataToFile:function(filename,logger){if(xtiger.cross.UA.gecko){try{netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");}catch(e){this._report(0,'Permission to save data to file "'+filename+'" was denied. Exception : '+e.name+'/'+e.message,logger);return false;}
try{var log=new xtiger.util.DOMLogger();var data=this.editor.serializeData(this.root,log,this.serializer);log.close();var file=Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);file.initWithPath(filename);if(file.exists()==false){file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE,420);}
var outputStream=Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);outputStream.init(file,0x04|0x08|0x20,420,0);var uc=Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);uc.charset="UTF-8";var data_stream=uc.ConvertFromUnicode(log.dump('*'));var result=outputStream.write(data_stream,data_stream.length);outputStream.close();this._report(1,'Data saved to "'+filename+'"',logger);}catch(e){this._report(0,'Cannot save data to file "'+filename+'". Exception : '+e.name+'/'+e.message,logger);}}else{this.postDataToUrl(filename,xtiger.cross.getXHRObject());}
return(this.status==1);}}
xtiger.editor.Plugin=function(){}
xtiger.editor.Plugin.prototype={pluginEditors:{},getEditorFor:function(xtigerSrcNode,typesArray){var factory;if(typesArray.length==1){var wrapper=xtigerSrcNode.getAttribute('wrapper');var editor=(wrapper)?'string':typesArray[0];factory=this.pluginEditors[editor];}
return factory;},hasEditorFor:function(xtigerSrcNode,typesStr){var res;if(this.pluginEditors[typesStr]){res=true;}else{var wrapper=xtigerSrcNode.getAttribute('wrapper');var editor=(wrapper)?'string':typesStr;res=(this.pluginEditors[editor]!=undefined);}
return res;}}
xtiger.editor.Generator=function(baseUrl){if(baseUrl){xtiger.resources.setBase(baseUrl);}
this.plugins=new xtiger.editor.Plugin();}
xtiger.editor.LABEL_MARK=0;xtiger.editor.REPEAT_MARK=1;xtiger.editor.CHOICE_MARK=2;xtiger.editor.Generator.prototype={markerNames:['xttOpenLabel','xttCloseLabel','startRepeatedItem','endRepeatedItem','beginChoiceItem','endChoiceItem'],isBoundarySafe:function(node){if(!node){alert('Empty node in transformation, the template may contain XHTML errors, please correct it !');return false;}
if(xtiger.cross.UA.IE&&(node.nodeType!=xtdom.ELEMENT_NODE)){return false;}
for(var i=0;i<this.markerNames.length;i++){if(node[this.markerNames[i]]){return false;}}
if((node.nodeType==xtdom.ELEMENT_NODE)&&(node.nodeName.search('menu-marker')!=-1)){return false;}
return true;},verifyBoundaries:function(container,category){var begin;if(!this.isBoundarySafe(container.firstChild)){begin=xtdom.createElement(this.curDoc,'span');xtdom.addClassName(begin,'xtt-boundary');}
if(!this.isBoundarySafe(container.lastChild)){var end=xtdom.createElement(this.curDoc,'span');xtdom.addClassName(end,'xtt-boundary');container.appendChild(end);}
if(begin){container.insertBefore(begin,container.firstChild);}},getNodeFromOpaqueContext:function(item){xtiger.cross.log('warning','unexpected call to "getNodeFromOpaqueContext" in "generator.js"');return item;},saveContext:function(xtSrcNode,isOpaque){if(xtdom.isUseXT(xtSrcNode)||xtdom.isBagXT(xtSrcNode)){this.context.push(xtSrcNode);}},restoreContext:function(xtSrcNode){if(xtdom.isUseXT(xtSrcNode)||xtdom.isBagXT(xtSrcNode)){this.context.pop();}},pushContext:function(value){this.context.push(value);},popContext:function(){return this.context.pop();},savePendingEditor:function(ed,menu){var top=this.popContext();this.pushContext([top,[ed,menu]]);},getPendingEditor:function(){if(this.context.length>0){var top=this.context[this.context.length-1];if(top instanceof Array){return top[1];}}
return false;},peekTopContext:function(){var top=this.context[this.context.length-1];return(top instanceof Array?top[0]:top);},coupleWithIterator:function(iterator){this.iterator=iterator;var anySimple=new Array("string","number","boolean");iterator.defineUnion("anySimple",anySimple);},prepareForIteration:function(iterator,doc,label){this.context=[];this.curDoc=doc;this.headLabel=label;if(!doc){alert('You must specify a document to prepareForIteration !');}},genComponentBody:function(componentNode,container){},genComponentContent:function(componentNode,container,accu){xtdom.moveChildOfInto(componentNode,container,accu);},finishComponentGeneration:function(xtigerSrcNode,container){var context=this.getPendingEditor();if(context){var editor=context[0];this.verifyBoundaries(container,xtiger.editor.CHOICE_MARK);var name=xtigerSrcNode.getAttribute('name');editor.addChoiceItem(name,container.firstChild,container.lastChild);var i18n=xtigerSrcNode.getAttribute('i18n');if(i18n){var menu=context[1];var options=menu.getElementsByTagName('option');for(var i=0;i<options.length;i++){var text=options.item(i).firstChild;if(text.data==name){text.data=i18n;break;}}}}},genRepeatBody:function(repeatNode,container){},genRepeatContent:function(repeatNode,container,accu){xtdom.moveChildOfInto(repeatNode,container,accu);},finishRepeatGeneration:function(repeatNode,container){this.verifyBoundaries(container,xtiger.editor.REPEAT_MARK);var rc=new xtiger.editor.Repeat();rc.initFromTree(container,repeatNode,this.curDoc);},genIteratedTypeBody:function(kind,xtigerSrcNode,container,types){if(types.length>1){var menu;var s=menu=xtdom.createElement(this.curDoc,'select');for(var i=0;i<types.length;i++){var o=xtdom.createElement(this.curDoc,'option');var t=xtdom.createTextNode(this.curDoc,types[i]);o.appendChild(t);s.appendChild(o);}
var cname;var marker=xtigerSrcNode.getAttribute('param');if(marker){var i=marker.indexOf('=');if(i!=-1){cname=marker.substr(i+1,marker.length-i-1);}}
if(cname){var span=xtdom.createElement(this.curDoc,'span');xtdom.addClassName(span,cname);var mm=xtdom.createElementNS(this.curDoc,'menu-marker',xtiger.parser.nsXTiger);span.appendChild(mm);var br=xtdom.createElement(this.curDoc,'br');span.appendChild(br);span.appendChild(menu);menu=span;}
container.appendChild(menu);var c=new xtiger.editor.Choice();c.initFromTree(s,types,this.curDoc);this.savePendingEditor(c,s);xtdom.addEventListener(s,'change',function(ev){c.handleSelect(ev);},false);xtiger.cross.log('plant','Created a Choice editor for types '+'/'+types+'/');}},genIteratedTypeContent:function(kind,xtigerSrcNode,container,accu,types){var factory;if(factory=this.plugins.getEditorFor(xtigerSrcNode,types)){var editorHandle=factory.createModel(container,xtigerSrcNode,this.curDoc);var srcUseOrBag=(kind=='attribute')?xtigerSrcNode:this.peekTopContext();editorHandle.xttPrimitiveEditor=factory.createEditorFromTree(editorHandle,srcUseOrBag,this.curDoc);}else{for(var i=0;i<types.length;i++){var curComponentForType=this.iterator.getComponentForType(types[i]);if(curComponentForType){var generated=curComponentForType.getClone(this.curDoc);container.appendChild(generated);accu.push(generated);}else{var span=xtdom.createElement(this.curDoc,'span');xtdom.addClassName(span,'xtt-gen-error');var txt=xtdom.createTextNode(this.curDoc,'ERROR: "'+types[i]+'" is undeclared or is terminal and part of a choice');span.appendChild(txt);container.appendChild(span);}}}},finishIteratedTypeGeneration:function(kind,xtigerSrcNode,container,types){var label=xtdom.getTagNameXT(xtigerSrcNode);if(!label)return;if(kind=='attribute'){label='@'+label;}
if(!container.firstChild){xtiger.cross.log('warning','XTiger component (label="'+label+'") definition is empty');return;}
this.verifyBoundaries(container,xtiger.editor.USE_MARK);xtiger.cross.log('plant','Planting use Start & End labels for '+label);if(container.firstChild.xttOpenLabel){xtiger.cross.log('warning','use "'+label+'" and use "'+container.firstChild.xttOpenLabel+'" with same START !');}
var flow=xtigerSrcNode.getAttribute('flow');if(flow){label='!'+flow+'!'+label;}
container.firstChild.xttOpenLabel=label;if(container.lastChild.xttCloseLabel){xtiger.cross.log('warning','use "'+label+'" and use "'+container.lastChild.xttCloseLabel+'" with same END !');}
container.lastChild.xttCloseLabel=label;},finishTransformation:function(n){var treeWalker=xtiger.cross.makeTreeWalker(n,xtdom.NodeFilter.SHOW_ELEMENT,function(node){return(node.markChoiceEditor)?xtdom.NodeFilter.FILTER_ACCEPT:xtdom.NodeFilter.FILTER_SKIP;});while(treeWalker.nextNode()){if(treeWalker.currentNode.markChoiceEditor){treeWalker.currentNode.markChoiceEditor.initializeSelectedItem(0);}}},loadData:function(root,dataSrc,loader){var l=loader||this.defaultLoader;if(l){l.loadData(root,dataSrc)}else{alert("Default XML loader missing !")}},serializeData:function(root,logger,serializer){var s=serializer?serializer:this.defaultSerializer;if(s){s.serializeData(root,logger,this.headLabel);}else{alert("Default XML serializer missing !")}}}
xtiger.editor.Repeat=function(){this.items=[];this.curDoc=null;this.originPosition=-1;}
xtiger.editor.Repeat.autoSelectRepeatIter=function(startFrom){var r;var cur=startFrom;var startCount=0;var endCount=0;while(cur){if(cur.startRepeatedItem){startCount++;}
if((cur!=startFrom)&&cur.endRepeatedItem){endCount++;}
if(startCount>endCount){r=cur.startRepeatedItem;if((0==r.min)&&(0==r.total)){r.unsetOption();}
cur=r.getFirstNodeForSlice(0);startCount=endCount=0;}
cur=cur.previousSibling;}
if(startFrom.parentNode){xtiger.editor.Repeat.autoSelectRepeatIter(startFrom.parentNode);}}
xtiger.editor.Repeat.prototype={trash:[],hasLabel:function(){return(this.label!='repeat');},getRepeatableLabel:function(){return this.pseudoLabel;},dump:function(){return this.label;},getSize:function(){return this.total;},getOriginPosition:function(){return this.originPosition;},getLastNodeForSlice:function(index){var pos=(index<this.items.length)?index:this.items.length-1;return this.items[pos][1];},getFirstNodeForSlice:function(index){var pos=(index<this.items.length)?index:this.items.length-1;return this.items[pos][0];},makeSeed:function(srcRepeater,dict){if(this==srcRepeater){xtiger.cross.log('clone-trace','*repeater* do not replicate top/master repeater',this.seed[3]);}else{if(this.seed){if(this.seed[0]==-2){var m=dict[this.seed[3]];if(!m){var id=xtdom.genId();xtiger.cross.log('clone-trace','*repeater* remaps a non top/master repeater',id);m=[-1,this.seed[1],this.seed[2],id,this.min,this.max,this.pseudoLabel];dict[this.seed[3]]=m;}
return m;}else{xtiger.cross.log('debug','*repeater* [should not happen] seed '+this.seed[3]+' already mapped as '+this.seed[0]);}}else{var id=xtdom.genId();xtiger.cross.log('debug','*repeater*  [should not happen] making a entirely repeater seed',id);this.seed=[-1,srcRepeater.label,srcRepeater.model,id,this.min,this.max,this.pseudoLabel];}}
return this.seed;},initFromSeed:function(repeaterSeed,doc){this.curDoc=doc;this.label=repeaterSeed[1];this.model=repeaterSeed[2];this.min=repeaterSeed[4];this.max=repeaterSeed[5];this.pseudoLabel=repeaterSeed[6];this.total=(this.min>0)?1:0;this.items=[[null,null,null,null]];},setStartItem:function(node){this.items[0][0]=node;},setEndItem:function(node){this.items[0][1]=node;},setMarkItem:function(node){if(this.items[0][2]){this.items[0][3]=node;}else{this.items[0][2]=node;}
var _this=this;xtdom.addEventListener(node,'click',function(ev){_this.handleRepeat(ev)},true);xtiger.cross.log('iter-trace','setMarkItem for repeater '+this.dump()+' on node '+node.tagName);},configureMenuForSlice:function(index){if(index>=this.items.length){xtiger.cross.log('error','Wrong menu configuration in repeater '+this.dump());return;}
var leftImg=this.items[index][2];var rightImg=this.items[index][3];var srcLeft=xtiger.bundles.repeat.checkedIconURL;if(0==this.min){if(0==this.total){srcLeft=xtiger.bundles.repeat.uncheckedIconURL;}else if(1==this.total){srcLeft=xtiger.bundles.repeat.checkedIconURL;}else{srcLeft=xtiger.bundles.repeat.minusIconURL;}}else if(this.total==this.min){srcLeft=xtiger.bundles.repeat.plusIconURL;}else{srcLeft=xtiger.bundles.repeat.minusIconURL;}
xtdom.setAttribute(leftImg,'src',srcLeft);xtdom.setAttribute(rightImg,'src',xtiger.bundles.repeat.plusIconURL);var rightVisible=false;if(0==this.min){if(((this.max>1)||(-1==this.max))&&(this.total>0)){rightVisible=true;}}else if((this.total>1)&&((this.max>1)||(-1==this.max))){rightVisible=true;}
if(rightVisible){xtdom.removeClassName(rightImg,'xtt-off');}else{xtdom.addClassName(rightImg,'xtt-off');}},initFromTree:function(container,repeatNode,doc){this.curDoc=doc;this.label=repeatNode.getAttribute('label')||'repeat';this.pseudoLabel=repeatNode.getAttribute('pseudoLabel')||'repeat';var val=repeatNode.getAttribute('minOccurs')||0;this.min=isNaN(val)?1:parseInt(val);val=repeatNode.getAttribute('maxOccurs')||-1;this.max=isNaN(val)?-1:parseInt(val);this.total=(this.min>0)?1:0;xtiger.cross.log('plant','Create Repeat Editor '+this.min+'/'+this.max+'/'+this.label);var rightImg=xtdom.createElement(this.curDoc,'img');var width='16';var insertPoint;if(insertPoint=xtdom.getMenuMarkerXT(container)){insertPoint.parentNode.replaceChild(rightImg,insertPoint);width=insertPoint.getAttribute('size')||width;}else{var counter=0;var cur=container.firstChild;while(cur){if(cur.nodeType==xtdom.ELEMENT_NODE){var curclass=cur.className;if(curclass&&(-1!=curclass.indexOf('xtt-auto-wrapped'))){if(counter==0){insertPoint=cur;}
counter++;}}
cur=cur.nextSibling;}
if(counter==1){insertPoint.appendChild(rightImg);}else{container.appendChild(rightImg);}}
xtdom.setAttribute(rightImg,'width',width);xtdom.addClassName(rightImg,'xtt-repeat-right');var leftImg=xtdom.createElement(this.curDoc,'img');xtdom.setAttribute(leftImg,'width',width);xtdom.addClassName(leftImg,'xtt-repeat-left');rightImg.parentNode.insertBefore(leftImg,rightImg,false);start=container.firstChild;end=container.lastChild;if(start.startRepeatedItem){xtiger.cross.log('warning','Repeat "'+this.label+'" and repeat "'+start.startRepeatedItem.label+'" with same START boundaries !');}
start.startRepeatedItem=this;if(end.endRepeatedItem){xtiger.cross.log('warning','Repeat "'+this.label+'" and repeat "'+end.endRepeatedItem.label+'" with same END boundaries !');}
end.endRepeatedItem=this;leftImg.markRepeatedEditor=this;rightImg.markRepeatedEditor=this;if(start.xttOpenLabel){xtiger.cross.log('warning','Repeat "'+this.label+'" and use with same START boundaries !');}
if(end.xttCloseLabel){xtiger.cross.log('warning','Repeat "'+this.label+'" and use with same END boundaries !');}
var _this=this;xtdom.addEventListener(leftImg,'click',function(ev){_this.handleRepeat(ev)},true);xtdom.addEventListener(rightImg,'click',function(ev){_this.handleRepeat(ev)},true);this.model=this.shallowClone(container);this.items.push([start,end,leftImg,rightImg]);this.configureMenuForSlice(0);if(0==this.min){this.unactivateSliceAt(0);}},shallowFinishCloning:function(clone,node,dict){if(node.xttOpenLabel)clone.xttOpenLabel=node.xttOpenLabel;if(node.xttCloseLabel)clone.xttCloseLabel=node.xttCloseLabel;if(node.markRepeatedEditor)clone.markRepeatedEditor=node.markRepeatedEditor.makeSeed(this,dict);if(node.startRepeatedItem)clone.startRepeatedItem=node.startRepeatedItem.makeSeed(this,dict);if(node.endRepeatedItem)clone.endRepeatedItem=node.endRepeatedItem.makeSeed(this,dict);if(node.markChoiceEditor)clone.markChoiceEditor=node.markChoiceEditor.makeSeed();if(node.beginChoiceItem)clone.beginChoiceItem=node.beginChoiceItem.makeSeed();if(node.endChoiceItem)clone.endChoiceItem=node.endChoiceItem.makeSeed();if(node.xttPrimitiveEditor)clone.xttPrimitiveEditor=node.xttPrimitiveEditor.makeSeed();if(node.xttService)clone.xttService=node.xttService.makeSeed();},shallowClone:function(node){var dict={};var clone=xtdom.cloneNode(this.curDoc,node,false);this.seed=[-2,this.label,clone,xtdom.genId(),this.min,this.max,this.pseudoLabel];this.shallowFinishCloning(clone,node,dict);for(var i=0;i<node.childNodes.length;i++){this.shallowCloneIter(clone,node.childNodes[i],dict);}
return clone;},shallowCloneIter:function(parent,node,dict){var clone=xtdom.cloneNode(this.curDoc,node,false);this.shallowFinishCloning(clone,node,dict);parent.appendChild(clone);for(var i=0;i<node.childNodes.length;i++){this.shallowCloneIter(clone,node.childNodes[i],dict);}},getChoiceEditorClone:function(dict,editorSeed){var m=dict[editorSeed];if(!m){var m=new xtiger.editor.Choice();m.initFromSeed(editorSeed,this.curDoc);dict[editorSeed]=m;}
return m;},getRepeatEditorClone:function(dict,editorSeed){var m=dict[editorSeed[3]];if(!m){var m=new xtiger.editor.Repeat();m.initFromSeed(editorSeed,this.curDoc);dict[editorSeed[3]]=m;xtiger.cross.log('stack-trace','cloning repeat editor',m.dump(),'('+editorSeed[3]+')');}
return m;},deepFinishCloning:function(clone,node,modelDict,masterRepeater,accu){if(node.xttOpenLabel)clone.xttOpenLabel=node.xttOpenLabel;if(node.xttCloseLabel)clone.xttCloseLabel=node.xttCloseLabel;if(node.startRepeatedItem){if(node.startRepeatedItem[0]==-1){var m=this.getRepeatEditorClone(modelDict[0],node.startRepeatedItem);m.setStartItem(clone);clone.startRepeatedItem=m;}else{clone.startRepeatedItem=this;accu[0]=clone;}}
if(node.endRepeatedItem){if(node.endRepeatedItem[0]==-1){var m=this.getRepeatEditorClone(modelDict[0],node.endRepeatedItem);m.setEndItem(clone);clone.endRepeatedItem=m;}else{clone.endRepeatedItem=this;accu[1]=clone;}}
if(node.markRepeatedEditor){if(node.markRepeatedEditor[0]==-1){var m=this.getRepeatEditorClone(modelDict[0],node.markRepeatedEditor);m.setMarkItem(clone);clone.markRepeatedEditor=m;}else{clone.markRepeatedEditor=this;var _this=this;xtdom.addEventListener(clone,'click',function(ev){_this.handleRepeat(ev)},true);if(accu[2]){accu[3]=clone;}else{accu[2]=clone;}}}
if(node.markChoiceEditor){var m=this.getChoiceEditorClone(modelDict[1],node.markChoiceEditor);m.setChoiceMenu(clone);clone.markChoiceEditor=m;}
if(node.beginChoiceItem){var m=this.getChoiceEditorClone(modelDict[1],node.beginChoiceItem);m.setBeginChoiceItem(clone);clone.beginChoiceItem=m;}
if(node.endChoiceItem){var m=this.getChoiceEditorClone(modelDict[1],node.endChoiceItem);m.setEndChoiceItem(clone);clone.endChoiceItem=m;}
if(node.xttPrimitiveEditor){var seed=node.xttPrimitiveEditor;var factory=seed[0];clone.xttPrimitiveEditor=factory.createEditorFromSeed(seed,clone,this.curDoc,this);}
if(node.xttService){var seed=node.xttService;var factory=seed[0];clone.xttService=factory.createServiceFromSeed(seed,clone,this.curDoc,this);}},deepClone:function(node,accu){var clone=xtdom.cloneNode(this.curDoc,node,false);var modelDict=[{},{}];this.deepFinishCloning(clone,node,modelDict,this,accu);for(var i=0;i<node.childNodes.length;i++){this.deepCloneIter(clone,node.childNodes[i],modelDict,this,accu);}
return clone;},deepCloneIter:function(parent,node,modelDict,masterRepeater,accu){if(node.xttPrimitiveEditor){var clone=xtdom.cloneNode(this.curDoc,node,true);parent.appendChild(clone);this.deepFinishCloning(clone,node,modelDict,masterRepeater,accu);return;}
var clone=xtdom.cloneNode(this.curDoc,node,false);parent.appendChild(clone);this.deepFinishCloning(clone,node,modelDict,masterRepeater,accu);for(var i=0;i<node.childNodes.length;i++){this.deepCloneIter(clone,node.childNodes[i],modelDict,masterRepeater,accu);}},getOneCopy:function(index,position){return this.deepClone(this.model,index);},reset:function(){var start=this.min+1;for(var i=start;i<this.total;i++){this.removeItemAtIndex(i,false);}
this.total=this.min;this.configureMenuForSlice(0);},plantSlice:function(index,position){if(this.items.length==1){xtdom.removeClassName(this.items[0][2],'xtt-off');}
this.items.splice(position+1,0,index);},sliceLoaded:function(){this.total++;if((0==this.min)&&(1==this.total)){this.activateSliceAt(0);}
if(((0==this.min)&&(2==this.total))||((this.min>0)&&(this.total==(this.min+1))))
{for(var i=0;i<=this.min;i++){this.configureMenuForSlice(i);}}
this.configureMenuForSlice(this.total-1);},appendSlice:function(){var lastIndex=this.items.length-1;var lastNode=this.getLastNodeForSlice(lastIndex);var index=[null,null,null,null];this.originPosition=-1;var copy=this.getOneCopy(index);xtdom.moveChildrenOfAfter(copy,lastNode);this.plantSlice(index,lastIndex);return lastIndex+1;},handleRepeat:function(ev){var appended=false;var target=xtdom.getEventTarget(ev);for(var i=0;i<this.items.length;i++){if(this.items[i][2]==target){if((0==this.min)&&(0==this.total)){this.unsetOption();appended=true;}else if((this.min>0)&&(1==this.total)){this.addItem(target,i,ev.shiftKey);appended=true;}else{if((0==this.min)&&(1==this.total)){this.setOption();}else{this.deleteItem(target,i,ev.shiftKey);}}
break;}else if(this.items[i][3]==target){this.addItem(target,i,ev.shiftKey);appended=true;break;}}
if(appended){xtiger.editor.Repeat.autoSelectRepeatIter(this.getFirstNodeForSlice(0));}},unsetOption:function(){this.total++;this.configureMenuForSlice(0);this.activateSliceAt(0);},activateNodeIter:function(node,curInnerRepeat){if((!curInnerRepeat)||(curInnerRepeat.total>=1)){xtdom.removeClassName(node,'xtt-repeat-unset');}},activateSliceAt:function(index){this.mapFuncToSliceAt(xtiger.editor.Repeat.prototype.activateNodeIter,index,false);},setOption:function(){this.total--;this.configureMenuForSlice(0);this.unactivateSliceAt(0);},unactivateNodeIter:function(node,curInnerRepat){xtdom.addClassName(node,'xtt-repeat-unset');},unactivateSliceAt:function(index){this.mapFuncToSliceAt(xtiger.editor.Repeat.prototype.unactivateNodeIter,index,true);},callPrimitiveEditors:function(top,action){var treeWalker=xtiger.cross.makeTreeWalker(top,xtdom.NodeFilter.SHOW_ELEMENT,function(n){if(n.xttPrimitiveEditor&&n.xttPrimitiveEditor.can(action)){return xtdom.NodeFilter.FILTER_ACCEPT}else{return xtdom.NodeFilter.FILTER_SKIP;}});while(treeWalker.nextNode()){treeWalker.currentNode.xttPrimitiveEditor.execute(action,this);}},addItem:function(mark,position,useTrash){var saved;var newIndex;var preceeding=this.items[position];if(useTrash){var i;for(i=0;i<this.trash.length;i++){if(this.trash[i][0]==this){saved=this.trash[i];break;}}}
this.originPosition=position;if(saved){newIndex=saved[2];var slice=saved[1];xtdom.moveNodesAfter(slice,preceeding[1]);this.trash.splice(i,1);var cur=newIndex[0];this.callPrimitiveEditors(cur,'paste');var end=newIndex[1];while(cur!=end){this.callPrimitiveEditors(cur,'paste');cur=cur.nextSibling;}}else{newIndex=[null,null,null,null];var n=this.getOneCopy(newIndex,position);xtdom.moveChildrenOfAfter(n,preceeding[1]);}
this.originPosition=-1;this.plantSlice(newIndex,position);this.total++;if(0==position){this.configureMenuForSlice(0);}
this.configureMenuForSlice(position+1);this.configureMenuForSlice(this.total-1);},deleteItem:function(mark,position,useTrash){this.removeItemAtIndex(position,useTrash);if(this.total<=1){this.configureMenuForSlice(0);}else{this.configureMenuForSlice(this.total-1);}},removeItemAtIndex:function(position,useTrash){this.originPosition=position;var index=this.items[position];var slice=useTrash?[]:null;if(index[0]==index[1]){if(useTrash){slice.push(index[0]);}
this.callPrimitiveEditors(index[0],'remove');index[0].parentNode.removeChild(index[0]);}else{var next=index[0].nextSibling;if(useTrash){slice.push(index[0]);}
this.callPrimitiveEditors(index[0],'remove');index[0].parentNode.removeChild(index[0]);while(next&&(next!=index[1])){var cur=next;next=next.nextSibling;if(useTrash){slice.push(cur);}
this.callPrimitiveEditors(cur,'remove');index[1].parentNode.removeChild(cur);}
if(useTrash){slice.push(index[1]);}
index[1].parentNode.removeChild(index[1]);}
this.originPosition=-1;this.items.splice(position,1);if(useTrash){this.trash.push([this,slice,index]);}
this.total--;},mapFuncToSliceAt:function(func,index){var cur,slice,curInnerRepeat,stackInnerRepeat;var opened=0;slice=this.items[index];cur=slice[0];curInnerRepeat=null;if(slice[0]==slice[1]){if(xtdom.ELEMENT_NODE==cur.nodeType){func.call(this,cur,curInnerRepeat);}}else{while(cur&&(cur!=slice[1])){if(cur.startRepeatedItem&&(cur.startRepeatedItem!=this)){if(curInnerRepeat){if(!stackInnerRepeat){stackInnerRepeat=[curInnerRepeat];}else{stackInnerRepeat.push(curInnerRepeat);}}
curInnerRepeat=cur.startRepeatedItem;if(cur.endRepeatedItem&&(cur.endRepeatedItem==cur.startRepeatedItem)){if(!stackInnerRepeat){stackInnerRepeat=[curInnerRepeat];}else{stackInnerRepeat.push(curInnerRepeat);}}}
if(cur.endRepeatedItem&&(cur.endRepeatedItem!=this)){if(stackInnerRepeat&&(stackInnerRepeat.length>0)){curInnerRepeat=stackInnerRepeat.pop();}else{curInnerRepeat=null;}}
if(xtdom.ELEMENT_NODE==cur.nodeType){func.call(this,cur,curInnerRepeat);}
cur=cur.nextSibling;}}}}
xtiger.resources.addBundle('repeat',{'plusIconURL':'plus.png','minusIconURL':'minus.png','uncheckedIconURL':'unchecked.png','checkedIconURL':'checked.png'});xtiger.editor.Choice=function(){this.items=[];this.curItem=-1;this.curDoc=null;}
xtiger.editor.Choice.prototype={initFromTree:function(menu,types,doc){this.curDoc=doc;this.menu=menu;menu.markChoiceEditor=this;this.types=types;},getTypes:function(){return this.types;},getSelectedChoiceName:function(){return this.types[this.curItem];},makeSeed:function(){if(!this.seed){this.seed=[this.items.length,this.types];}
return this.seed;},initFromSeed:function(editorSeed,doc){this.curDoc=doc;this.expectedLength=editorSeed[0];this.types=editorSeed[1];},setChoiceMenu:function(clone){this.menu=clone;var _this=this;xtdom.addEventListener(clone,'change',function(ev){_this.handleSelect(ev);},false);},setBeginChoiceItem:function(clone){this.items.push([clone,null]);},setEndChoiceItem:function(clone){this.items[this.items.length-1][1]=clone;if(this.items.length==this.expectedLength){xtiger.cross.log('stack-trace','Choice initialization terminated after cloning, size='+this.expectedLength);this.initializeSelectedItem(0);}},addChoiceItem:function(name,begin,end){this.items.push([begin,end]);if(begin.beginChoiceItem){xtiger.cross.log('warning','Choice <',name,'> ends with an already existing choice');}
if(end.endChoiceItem){xtiger.cross.log('warning','Choice <',name,'> ends with an already existing choice end');}
begin.beginChoiceItem=this;end.endChoiceItem=this;},initializeSelectedItem:function(rank){for(var i=0;i<this.items.length;i++){var memo=[];var item=this.items[i];var begin=item[0];var end=item[1];var cur=begin;memo.push(xtdom.getInlineDisplay(cur));if(i!=rank){if(cur.nodeType==xtdom.ELEMENT_NODE)cur.style['display']='none';}
while(cur!=end){cur=cur.nextSibling;memo.push(xtdom.getInlineDisplay(cur));if(i!=rank){if(cur.nodeType==xtdom.ELEMENT_NODE)cur.style['display']='none';}}
item.push(memo);}
this.curItem=rank;},selectChoiceItem:function(rank){xtiger.cross.log('plant','Choice.selectChoiceItem '+rank);if(this.curItem==rank)return;if(this.curItem!=-1){var item=this.items[this.curItem];var begin=item[0];var end=item[1];var memo=[];var cur=begin;memo.push(xtdom.getInlineDisplay(cur));if(cur.nodeType==xtdom.ELEMENT_NODE)cur.style['display']='none';while(cur!=end){cur=cur.nextSibling;memo.push(xtdom.getInlineDisplay(cur));if(cur.nodeType==xtdom.ELEMENT_NODE)cur.style['display']='none';}
item[2]=memo;}
var item=this.items[rank];var begin=item[0];var end=item[1];var memo=item[2];var i=0;var cur=begin;if(cur.nodeType==xtdom.ELEMENT_NODE)cur.style['display']=memo[i];while(cur!=end){i++;cur=cur.nextSibling;if(cur.nodeType==xtdom.ELEMENT_NODE)cur.style['display']=memo[i];}
this.curItem=rank;},selectChoiceForName:function(name){xtiger.cross.log('plant','Choice.selectChoiceForName '+name);var i;for(i=0;i<this.types.length;i++){if(this.types[i]==name){break}}
if(i!=this.types.length){this.selectChoiceItem(i);xtdom.setSelectedOpt(this.menu,i);return i;}else{return this.curItem;}},handleSelect:function(ev){var option=xtdom.getSelectedOpt(this.menu);this.selectChoiceItem(option);}}
xtiger.editor.Keyboard=function(){this.tabGroupManager=false;this.currentDevice=false;this.allowRC=false;}
xtiger.editor.Keyboard.prototype={setTabGroupManager:function(t){this.tabGroupManager=t;},register:function(aDevice,aAltHandle){var _handle=aAltHandle?aAltHandle:aDevice.getHandle();var _this=this;var _device=aDevice;var _handlers={keydown:function(ev){_this.handleKeyDown(ev,_device)},keyup:function(ev){_this.handleKeyUp(ev,_device)}}
xtdom.addEventListener(_handle,'keydown',_handlers.keydown,false);xtdom.addEventListener(_handle,'keyup',_handlers.keyup,false);return _handlers;},unregister:function(aDevice,handlers,aAltHandle){var _handle=aAltHandle?aAltHandle:aDevice.getHandle();xtdom.removeEventListener(_handle,'keydown',handlers.keydown,false);xtdom.removeEventListener(_handle,'keyup',handlers.keyup,false);},handleKeyDown:function(ev,device){if(device.isEditing()){if(this.tabGroupManager){this.tabGroupManager.filterKeyDown(ev);}
var validate=(this.allowRC&&(ev.keyCode==13)&&(!ev.shiftKey))||((!this.allowRC)&&(ev.keyCode==13));if(validate){device.stopEditing(false);}else if(ev.keyCode==27){device.cancelEditing();}
device.doKeyDown(ev);}},handleKeyUp:function(ev,device){if(device.isEditing()){if(this.tabGroupManager&&this.tabGroupManager.filterKeyPress(ev)){xtdom.preventDefault(ev);xtdom.stopPropagation(ev);}else{device.doKeyUp(ev);}}},grab:function(device,editor){if(this.tabGroupManager){this.tabGroupManager.startEditingSession(editor);}},release:function(device,editor){if(this.tabGroupManager){this.tabGroupManager.stopEditingSession();}},enableRC:function(){this.allowRC=true;},disableRC:function(){this.allowRC=false;}}
xtiger.editor.TabGroupManager=function(rootNode){this.root=rootNode;this.isChangingFocus=false;this.direction=0;}
xtiger.editor.TabGroupManager.prototype={startEditingSession:function(editor){if(this.isChangingFocus)return;this.tabs=[];var treeWalker=xtiger.cross.makeTreeWalker(this.root,xtdom.NodeFilter.SHOW_ELEMENT,function(node){if(node.xttPrimitiveEditor&&node.xttPrimitiveEditor.isFocusable()){return xtdom.NodeFilter.FILTER_ACCEPT}else{return xtdom.NodeFilter.FILTER_SKIP;}});while(treeWalker.nextNode()){this.tabs.push(treeWalker.currentNode.xttPrimitiveEditor);}
this.curEditor=editor;},stopEditingSession:function(){if(this.isChangingFocus)return;this.tabs=undefined;this.curEditor=undefined;},filterKeyDown:function(ev){this.direction=0;if(ev.keyCode==9){if(xtiger.cross.UA.gecko){this.direction=ev.shiftKey?-1:1;}else{this._focusNextInput(ev.shiftKey?-1:1);}
try{xtdom.preventDefault(ev);xtdom.stopPropagation(ev);}catch(e){}
return true}else{return false;}},filterKeyPress:function(ev){if(xtiger.cross.UA.gecko&&(this.direction!=0)){return(this._focusNextInput(this.direction));}
return false;},_focusNextInput:function(direction){var res=false;if(!this.tabs)
return;for(var i=0;i<this.tabs.length;i++){if(this.tabs[i]==this.curEditor){break;}}
if(i<this.tabs.length){var next;if((i+direction)<0){next=this.tabs.length-1;}else{next=(i+direction)%this.tabs.length;}
this.isChangingFocus=true;this.tabs[i].unfocus();this.tabs[next].focus();this.isChangingFocus=false;this.curEditor=this.tabs[next];res=true;}
this.direction=0;return res;}}
xtiger.editor.StringModel=function(){}
xtiger.editor.StringModel.prototype={createModel:function(container,useNode,curDoc){var wrapper=useNode.getAttribute('wrapper');var viewNode=xtdom.createElement(curDoc,'span');var content=xtdom.createTextNode(curDoc,'');var inputNode=xtdom.createElement(curDoc,'input');viewNode.appendChild(content);xtdom.addClassName(viewNode,'xtt-on');xtdom.addClassName(viewNode,'xtt-editable');xtdom.addClassName(inputNode,'xtt-off');xtdom.addClassName(inputNode,'xtt-editor');var wrap=wrapper&&("embedded"!=wrapper);if(wrap){var tag=wrapper
if("auto"==wrapper){tag=useNode.getAttribute('types');}
var holder=xtdom.createElement(curDoc,tag);if("auto"==wrapper){xtdom.addClassName(holder,'xtt-auto-wrapped');}
holder.appendChild(viewNode);holder.appendChild(inputNode);container.appendChild(holder);}else{container.appendChild(viewNode);container.appendChild(inputNode);}
var option=useNode.getAttribute('option');if(option){var check=xtdom.createElement(curDoc,'input');xtdom.setAttribute(check,'type','checkbox');xtdom.addClassName(check,'xtiger-option-checkbox');viewNode.parentNode.insertBefore(check,viewNode);}
return inputNode;},createEditorFromTree:function(handleNode,xtSrcNode,curDoc){var data=xtdom.extractDefaultContentXT(xtSrcNode);if(data){if(data.search(/\S/)==-1){data=null;}else{var m=data.match(/^\s*\<.*\>(.*?)\<\/\w*\>\s*$/);if(m){data=m[1];}}}
var param=xtSrcNode.getAttribute('param');var s=new xtiger.editor.String();s.initFromTree(handleNode,curDoc,data,param,xtSrcNode.getAttribute('option')||false);return s;},createEditorFromSeed:function(seed,clone,curDoc){var s=new xtiger.editor.String();s.initFromSeed(seed,clone,curDoc);return s;}}
xtiger.editor.String=function(){this.defaultContent=null;this.param=null;this.isOptional=null;this.isSelected=false;this.doEdit=false;var _this=this;this.lostFocusHandler=function(ev){_this.unfocus()};}
xtiger.editor.String.prototype={isEditing:function(){return this.doEdit;},startEditing:function(isMouseAction,doSelectAll){this.doEdit=true;this.keyboard.grab(this,this);xtdom.setAttribute(this.editor,'size',this.editor.value.length+Number(this.param['lookahead']));xtdom.replaceClassNameBy(this.handle,'xtt-on','xtt-off');xtdom.replaceClassNameBy(this.editor,'xtt-off','xtt-on');try{this.editor.focus();if(doSelectAll||(this.editor.value==this.defaultContent)){this.editor.select();}}catch(e){}
xtdom.addEventListener(this.editor,'blur',this.lostFocusHandler,true);},stopEditing:function(willEditAgain,value,isCancel){this.doEdit=false;var content=value||this.editor.value;if(content.search(/\S/)==-1){content=this.defaultContent;}
var isEdited=(content!=this.defaultContent);this.setData(content);xtdom.replaceClassNameBy(this.handle,'xtt-off','xtt-on');xtdom.replaceClassNameBy(this.editor,'xtt-on','xtt-off');this.keyboard.release(this,this);xtdom.removeEventListener(this.editor,'blur',this.lostFocusHandler,true);if((!isCancel)&&isEdited)
{if((this.isOptional)&&(!this.isSelected)){this.setSelectionState(true);}
xtiger.editor.Repeat.autoSelectRepeatIter(this.getHandle());}
if(!isEdited){this.setSelectionState(false);}},cancelEditing:function(){this.stopEditing(false,this.dump(),true);},doKeyDown:function(ev){},doKeyUp:function(ev){},getHandle:function(ev){return this.editor;},decodeParameters:function(res,params){var tokens=params.split(';');for(var i=0;i<tokens.length;i++){var p=tokens[i].split('=');if(p.length==2){res[p[0]]=p[1];}}},initFromTree:function(handleNode,doc,userdata,parameters,option){this.param={'lookahead':2}
this.curDoc=doc;this.handle=handleNode.previousSibling;this.editor=handleNode;this.defaultContent=userdata||'click to edit';if(parameters){this.decodeParameters(this.param,parameters)}
if(option){this.isOptional=option.toLowerCase();}
this.awake();},awake:function(){this.keyboard=xtiger.session(this.curDoc).load('keyboard');var _this=this;xtdom.addEventListener(this.handle,'click',function(ev){_this.handleClick(ev)},true);this.setData(this.defaultContent);this.editor.defaultValue=this.defaultContent;this.keyboard.register(this);if(this.isOptional){var check=this.handle.previousSibling;xtdom.addEventListener(check,'click',function(ev){_this.handleSelect(ev)},true);this.setSelectionState('set'==this.isOptional);}},makeSeed:function(){if(!this.seed){var factory=xtiger.editor.Plugin.prototype.pluginEditors['string'];this.seed=[factory,this.defaultContent,this.param,this.isOptional];}
return this.seed;},initFromSeed:function(seed,clone,doc){this.curDoc=doc;this.handle=clone.previousSibling;this.editor=clone;this.defaultContent=seed[1];this.param=seed[2];this.isOptional=seed[3];this.awake();},setSelectionState:function(isSel){if(this.isOptional){var check=this.handle.previousSibling;this.isSelected=isSel;check.checked=isSel;if(isSel){xtdom.replaceClassNameBy(this.handle,'xtt-option-edit-unset','xtt-option-edit-set');}else{xtdom.replaceClassNameBy(this.handle,'xtt-option-edit-set','xtt-option-edit-unset');}}},load:function(point,dataSrc){if(point!==-1){var value=dataSrc.getDataFor(point);this.setData(value);this.setSelectionState(true);}else{this.setData(this.defaultContent);this.setSelectionState(false);}},save:function(logger){if((!this.isOptional)||(this.isSelected)){logger.write(this.dump());}else{logger.discardNodeIfEmpty();}},dump:function(){return this.handle.firstChild.data;},setData:function(value){var norm=value?value.replace(/\s+/g,' '):'click to edit';this.handle.firstChild.data=norm;this.editor.value=norm;this.editor.size=norm.length;},can:function(action){return false;},handleClick:function(ev){this.startEditing(true,ev.shiftKey);},handleSelect:function(ev){this.isSelected=this.handle.previousSibling.checked;if(this.isSelected){xtdom.replaceClassNameBy(this.handle,'xtt-option-edit-unset','xtt-option-edit-set');xtiger.editor.Repeat.autoSelectRepeatIter(this.getHandle());}else{xtdom.replaceClassNameBy(this.handle,'xtt-option-edit-set','xtt-option-edit-unset');}},isFocusable:function(){return true;},focus:function(){this.startEditing(false,false);},unfocus:function(){this.stopEditing(false);}}
xtiger.editor.Plugin.prototype.pluginEditors['string']=new xtiger.editor.StringModel();xtiger.editor.RobustLoader=function(){}
xtiger.editor.RobustLoader.prototype={WARN_REPEAT_COUNT:250,_dumpStackPath:function(msg,stack,point){},_dumpPointName:function(p){if(p){if(p instanceof Array){return p[0].localName;}else{return'-1';}}else{return'null';}},_empile:function(stack,point){var path=this._dumpStackPath('Empile',stack,point);stack.push(point);},_replaceTop:function(stack,point){var path=this._dumpStackPath('Remplace',stack,point);stack[stack.length-1]=point;},_depile:function(stack){var top=stack.pop();var path=this._dumpStackPath('Depile',stack,top);return stack[stack.length-1];},loadData:function(n,dataSrc){var curSrc=dataSrc.getRootVector();var stack=[curSrc];this.loadDataIter(n,dataSrc,stack);},makeRepeatState:function(repeater,size,useStack,useReminder){return[repeater,size,useStack,useReminder];},loadDataSlice:function(begin,end,dataSrc,stack,point,origin,repeatedRepeater){var repeats=[];var cur=begin;var go=true;var next;var tmpStack,pos,begin,end;while(cur&&go){if(cur.startRepeatedItem&&(cur.startRepeatedItem!=repeatedRepeater)){if((repeats.length==0)||((repeats[repeats.length-1][0])!=cur.startRepeatedItem)){var state;if(cur.startRepeatedItem.hasLabel()){var nextPoint=dataSrc.getVectorFor(cur.startRepeatedItem.dump(),point);if((nextPoint instanceof Array)&&(dataSrc.lengthFor(nextPoint)>0)){this._empile(stack,nextPoint);point=nextPoint;state=this.makeRepeatState(cur.startRepeatedItem,cur.startRepeatedItem.getSize(),true,true);}else{cur=cur.startRepeatedItem.getLastNodeForSlice(cur.startRepeatedItem.getSize());cur=cur.nextSibling;continue}}else{if(this.repeatWouldLDS(cur.startRepeatedItem,dataSrc,point)){state=this.makeRepeatState(cur.startRepeatedItem,cur.startRepeatedItem.getSize(),false,true);}else{cur=cur.startRepeatedItem.getLastNodeForSlice(cur.startRepeatedItem.getSize());cur=cur.nextSibling;continue}}
repeats.push(state);}}
if(cur.beginChoiceItem&&(cur.beginChoiceItem!=origin)){var c=cur.beginChoiceItem;point=dataSrc.getVectorForAnyOf(c.getTypes(),point);if(point instanceof Array){this._empile(stack,point);var curItem=c.selectChoiceForName(dataSrc.nameFor(point));if(c.items[curItem][0]!=c.items[curItem][1]){this.loadDataSlice(c.items[curItem][0],c.items[curItem][1],dataSrc,stack,point,c);cur=c.items[c.items.length-1][1];if((cur.xttCloseLabel&&(!cur.xttOpenLabel))&&(curItem!=(c.items.length-1))){point=this._depile(stack);}}else{this.loadDataIter(c.items[curItem][0],dataSrc,stack);point=this._depile(stack);cur=c.items[c.items.length-1][1];}}}else{this.loadDataIter(cur,dataSrc,stack);point=stack[stack.length-1];if(origin){if(cur==origin.items[origin.curItem][1]){point=this._depile(stack);return;}}}
if(cur==end){go=false;}
next=cur.nextSibling;if(cur.endRepeatedItem&&(cur.endRepeatedItem!=repeatedRepeater)){var state=repeats[repeats.length-1];--(state[1]);if(state[1]<0){cur.endRepeatedItem.sliceLoaded();}
if(state[1]<=0){if(state[3]){var nb=0;var repeater=cur.endRepeatedItem;while(this.repeatWouldLDS(repeater,dataSrc,point)){if(++nb>this.WARN_REPEAT_COUNT){var terminate=confirm('Too many repetitions, data seems corrupted, abort ?');if(terminate)break;}
tmpStack=[point];pos=repeater.appendSlice();begin=repeater.getFirstNodeForSlice(pos);end=repeater.getLastNodeForSlice(pos);this.loadDataSlice(begin,end,dataSrc,tmpStack,point,undefined,repeater);repeater.sliceLoaded();}}
if(state[2]){point=this._depile(stack);}
repeats.pop();}}
cur=next;}},loadDataIter:function(n,dataSrc,stack){var curFlow,curLabel;var point=stack[stack.length-1];if(n.xttOpenLabel){curLabel=n.xttOpenLabel;if(curLabel.charAt(0)=='!'){var m=curLabel.match(/^!(.*?)!(.*)$/);curFlow=m[1];curLabel=m[2];point=dataSrc.openFlow(curFlow,point,curLabel)||point;}
var attr=false;if(curLabel.charAt(0)=='@'){point=dataSrc.getAttributeFor(curLabel.substr(1,curLabel.length-1),point);attr=true;}else{point=dataSrc.getVectorFor(curLabel,point);}
if(attr||((point instanceof Array)&&(dataSrc.lengthFor(point)>0))){this._empile(stack,point);}else{point=-1;this._empile(stack,point);}}
if(n.xttPrimitiveEditor){n.xttPrimitiveEditor.load(point,dataSrc);point=-1;}
if(n.firstChild){this.loadDataSlice(n.firstChild,n.lastChild,dataSrc,stack,point);}
if(n.xttCloseLabel){curLabel=n.xttCloseLabel;if(curLabel.charAt(0)=='!'){var m=curLabel.match(/^!(.*?)!(.*)$/);curFlow=m[1];curLabel=m[2];dataSrc.closeFlow(curFlow,point);}
this._depile(stack);}},repeatWouldLDS:function(repeater,dataSrc,point){var tmpStack=[point];var begin=repeater.getFirstNodeForSlice(0);var end=repeater.getLastNodeForSlice(0);return this.wouldLoadDataSlice(begin,end,dataSrc,tmpStack,point,undefined,repeater);},wouldLoadDataSlice:function(begin,end,dataSrc,stack,point,origin,repeatedRepeater){var repeats=[];var cur=begin;var go=true;var next;while(cur&&go){if(cur.startRepeatedItem&&(cur.startRepeatedItem!=repeatedRepeater)){if((repeats.length==0)||((repeats[repeats.length-1][0])!=cur.startRepeatedItem)){var state;if(cur.startRepeatedItem.hasLabel()){if(dataSrc.hasVectorFor(cur.startRepeatedItem.dump(),point)){return true;}else{cur=cur.startRepeatedItem.getLastNodeForSlice(cur.startRepeatedItem.getSize());cur=cur.nextSibling;continue}}else{if(this.repeatWouldLDS(cur.startRepeatedItem,dataSrc,point)){return true;}else{cur=cur.startRepeatedItem.getLastNodeForSlice(cur.startRepeatedItem.getSize());cur=cur.nextSibling;continue}}
repeats.push(state);}}
if(cur.beginChoiceItem&&(cur.beginChoiceItem!=origin)){var c=cur.beginChoiceItem;if(dataSrc.hasVectorForAnyOf(c.getTypes(),point)){return true;}}else{if(this.wouldLoadDataIter(cur,dataSrc,stack)){return true;}
point=stack[stack.length-1];}
if(cur==end){go=false;}
next=cur.nextSibling;if(cur.endRepeatedItem&&(cur.endRepeatedItem!=repeatedRepeater)){var state=repeats[repeats.length-1];if(true||(cur.endRepeatedItem==state[0])){--(state[1]);if(state[1]<=0){repeats.pop();}}}
cur=next;}},wouldLoadDataIter:function(n,dataSrc,stack){var curFlow,curLabel;var point=stack[stack.length-1];if(n.xttOpenLabel){curLabel=n.xttOpenLabel;if(curLabel.charAt(0)=='!'){var m=curLabel.match(/^!(.*?)!(.*)$/);curFlow=m[1];curLabel=m[2];point=dataSrc.openFlow(curFlow,point,curLabel)||point;}
var attr=false;if(curLabel.charAt(0)=='@'){attr=true;if(dataSrc.hasAttributeFor(curLabel.substr(1,curLabel.length-1),point)){return true;}}else{if(dataSrc.hasVectorFor(curLabel,point)){return true;}else{point=-1;}}
if(attr||((point instanceof Array)&&(dataSrc.lengthFor(point)>0))){this._empile(stack,point);}else{point=-1;this._empile(stack,point);}}
if(n.xttPrimitiveEditor){point=-1;}
if(n.firstChild){if(this.wouldLoadDataSlice(n.firstChild,n.lastChild,dataSrc,stack,point)){return true;}}
if(n.xttCloseLabel){curLabel=n.xttCloseLabel;if(curLabel.charAt(0)=='!'){var m=curLabel.match(/^!(.*?)!(.*)$/);curFlow=m[1];curLabel=m[2];dataSrc.closeFlow(curFlow,point);}else{this._depile(stack);}}
return false;}}
xtiger.editor.Generator.prototype.defaultLoader=new xtiger.editor.RobustLoader();xtiger.editor.BasicLoader=function(){}
xtiger.editor.BasicLoader.prototype={loadData:function(n,dataSrc){var curSrc=dataSrc.getRootVector();var stack=[curSrc];this.loadDataIter(n,dataSrc,stack);},hasDataFor:function(repeater,point,dataSrc){var doMore=false;if(repeater.hasLabel()){doMore=(0!=dataSrc.lengthFor(point));}else{doMore=dataSrc.hasDataFor(repeater.getRepeatableLabel(),point);}
return doMore;},makeRepeatState:function(repeater,size,useStack,useReminder){return[repeater,size,useStack,useReminder];},loadDataSlice:function(begin,end,dataSrc,stack,point,origin,repeatedRepeater){var repeats=[];var cur=begin;var go=true;var next;while(cur&&go){if(cur.startRepeatedItem&&(cur.startRepeatedItem!=repeatedRepeater)){if((repeats.length==0)||((repeats[repeats.length-1][0])!=cur.startRepeatedItem)){var state;if(cur.startRepeatedItem.hasLabel()){var nextPoint=dataSrc.getVectorFor(cur.startRepeatedItem.dump(),point);if((nextPoint instanceof Array)&&(dataSrc.lengthFor(nextPoint)>0)){stack.push(nextPoint);point=nextPoint;state=this.makeRepeatState(cur.startRepeatedItem,cur.startRepeatedItem.getSize(),true,true);}else{cur=cur.startRepeatedItem.getLastNodeForSlice(cur.startRepeatedItem.getSize());cur=cur.nextSibling;continue}}else{if(this.hasDataFor(cur.startRepeatedItem,point,dataSrc)){state=this.makeRepeatState(cur.startRepeatedItem,cur.startRepeatedItem.getSize(),false,true);}else{cur=cur.startRepeatedItem.getLastNodeForSlice(cur.startRepeatedItem.getSize());cur=cur.nextSibling;continue}}
repeats.push(state);}}
if(cur.beginChoiceItem&&(cur.beginChoiceItem!=origin)){var c=cur.beginChoiceItem;point=dataSrc.getVectorForAnyOf(c.getTypes(),point);if(point instanceof Array){stack.push(point);var curItem=c.selectChoiceForName(dataSrc.nameFor(point));if(c.items[curItem][0]!=c.items[curItem][1]){this.loadDataSlice(c.items[curItem][0],c.items[curItem][1],dataSrc,stack,point,c);cur=c.items[c.items.length-1][1];if((cur.xttCloseLabel&&(!cur.xttOpenLabel))&&(curItem!=(c.items.length-1))){stack.pop();point=stack[stack.length-1];}}else{this.loadDataIter(c.items[curItem][0],dataSrc,stack);stack.pop();point=stack[stack.length-1];cur=c.items[c.items.length-1][1];}}}else{this.loadDataIter(cur,dataSrc,stack);point=stack[stack.length-1];if(origin){if(cur==origin.items[origin.curItem][1]){stack.pop();point=stack[stack.length-1];return;}}}
if(cur==end){go=false;}
next=cur.nextSibling;if(cur.endRepeatedItem&&(cur.endRepeatedItem!=repeatedRepeater)){var state=repeats[repeats.length-1];if(true||(cur.endRepeatedItem==state[0])){--(state[1]);if(state[1]<0){cur.endRepeatedItem.sliceLoaded();}
if(state[1]<=0){if(state[3]&&this.hasDataFor(cur.endRepeatedItem,point,dataSrc)){var repeater=cur.endRepeatedItem;while(this.hasDataFor(repeater,point,dataSrc)){xtiger.cross.log('stack-trace','>>[ extra ]>> start repetition for',repeater.dump());var tmpStack=[point];var pos=repeater.appendSlice();var begin=repeater.getFirstNodeForSlice(pos);var end=repeater.getLastNodeForSlice(pos);this.loadDataSlice(begin,end,dataSrc,tmpStack,point,undefined,repeater);repeater.sliceLoaded();}}
if(state[2]){stack.pop();point=stack[stack.length-1];}
repeats.pop();}}}
cur=next;}},loadDataIter:function(n,dataSrc,stack){var curFlow,curLabel;var point=stack[stack.length-1];if(n.xttOpenLabel){curLabel=n.xttOpenLabel;if(curLabel.charAt(0)=='!'){var m=curLabel.match(/^!(.*?)!(.*)$/);curFlow=m[1];curLabel=m[2];point=dataSrc.openFlow(curFlow,point,curLabel)||point;}
var attr=false;if(curLabel.charAt(0)=='@'){point=dataSrc.getAttributeFor(curLabel.substr(1,curLabel.length-1),point);attr=true;}else{point=dataSrc.getVectorFor(curLabel,point);}
if(attr||((point instanceof Array)&&(dataSrc.lengthFor(point)>0))){stack.push(point);}else{point=-1;stack.push(point);}}
if(n.xttPrimitiveEditor){n.xttPrimitiveEditor.load(point,dataSrc);point=-1;}
if(n.firstChild){this.loadDataSlice(n.firstChild,n.lastChild,dataSrc,stack,point);}
if(n.xttCloseLabel){curLabel=n.xttCloseLabel;if(curLabel.charAt(0)=='!'){var m=curLabel.match(/^!(.*?)!(.*)$/);curFlow=m[1];curLabel=m[2];dataSrc.closeFlow(curFlow,point);}
stack.pop();}}}
xtiger.editor.Generator.prototype.defaultLoader=new xtiger.editor.BasicLoader();xtiger.editor.BasicSerializer=function(baseUrl){}
xtiger.editor.BasicSerializer.prototype={serializeData:function(n,logger,rootTagName){logger.openTag(rootTagName||'document');this.serializeDataIter(n,logger);logger.closeTag(rootTagName||'document');},serializeDataSlice:function(begin,end,logger,origin){var repeats=[];var cur=begin;var go=true;while(cur&&go){if(cur.startRepeatedItem){if((repeats.length==0)||((repeats[repeats.length-1][0])!=cur.startRepeatedItem)){if(cur.startRepeatedItem.getSize()==0){cur=cur.startRepeatedItem.getLastNodeForSlice(0);cur=cur.nextSibling;continue;}else if(cur.startRepeatedItem.hasLabel()){logger.openTag(cur.startRepeatedItem.dump());}
repeats.push([cur.startRepeatedItem,cur.startRepeatedItem.getSize()]);}}
if(cur.beginChoiceItem&&(cur.beginChoiceItem!=origin)){var c=cur.beginChoiceItem;logger.openTag(c.getSelectedChoiceName());if(c.items[c.curItem][0]!=c.items[c.curItem][1]){this.serializeDataSlice(c.items[c.curItem][0],c.items[c.curItem][1],logger,c);}else{this.serializeDataIter(c.items[c.curItem][0],logger);logger.closeTag(c.getSelectedChoiceName());}
cur=c.items[c.items.length-1][1];if(cur.xttCloseLabel&&(c.curItem!=(c.items.length-1))){logger.closeTag(cur.xttCloseLabel);}}else{this.serializeDataIter(cur,logger);if(origin){if(cur==origin.items[origin.curItem][1]){logger.closeTag(origin.getSelectedChoiceName());}}}
if(cur.endRepeatedItem){if(true||(cur.endRepeatedItem==repeats[repeats.length-1][0])){--(repeats[repeats.length-1][1]);if(repeats[repeats.length-1][1]<=0){if((cur.endRepeatedItem.getSize()!=0)&&(cur.endRepeatedItem.hasLabel())){logger.closeTag(cur.endRepeatedItem.dump());}
repeats.pop();}}}
if(cur==end){go=false;}
cur=cur.nextSibling;}},serializeDataIter:function(n,logger){var curFlow,curLabel;if(n.xttOpenLabel){curLabel=n.xttOpenLabel;if(curLabel.charAt(0)=='!'){var m=curLabel.match(/^!(.*?)!(.*)$/);curFlow=m[1];curLabel=m[2];logger.openFlow(curFlow,curLabel);}
if(curLabel.charAt(0)=='@'){logger.openAttribute(curLabel.substr(1,curLabel.length-1));}else{logger.openTag(curLabel);}}
if(n.xttPrimitiveEditor){n.xttPrimitiveEditor.save(logger);}
if(n.firstChild){this.serializeDataSlice(n.firstChild,n.lastChild,logger);}
if(n.xttCloseLabel){curFlow=false;curLabel=n.xttCloseLabel;if(curLabel.charAt(0)=='!'){var m=curLabel.match(/^!(.*?)!(.*)$/);curFlow=m[1];curLabel=m[2];}
if(curLabel.charAt(0)=='@'){logger.closeAttribute(curLabel.substr(1,curLabel.length-1));}else{logger.closeTag(curLabel);}
if(curFlow){logger.closeFlow(curFlow);}}}}
xtiger.editor.Generator.prototype.defaultSerializer=new xtiger.editor.BasicSerializer();xtiger.editor.TextFactory=(function TextFactory(){var _TextModel=function(aHandleNode,aDocument){var _DEFAULT_PARAMS={device:'text-device',type:'input',layout:'placed',shape:'self',expansion:'grow',clickthrough:'true',enablelinebreak:'false'};this._handle=aHandleNode;this._data=null;this._defaultData=this._data;this._noData=this._handle.firstChild;this._document=aDocument;this._params=_DEFAULT_PARAMS;this._isOptional=false;this._isOptionSet=false;this._optCheckBox;this._device=null;this._seed=null;this._isModified=false;this._uniqueKey;this.create();};_TextModel.prototype={_setData:function(aData){if(this._handle.firstChild)
this._handle.firstChild.data=aData;this._data=aData;},create:function(){},init:function(aDefaultData,aParams,aOption,aUniqueKey,aRepeater){if(aParams){if(typeof(aParams)=='string')
xtiger.util.decodeParameters(aParams,this._params);else if(typeof(aParams)=='object')
this._params=aParams;}
if(aDefaultData&&typeof aDefaultData=='string'){this._defaultData=aDefaultData;}else{this._defaultData='click to edit';}
this._data=this._defaultData;this._setData(this._defaultData);this._isOptional=aOption?true:false;if(aOption){this._optCheckBox=this._handle.previousSibling;if(aOption=='unset')
this._isOptionSet=true;(aOption=='set')?this.set(false):this.unset(false);}
this._uniqueKey=aUniqueKey;if(this.getParam('hasClass')){xtdom.addClassName(this._handle,this.getParam('hasClass'));}
var _deviceFactory=this._params['device']?xtiger.factory(this._params['device']):xtiger.factory(this._params['defaultDevice']);this._device=_deviceFactory.getInstance(this._document,this._params['type'],this._params['layout']);this.awake();},makeSeed:function(){if(!this._seed)
this._seed=[xtiger.editor.TextFactory,this._defaultData,this._params,this._isOptional];return this._seed;},remove:function(){},can:function(aFunction){return typeof this[aFunction]=='function';},execute:function(aFunction,aParam){return this[aFunction](aParam);},load:function(aPoint,aDataSrc){var _value;if(aPoint!==-1){_value=aDataSrc.getDataFor(aPoint);this._setData(_value||this._defaultData);this._isModified=(_value!=this._defaultData);this.set(false);}else{this.clear(false);}},save:function(aLogger){if(this.isOptional()&&!this._isOptionSet){aLogger.discardNodeIfEmpty();return;}
if(!this._data)
return;aLogger.write(this._data);},update:function(aData){if(aData==this._data){return;}
if(aData.search(/\S/)==-1||(aData==this._defaultData)){this.clear(true);return;}
this._setData(aData);this._isModified=true;this.set(true);},clear:function(doPropagate){this._setData(this._defaultData);this._isModified=false;if(this.isOptional()&&this.isSet())
this.unset(doPropagate);},setDefaultData:this.clear,getData:function(){return this._data;},getDefaultData:function(){return this._defaultData;},getHandle:function(inDOMOnly){if(inDOMOnly){if(this._params['layout']=='placed'&&this._device&&this._device.getCurrentModel()==this)
return this._device.getHandle();}
return this._handle;},getDocument:function(){return this._document;},getGhost:function(){var _s=this._params['shape'];return(_s&&_s.charAt(0)=='p')?this._handle.parentNode:this._handle;},getParam:function(aKey){return this._params[aKey];},getUniqueKey:function(){return this._uniqueKey;},isModified:function(){return this._isModified;},setModified:function(isModified){this._isModified=isModified;},isFocusable:function(){return true;},focus:function(){this.startEditing({shiftKey:true});},unfocus:function(){this.stopEditing();},isOptional:function(){return this._isOptional;},isSet:function(){return this._isOptional&&(this._isOptionSet?true:false);},set:function(doPropagate){if(doPropagate){xtiger.editor.Repeat.autoSelectRepeatIter(this.getHandle(true));xtdom.removeClassName(this._handle,'xtt-repeat-unset');}
if(this._isOptionSet)
return;this._isOptionSet=true;if(this._isOptional){xtdom.removeClassName(this._handle,'xtt-option-edit-unset');xtdom.addClassName(this._handle,'xtt-option-edit-set');this._optCheckBox.checked=true;}},unset:function(doPropagate){if(!this._isOptionSet)
return;this._isOptionSet=false;if(this._isOptional){xtdom.removeClassName(this._handle,'xtt-option-edit-set');xtdom.addClassName(this._handle,'xtt-option-edit-unset');this._optCheckBox.checked=false;}},awake:function(){var _this=this;if(!this._params['noclick']){xtdom.addEventListener(this._handle,'click',function(ev){_this.startEditing(ev);},true);}
if(this.isOptional()){xtdom.addEventListener(this._optCheckBox,'click',function(ev){_this.onToggleOpt(ev);},true);}},startEditing:function(aEvent){var _doSelect=aEvent?(!this._isModified||aEvent.shiftKey):false;this._device.startEditing(this,aEvent,_doSelect);},stopEditing:function(){this._device.stopEditing(false,false);},onToggleOpt:function(ev){this._isOptionSet?this.unset(true):this.set(true);}};var _BASE_KEY='text';var _keyCounter=0;return{createModel:function createModel(aContainer,aXTUse,aDocument){var _handletag=aXTUse.getAttribute('handle');_handletag=_handletag?_handletag:'span';var _handle=xtdom.createElement(aDocument,_handletag);var _content=xtdom.createTextNode(aDocument,'');_handle.appendChild(_content);xtdom.addClassName(_handle,'xtt-on');xtdom.addClassName(_handle,'xtt-editable');var option=aXTUse.getAttribute('option');if(option){var check=xtdom.createElement(aDocument,'input');xtdom.setAttribute(check,'type','checkbox');xtdom.addClassName(check,'xtiger-option-checkbox');aContainer.appendChild(check);}
aContainer.appendChild(_handle);return _handle;},createEditorFromTree:function createEditorFromTree(aHandleNode,aXTUse,aDocument){var _data=xtdom.extractDefaultContentXT(aXTUse);if(_data&&(_data.search(/\S/)==-1)){_data=null;}
var _model=new _TextModel(aHandleNode,aDocument);var _param={};xtiger.util.decodeParameters(aXTUse.getAttribute('param'),_param);if(_param['filter'])
_model=this.applyFilters(_model,_param['filter']);_model.init(_data,aXTUse.getAttribute('param'),aXTUse.getAttribute('option'),this.createUniqueKey());return _model;},createEditorFromSeed:function createEditorFromSeed(aSeed,aClone,aDocument,aRepeater){var _model=new _TextModel(aClone,aDocument);var _defaultData=aSeed[1];var _params=aSeed[2];var _option=aSeed[3];if(_params['filter'])
_model=this.applyFilters(_model,_params['filter']);_model.init(_defaultData,_params,_option,this.createUniqueKey(),aRepeater);return _model;},createUniqueKey:function createUniqueKey(){return _BASE_KEY+(_keyCounter++);}}})();xtiger.editor.Plugin.prototype.pluginEditors['text']=xtiger.util.filterable('text',xtiger.editor.TextFactory);(function(){var _TextMetrics=function _TextMetrics(doc){this.div=xtdom.createElement(doc,'div');xtdom.addClassName(this.div,'xtt-shadow-buffer');this.divText=xtdom.createTextNode(doc,'');this.div.appendChild(this.divText);}
_TextMetrics.prototype={setBBox:function setBBox(w,h,handle,shape,type){var wpx=w+'px';var hpx=h+'px';this.lastWidth=w;this.lastHeight=h;if((type=='input')||(shape=='self')){this.div.style.width='';this.div.style.height='';}else{this.div.style.width=wpx;this.div.style.height='auto';}
handle.style.width=wpx;handle.style.height=hpx;},setText:function setText(text){this.divText.data=text+'m';},adjustWidth:function adjustWidth(handle){var w=Math.max(this.div.offsetWidth,this.div.clientWidth,this.div.scrollWidth);if(w>this.lastWidth){handle.style.width=w-(w%20)+20+'px';this.lastWidth=w;}},adjustHeight:function adjustHeight(handle,init){var h=Math.max(this.div.offsetHeight,this.div.clientHeight,this.div.scrollHeight);if(h>this.lastHeight){handle.style.height=h+"px";this.lastHeight=h;}},grab:function grab(field){field.hook.appendChild(this.div);},release:function(field,willEditAgain){field.hook.removeChild(this.div);}};xtiger.editor.TextDevice=function(input,kbd,doc){this.keyboard=kbd;this.field=input;this.metrics=xtiger.session(doc).load('metrics');if(!this.metrics){this.metrics=new _TextMetrics(doc);xtiger.session(doc).save('metrics',this.metrics);}
this.currentEditor=null;var _this=this;this.blurHandler=function(ev){_this.handleBlur(ev);};};xtiger.editor.TextDevice.prototype={getHandle:function(){return this.field.getHandle();},isEditing:function(){return(null!=this.currentEditor);},_computeOffset:function(mouseEvent,editor){var offset=-1;var selObj,selRange;if(mouseEvent&&window.getSelection&&(editor.getParam('clickthrough')=='true')){selObj=window.getSelection();if(selObj&&(selObj.rangeCount>0)){selRange=selObj.getRangeAt(0);if(selRange){offset=selRange.startOffset;}}}
return offset;},startEditing:function(editor,mouseEvent,doSelectAll){var ghost,offset;var constw,consth;var pos,oRange;var shape;var redux=false;var handle=this.field.getHandle();var coldStart=false;if(this.currentEditor){this.stopEditing(true);}else{this._kbdHandlers=this.keyboard.register(this);this.keyboard.grab(this,editor);if(editor.getParam('hasClass')){xtdom.addClassName(handle,editor.getParam('hasClass'));}
if(!doSelectAll){offset=this._computeOffset(mouseEvent,editor);}
coldStart=true;this.field.show(editor);}
this.currentEditor=editor;ghost=editor.getGhost();constw=Math.max(ghost.offsetWidth,ghost.clientWidth,ghost.scrollWidth);consth=Math.max(ghost.offsetHeight,ghost.clientHeight,ghost.scrollHeight);this.field.grab(editor);this.metrics.grab(this.field);if(editor.getParam('enablelinebreak')=='true'){this.keyboard.enableRC();}
try{handle.focus();if(doSelectAll){handle.select();}}catch(e){}
if(offset){pos=(offset==-1)?handle.value.length:offset;if(handle.setSelectionRange){handle.setSelectionRange(pos,pos);}else if(handle.createTextRange){oRange=handle.createTextRange();oRange.moveStart("character",pos);oRange.moveEnd("character",pos);oRange.select();}}
shape=this.currentEditor.getParam('shape');if(shape.charAt(shape.length-1)=='x'){var m=shape.match(/\d+/);if(m){constw=constw-parseInt(m[0]);redux=true;}}
this.metrics.setBBox(constw,consth,handle,shape,this.field.deviceType);this.metrics.setText(this.field.getValue());if((this.field.deviceType=='input')||(shape=='self')){this.metrics.adjustWidth(handle);}
if(redux){this.metrics.adjustHeight(handle);}
if(coldStart){xtdom.addEventListener(handle,'blur',this.blurHandler,false);}},stopEditing:function(willEditAgain,isCancel){if(!this.currentEditor)
return;if(!this.stopInProgress){this.stopInProgress=true;var model=this.currentEditor;this.currentEditor=null;this.field.release(model,willEditAgain);this.metrics.release(this.field);if(!isCancel){model.update(this.field.getValue());}
if(!willEditAgain){if(model.getParam('enablelinebreak')=='true'){this.keyboard.disableRC();}
this.keyboard.unregister(this,this._kbdHandlers);this.keyboard.release(this,model);xtdom.removeEventListener(this.getHandle(),'blur',this.blurHandler,false);if(model.getParam('hasClass')){xtdom.removeClassName(this.getHandle(),model.getParam('hasClass'));}}
this.stopInProgress=false;}},getCurrentModel:function(){return this.currentEditor;},cancelEditing:function(){this.stopEditing(false,true);},handleBlur:function(ev){this.stopEditing(false);},doKeyDown:function(ev){if(this.currentEditor&&(this.currentEditor.getParam('expansion')=='grow')){this.curLength=this.field.getValue().length;this.adjustShape();}},doKeyUp:function(ev){if(this.currentEditor&&this.currentEditor.can('onkeyup')){this.currentEditor.execute('onkeyup',this.field.getHandle());}
if(this.currentEditor&&(this.currentEditor.getParam('expansion')=='grow')){if(this.field.getValue().length>(this.curLength+1)){this.adjustShape();}}},adjustShape:function(){this.metrics.setText(this.field.getValue());var h=this.field.getHandle();this.metrics.adjustWidth(h);if(this.field.deviceType=='textarea'){this.metrics.adjustHeight(h);}}};xtiger.editor.FloatingField=function(kind,doc){this.deviceType=kind;this.handle=this.createHandleForDoc(kind,doc);this.hook=xtdom.createElement(doc,'div');xtdom.addClassName(this.hook,'xtt-text-container');this.hook.appendChild(this.handle);this.hook.style.display='none';};xtiger.editor.FloatingField.prototype={createHandleForDoc:function(kind,doc){var device=xtiger.session(doc).load('ff_'+kind);if(!device){device=xtdom.createElement(doc,kind);xtdom.addClassName(device,'xtt-text-float');xtiger.session(doc).save('ff_'+kind,device);}
return device;},getHandle:function(){return this.handle;},getValue:function(){return this.handle.value;},show:function(){this.hook.style.display='inline';},grab:function(editor){this.handle.value=editor.getData();this.editorHandle=editor.getHandle();this.editorHandle.parentNode.insertBefore(this.hook,this.editorHandle);editor.getHandle().style.visibility='hidden';},release:function(editor,willEditAgain){this.editorHandle.parentNode.removeChild(this.hook);editor.getHandle().style.visibility='visible';if(!willEditAgain){this.hook.style.display='none';}},setPosition:function(ghost){var pos=xtdom.findPos(ghost);with(this.handle.style){left=pos[0]+'px';top=pos[1]+'px';}}};xtiger.editor.PlacedField=function(kind,doc){this.myDoc=doc;this.deviceType=kind;this.handle=this.createHandleForDoc(kind,doc);this.handle.style.display='none';this.cache={};this.hook;};xtiger.editor.PlacedField.prototype={createHandleForDoc:function(kind,doc){var device=xtiger.session(doc).load('pf_'+kind);if(!device){device=xtdom.createElement(doc,kind);xtdom.addClassName(device,'xtt-text-placed');xtiger.session(doc).save('pf_'+kind,device);}
return device;},getHandle:function(){return this.handle;},getValue:function(){return this.handle.value;},show:function(editor){this.handle.style.display='inline';},grab:function(editor){var _htag;this.handle.value=editor.getData();this.editorHandle=editor.getHandle();_htag=xtdom.getLocalName(this.editorHandle);if(!this.cache[_htag]){this.hook=xtdom.createElement(this.myDoc,_htag);this.cache[_htag]=this.hook;}else{this.hook=this.cache[_htag];}
var parent=this.editorHandle.parentNode;if(this.hook.firstChild!=this.handle){this.hook.appendChild(this.handle);}
parent.insertBefore(this.hook,this.editorHandle,true);parent.removeChild(this.editorHandle);},release:function(editor,willEditAgain){var parent=this.hook.parentNode;parent.insertBefore(this.editorHandle,this.hook,true);parent.removeChild(this.hook);if(!willEditAgain){this.handle.style.display='none';}}};xtiger.editor.TextDeviceFactory=function(){this.devKey='TextDeviceCache';}
xtiger.editor.TextDeviceFactory.prototype={_getCache:function(doc){var cache=xtiger.session(doc).load(this.devKey);if(!cache){cache={'input':{'float':null,'placed':null},'textarea':{'float':null,'placed':null},'filtered':{}};xtiger.session(doc).save(this.devKey,cache);}
return cache;},getInstance:function(doc,type,layout){var t=type||'input';if((t!='input')&&(t!='textarea')){xtiger.cross.log('error',"AXEL error : unkown text device type '"+t+"' requested !");t='input';}
var l=layout||'placed';if((l!='float')&&(l!='placed')){xtiger.cross.log('error',"AXEL error : unkown text device layout '"+l+"' requested !");l='float';}
var cache=this._getCache(doc);var fConstructor;var device=cache[t][l];if(!device){var wrapper=(l=='float')?new xtiger.editor.FloatingField(t,doc):new xtiger.editor.PlacedField(t,doc);device=new xtiger.editor.TextDevice(wrapper,xtiger.session(doc).load('keyboard'),doc);if(fConstructor){device.addFilter(fConstructor(doc));}
cache[t][l]=device;}
return device;}}
xtiger.registry.registerFactory('text-device',new xtiger.editor.TextDeviceFactory());})();xtiger.editor.PopupDevice=function(aDocument){this._document=aDocument;this._menu=xtiger.session(aDocument).load('popupmenu');if(!this._menu){this._menu=new xtiger.editor.PopupMenu(aDocument);xtiger.session(aDocument).save('popupmenu',this._menu);}
this._keyboard=xtiger.session(aDocument).load('keyboard');this._currentModel=null;this._keyboardHandlers=null;this._currentSelection=null;var _this=this;this.clickHandler=function(ev){_this.handleClick(ev)};}
xtiger.editor.PopupDevice.prototype={startEditing:function(aModel,aChoices,aSelection,aHandle){var coldStart=true;if(this._currentModel){this.stopEditing(true);coldStart=false;}
this._menu.setOptions(aChoices,aSelection);this._menu.setPosition(aHandle);if(coldStart){this._menu.show();xtdom.addEventListener(this._document,'mousedown',this.clickHandler,true);this._keyboardHandlers=this._keyboard.register(this,this._document);}
this._currentModel=aModel;this._currentSelection=null;},stopEditing:function(willEditAgain,isCancel){if(!this._currentModel)
return;if(!isCancel){if(this.getSelection()){if(this._currentModel.onMenuSelection)
this._currentModel.onMenuSelection(this.getSelection());else
this._currentModel.update(this.getSelection());}}
if(!willEditAgain){xtdom.removeEventListener(this._document,'mousedown',this.clickHandler,true);this._menu.hide();this._keyboard.unregister(this,this._keyboardHandlers,this._document);}
if((!isCancel)&&(this._currentModel.isOptional)&&(!this._currentModel.isSelected)){if(this._currentModel.setSelectionState)
this._currentModel.setSelectionState(true);else
this._currentModel.set();}
this._currentModel=null;},cancelEditing:function(){this.stopEditing(false,true);},isEditing:function(){return this._currentModel?true:false;},getSelection:function(){return this._currentSelection;},getHandle:function(){return this._menu.getHandle();},handleClick:function(ev){var found=false;var option=this._menu.peekEvent(ev);if(option){this._currentSelection=option;found=true;}
this.stopEditing(false,!found);xtdom.preventDefault(ev);xtdom.stopPropagation(ev);},doKeyDown:function(aEvent){switch(aEvent.keyCode){case 38:this._menu.selectPrev();break;case 40:this._menu.selectNext();break;default:}
this._currentSelection=this._menu.getSelected();},doKeyUp:function(aEvent){}}
xtiger.editor.PopupMenu=function(aDocument){this._document=aDocument;this._handle=this._createMenuForDoc(aDocument);this._handle.style.visibility='hidden';this._currentSelection=-1;this._options=null;}
xtiger.editor.PopupMenu.prototype={_createMenuForDoc:function(aDocument){var body=aDocument.getElementsByTagName('body')[0];var device=xtdom.createElement(aDocument,'ul');xtdom.addClassName(device,'xtiger-popup');body.appendChild(device);return device;},_createMenuElement:function(aOption){var _li=xtdom.createElement(this._document,'li');switch(typeof aOption){case'object':if(aOption.value&&aOption.display){_text=xtdom.createTextNode(this._document,aOption.display);_li.selectionvalue=aOption.value;_li.appendChild(_text);break;}
case'string':default:_text=xtdom.createTextNode(this._document,aOption);_li.selectionvalue=aOption;_li.appendChild(_text);}
return _li;},_setPositionXY:function(x,y){with(this._handle.style){left=x+'px';top=y+'px';}},getHandle:function(){return this._handle;},setOptions:function(aOptions,aSelection){this._currentSelection=-1;this._handle.innerHTML='';for(var _i=0;_i<aOptions.length;_i++){var _opt=this._createMenuElement(aOptions[_i]);if(aOptions[_i]==aSelection||aOptions[_i].value==aSelection){xtdom.addClassName(_opt,'selected');}
this._handle.appendChild(_opt);}},setPosition:function(aHandle){var pos=xtdom.findPos(aHandle);this._setPositionXY(pos[0],aHandle.offsetHeight+pos[1])},selectNext:function(){if(this._currentSelection!=-1)
xtdom.removeClassName(this._handle.childNodes[this._currentSelection],'selected');this._currentSelection++;this._currentSelection%=(this._handle.childNodes.length);xtdom.addClassName(this._handle.childNodes[this._currentSelection],'selected');},selectPrev:function(){if(this._currentSelection!=-1)
xtdom.removeClassName(this._handle.childNodes[this._currentSelection],'selected');else
this._currentSelection=1;this._currentSelection--;if(this._currentSelection<0)
this._currentSelection=this._handle.childNodes.length-1;xtdom.addClassName(this._handle.childNodes[this._currentSelection],'selected');},getSelected:function(){if(this._currentSelection==-1)
return false;var _sel=this._handle.childNodes[this._currentSelection];if(_sel.value)
return _sel.selectionvalue;return _sel.firstChild.data;},show:function(){this._handle.style.visibility='visible';},hide:function(){this._handle.style.visibility='hidden';},peekEvent:function(aEvent){var target=xtdom.getEventTarget(aEvent);while((target.parentNode)&&(xtdom.getLocalName(target).toUpperCase()!='LI')){target=target.parentNode;}
var _name=xtdom.getLocalName(target);if(_name&&_name.toUpperCase()=='LI'){var _options=this._handle.childNodes;for(var i=0;(i<_options.length);i++){if(_options.item(i)==target){return _options.item(i).selectionvalue;}}}
return false;}}
xtiger.editor.SelectModel=function(){}
xtiger.editor.SelectModel.prototype={getDevice:function(doc){var devKey='popupdevice';var device=xtiger.session(doc).load(devKey);if(!device){device=new xtiger.editor.PopupDevice(doc);xtiger.session(doc).save(devKey,device);}
return device;},createModel:function(container,useNode,curDoc){var viewNode=xtdom.createElement(curDoc,'span');var t=xtdom.createTextNode(curDoc,'');viewNode.appendChild(t);xtdom.addClassName(viewNode,'xtt-editable');var option=useNode.getAttribute('option');if(option){var check=xtdom.createElement(curDoc,'input');xtdom.setAttribute(check,'type','checkbox');xtdom.addClassName(check,'xtiger-option-checkbox');container.appendChild(check);}
container.appendChild(viewNode);return viewNode;},createEditorFromTree:function(handleNode,xtSrcNode,curDoc){var data=xtdom.extractDefaultContentXT(xtSrcNode);var param=xtSrcNode.getAttribute('param');var s=new xtiger.editor.SelectEditor(this);var values=xtSrcNode.getAttribute('values');var i18n=xtSrcNode.getAttribute('i18n');var _values=values?values.split(' '):'null';var _i18n=i18n?i18n.split(' '):false;s.initFromTree(handleNode,curDoc,data,param,xtSrcNode.getAttribute('option')||false,_i18n?[_i18n,_values]:_values);return s;},createEditorFromSeed:function(seed,clone,curDoc){var s=new xtiger.editor.SelectEditor(this);s.initFromSeed(seed,clone,curDoc);return s;}}
xtiger.editor.SelectEditor=function(model){this.factory=model;this.isOptional=null;this.isSelected=false;}
xtiger.editor.SelectEditor.prototype={defaultParams:{},getParam:function(name){return this.param?(this.param[name]||this.defaultParams[name]):this.defaultParams[name];},decodeParameters:function(res,params){var tokens=params.split(';');for(var i=0;i<tokens.length;i++){var p=tokens[i].split('=');if(p.length==2){var key=(p[0]=='class')?'hasClass':p[0];res[key]=p[1];}}},initFromTree:function(h,doc,userdata,parameters,option,values){this.param=null;this.handle=h;this.defaultContent=userdata;this.param={};if(parameters){this.decodeParameters(this.param,parameters)}
this.param['values']=values;if(option){this.isOptional=option.toLowerCase();}
this.awake(doc);},makeSeed:function(){if(!this.seed){this.seed=[this.factory,this.defaultContent,this.param,this.isOptional];}
return this.seed;},initFromSeed:function(seed,clone,doc){this.handle=clone;this.defaultContent=seed[1];this.param=seed[2];this.isOptional=seed[3];this.awake(doc);},awake:function(doc){this.device=this.factory.getDevice(doc);if(this.getParam('hasClass')){xtdom.addClassName(this.handle,this.getParam('hasClass'));}
var _this=this;xtdom.addEventListener(this.handle,'click',function(ev){_this.handleClick(ev)},true);this.setData(this.i18nFilter(this.defaultContent,true));if(this.isOptional){var check=this.handle.previousSibling;xtdom.addEventListener(check,'click',function(ev){_this.handleSelect(ev)},true);this.setSelectionState('set'==this.isOptional);}},isFocusable:function(){return false;},getHandle:function(){return this.handle;},load:function(point,dataSrc){if(point!==-1){var value=dataSrc.getDataFor(point);if(value){this.setData(this.i18nFilter(value,true));}
this.setSelectionState(true);}else{this.setData(this.i18nFilter(this.defaultContent,true));this.setSelectionState(false);}},save:function(logger){if((!this.isOptional)||(this.isSelected)){logger.write(this.i18nFilter(this.handle.firstChild.data,false));}else{logger.discardNodeIfEmpty();}},setData:function(value){this.handle.firstChild.data=value||this.defaultContent;},onMenuSelection:function(value){this.setData(value);xtiger.editor.Repeat.autoSelectRepeatIter(this.getHandle());},can:function(action){return false;},handleClick:function(ev){var options=this.param['values'];var _options=('string'!=typeof(options[0]))?options[0]:options;this.device.startEditing(this,_options,this.i18nFilter(this.handle.firstChild.data,true),this.getHandle());},i18nFilter:function(value,isToLabel){var selected=value;var options=this.param['values'];if('string'!=typeof(options[0])){var src=options[isToLabel?1:0];var target=options[isToLabel?0:1];for(var i=0;i<src.length;i++){if(value==src[i]){if(i<target.length){selected=target[i];}else{selected="**Error**"}
break;}}}
return selected;},setSelectionState:function(isSel){if(this.isOptional){var check=this.handle.previousSibling;this.isSelected=isSel;check.checked=isSel;if(isSel){xtdom.replaceClassNameBy(this.handle,'xtt-option-edit-unset','xtt-option-edit-set');}else{xtdom.replaceClassNameBy(this.handle,'xtt-option-edit-set','xtt-option-edit-unset');}}},handleSelect:function(ev){this.isSelected=this.handle.previousSibling.checked;if(this.isSelected){xtdom.replaceClassNameBy(this.handle,'xtt-option-edit-unset','xtt-option-edit-set');xtiger.editor.Repeat.autoSelectRepeatIter(this.getHandle());}else{xtdom.replaceClassNameBy(this.handle,'xtt-option-edit-set','xtt-option-edit-unset');}}}
xtiger.editor.Plugin.prototype.pluginEditors['select']=new xtiger.editor.SelectModel();var _WikiFilter=(function _WikiFilter(){var _markers_re="\\*|'";var _scanner=new RegExp("(http:\/\/[\\.\\w\/\\-\\?\\=_&;#]*)\\[([^\\]]*)\\]|("+_markers_re
+"){2}(.*?)\\3{2}","g");var _tagname={'html':{'Fragment':'span','FragmentKind':'class','Link':'a'},'default':{'Fragment':'Fragment','FragmentKind':'FragmentKind','Link':'Link'}}
var _markers={"em":'important',"tt":'verbatim','important':'em','verbatim':'tt',"*":'em',"'":'tt'}
var _markers2ascii={"em":'**',"tt":"''"}
var _text2html=function _text2html(str,href,anchor,marker,marked){if(href){return"<a href='"+xtiger.util.encodeEntities(href)
+"' target='_blank'>"+xtiger.util.encodeEntities(anchor)
+"</a>";}else if(marker){var tag=_markers[marker];var cl=_markers[tag];return"<"+tag+' class="'+cl+'"'+">"
+xtiger.util.encodeEntities(marked)+"</"+tag+">";}}
var _getElementChildren=function _getElementChildren(aNode){var res=[];var c=aNode.childNodes;for(var i=0;i<c.length;i++){var cur=c.item(i);if(cur.nodeType==xtdom.ELEMENT_NODE){res.push(cur);}}
return res;}
var _dumpFragment=function _dumpFragment(aBuffer,aFragment,aDocument,lang){var _cur;var _parent=aBuffer;var _content=aFragment.firstChild?aFragment.firstChild.nodeValue:'';var _type=aFragment.getAttribute(_tagname[lang]['FragmentKind']);var tag=_type?_markers[_type]:null;if(tag){_cur=xtdom.createElement(aDocument,tag);xtdom.setAttribute(_cur,'class',_type);_parent.appendChild(_cur);_parent=_cur;}
if(_parent.lastChild&&(_parent.lastChild.nodeType==xtdom.TEXT_NODE)){_parent.lastChild.appendData(_content);}else{_cur=xtdom.createTextNode(aDocument,_content);_parent.appendChild(_cur);}}
var _dumpLink=function _dumpLink(aBuffer,aLink,aDocument,lang){var linktextnode,url;if(lang=='html'){linktextnode=aLink;url=aLink.getAttribute('href');}else{var c=_getElementChildren(aLink);var name=xtdom.getLocalName(c[0]);var itext=iref=0;if(name=='LinkText'){iref=1;}else{itext=1;}
linktextnode=c[itext];url=c[iref].firstChild?c[iref].firstChild.nodeValue:'';}
var a=xtdom.createElement(aDocument,'a');var content=linktextnode.firstChild?linktextnode.firstChild.nodeValue:'url';var anchor=xtdom.createTextNode(aDocument,content);a.appendChild(anchor);a.setAttribute('href',url);aBuffer.appendChild(a);}
_dumpContent=function _dumpContent(aBuffer,aContent,aDocument,lang){var name;var c=_getElementChildren(aContent);for(var i=0;i<c.length;i++){name=xtdom.getLocalName(c[i]);if(name==_tagname[lang]['Fragment']){_dumpFragment(aBuffer,c[i],aDocument,lang);}else if(name==_tagname[lang]['Link']){_dumpLink(aBuffer,c[i],aDocument,lang);}}}
_getPopupDevice=function _getPopupDevice(aDocument){var devKey='popupdevice';var device=xtiger.session(aDocument).load(devKey);if(!device){device=new xtiger.editor.PopupDevice(aDocument);xtiger.session(aDocument).save(devKey,device);}
return device;}
return{'->':{'load':'_wikiSuperLoad','startEditing':'_wikiSuperStartEditing'},_setData:function _setData(aData){try{this.getHandle().innerHTML=xtiger.util.encodeEntities(aData).replace(_scanner,_text2html);}catch(e){xtiger.cross.log('error',"Exception "+e.name+"\n"+e.message);try{this.getHandle().innerHTML=xtiger.util.encodeEntities(aData)+" (Exception : "+e.name+" - "+e.message+")";}catch(e){}}},load:function load(aPoint,aDataSrc){if(aDataSrc.isEmpty(aPoint)){this._wikiSuperLoad(aPoint,aDataSrc);}else{var h=this.getHandle();xtdom.removeChildrenOf(h);_dumpContent(h,aPoint[0],this.getDocument(),this.getParam('wiki_lang')||'default');this.setModified(true);this.set(false);}},save:function save(aLogger){if(this.isOptional()&&!this._isOptionSet){aLogger.discardNodeIfEmpty();return;}
var name,anchor,href,tag;var lang=this.getParam('wiki_lang')||'default';var cur=this.getHandle().firstChild;while(cur){if(cur.nodeType==xtdom.ELEMENT_NODE){name=xtdom.getLocalName(cur);tag=_markers[name];if(tag){if(cur.firstChild){aLogger.openTag(_tagname[lang]['Fragment']);aLogger.openAttribute(_tagname[lang]['FragmentKind']);aLogger.write(tag);aLogger.closeAttribute(_tagname[lang]['FragmentKind']);aLogger.write(cur.firstChild.data);aLogger.closeTag(_tagname[lang]['Fragment']);}}else if(name=='a'){anchor=(cur.firstChild)?cur.firstChild.data:'null';href=cur.getAttribute('href')||'null';aLogger.openTag(_tagname[lang]['Link']);if(lang=='html'){aLogger.write(anchor);aLogger.openAttribute('href');aLogger.write(href);aLogger.closeAttribute('href');}else{aLogger.openTag('LinkText');aLogger.write(anchor);aLogger.closeTag('LinkText');aLogger.openTag('LinkRef');aLogger.write(href);aLogger.closeTag('LinkRef');}
aLogger.closeTag(_tagname[lang]['Link']);}}else{if(cur.data&&(cur.data.search(/\S/)!=-1)){aLogger.openTag(_tagname[lang]['Fragment']);aLogger.write(cur.data);aLogger.closeTag(_tagname[lang]['Fragment']);}}
cur=cur.nextSibling;}},getData:function getData(){var _name,_tag;var _txtBuffer='';var _cur=this.getHandle().firstChild;while(_cur){if(_cur.nodeType==xtdom.ELEMENT_NODE){_name=xtdom.getLocalName(_cur);_tag=_markers2ascii[_name];if(_tag){if(_cur.firstChild){_txtBuffer+=_tag+_cur.firstChild.data+_tag;}}else if(_name=='a'){_txtBuffer+=(_cur.getAttribute('href')||'')+'['+(_cur.firstChild?_cur.firstChild.data:'null')+']';}}else{_txtBuffer+=_cur.data;}
_cur=_cur.nextSibling;}
return _txtBuffer;},startEditing:function startEditing(optMouseEvent,optSelectAll){if(optMouseEvent){var _target=xtdom.getEventTarget(optMouseEvent);var _tname=xtdom.getLocalName(_target);if(/^a$/i.test(_tname)){xtdom.preventDefault(optMouseEvent);xtdom.stopPropagation(optMouseEvent);var _popupdevice=_getPopupDevice(this.getDocument());this._url=_target.getAttribute('href');if((!this._url)||(this._url==''))
this._url=_target.getAttribute('HREF');_popupdevice.startEditing(this,['edit','open'],'edit',_target)
return;}}
this._wikiSuperStartEditing(optMouseEvent,optSelectAll);},onMenuSelection:function onMenuSelection(aSelection){if(aSelection=='edit'){this._wikiSuperStartEditing();}else if(aSelection=='open'){window.open(this._url);}},setSelectionState:function setSelectionState(aState){aState?this.set():this.unset();}};})();xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('wiki',_WikiFilter);var _ImageFilter=(function _ImageFilter(){function _genImageInside(editor,src){var h=editor.getHandle();var base=editor.getParam('base');xtdom.removeChildrenOf(h);var cur=xtdom.createElement(editor.getDocument(),'img');xtdom.setAttribute(cur,'src',base?base+src:src);xtdom.setAttribute(cur,'alt','image '+src);h.appendChild(cur);}
function _getImageSrcFromHandle(editor){var url;var h=editor.getHandle();var base=editor.getParam('base');var cur=h.firstChild;if(cur.nodeType!=xtdom.TEXT_NODE){url=cur.getAttribute('src');}else{url=cur.data;}
return(base&&(url.indexOf(base)!=-1))?url.substr(base.length,url.length):url;}
function _onDragEnter(ev){var isLink=ev.dataTransfer.types.contains("text/uri-list");if(isLink){xtdom.preventDefault(ev);xtdom.stopPropagation(ev);}}
function _onDragOver(ev){xtdom.preventDefault(ev);xtdom.stopPropagation(ev);}
function _onDrop(ev){var found=false;var model=ev.target.xttPrimitiveEditor||ev.target.parentNode.xttPrimitiveEditor;if(model){var link=ev.dataTransfer.getData("URL");if(link.search(/(png|jpg|jpeg|gif)$/i)!=-1){model.update(link);}else{xtiger.cross.log('warning','Not a supported image link (must end with png, jpg, jpeg or gif) !\n');}}
xtdom.stopPropagation(ev);xtdom.preventDefault(ev);}
return{'->':{'awake':'__ImageSuperAwake','update':'__ImageSuperUpdate','_setData':'__ImageSuperSetData','load':'__ImageSuperLoad'},_setData:function(aData){if(aData.search(/(png|jpg|jpeg|gif)$/i)!=-1){_genImageInside(this,aData);}else{var h=this.getHandle();if(h.firstChild.nodeType!=xtdom.TEXT_NODE){xtdom.removeChildrenOf(h);var t=xtdom.createTextNode(this.getDocument(),'');h.appendChild(t);}
this.__ImageSuperSetData(aData);}},update:function(aData){if((aData.search(/\S/)!=-1)&&(aData!==this.getDefaultData())&&(aData.search(/(png|jpg|jpeg|gif)$/i)==-1)){this.__ImageSuperUpdate('Not a supported image file (must end with png, jpg, jpeg or gif)');}else{this.__ImageSuperUpdate(aData);}},awake:function(){this.__ImageSuperAwake()
var h=this.getHandle();xtdom.addEventListener(h,"dragenter",_onDragEnter,false);xtdom.addEventListener(h,"dragover",_onDragOver,false);xtdom.addEventListener(h,'drop',_onDrop,true);},load:function(point,dataSrc){var src;var n=point[0];src=point[0].getAttribute(this.getParam('image-tag')||'Source');if((!src)||(src.search(/(png|jpg|jpeg|gif)$/i)==-1)){this.__ImageSuperLoad(point,dataSrc);}else{_genImageInside(this,src);this.setModified(true);this.set(false);}},save:function(logger){var src=_getImageSrcFromHandle(this);logger.openAttribute(this.getParam('image-tag')||'Source');logger.write(src);logger.closeAttribute(this.getParam('image-tag')||'Source');},getData:function(){return _getImageSrcFromHandle(this);}};})();xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('image',_ImageFilter);xtiger.editor.LayoutManager=(function LayoutManager(){var _fakeDiv;var _posContainer;var _document;var _initFakeDiv=function _initFakeDiv(){_fakeDiv=xtdom.createElement(_document,'img');_fakeDiv.setAttribute('src',xtiger.bundles.lens.whiteIconURL);}
return function(aDocument){_document=aDocument;_posContainer=xtdom.createElement(aDocument,'div');xtdom.addClassName(_posContainer,'xtt-layout-container');this.getFakeDiv=function(){if(!_fakeDiv){_initFakeDiv();}
return _fakeDiv;};this.getLayoutHandle=function(){return _posContainer;};}})();xtiger.editor.LayoutManager.prototype={_getOwnPixelShiftFrom:function(aNode,aName){var style=xtdom.getComputedStyle(aNode,aName);var value=parseInt(style);return(!isNaN(value))?value:0;},_getPositionOffsets:function _getPositionOffsets(aTarget,aPadding){var _topOffset=0,_leftOffset=0;var _hmt,_hml;switch(xtdom.getComputedStyle(aTarget,'position')){case'absolute':case'fixed':break;case'relative':_topOffset=this._getOwnPixelShiftFrom(aTarget,'top');_leftOffset=this._getOwnPixelShiftFrom(aTarget,'left')
case'static':default:_hmt=this._getOwnPixelShiftFrom(aTarget,'margin-top');_hml=this._getOwnPixelShiftFrom(aTarget,'margin-left');_topOffset+=_hmt>0?_hmt:0;_leftOffset+=_hml>0?_hml:0;_topOffset-=aPadding;_leftOffset-=aPadding;}
return[_leftOffset,_topOffset];},_configureAndGetContainerFor:function _configureAndGetContainerFor(aSrcHandle,aPadding){var mhDisplay,_offsets;var _pos=this.getLayoutHandle();_mhDisplay=xtdom.getComputedStyle(aSrcHandle,'display');_mhDisplay=(/^block$|^inline$/.test(_mhDisplay))?_mhDisplay:'block';_pos.style.display=_mhDisplay;_offsets=this._getPositionOffsets(aSrcHandle,aPadding);_pos.style.left=''+_offsets[0]+'px';return _pos;},_confirmInsertion:function(aModelHandle){var doIt=(!this.curHandle)||(this.curHandle!=aModelHandle);if(this.curHandle&&(this.curHandle!=aModelHandle)){this.restoreHandle();}
return doIt;},insertAbove:function(aModelHandle,aLensContent,aPadding,aGrabCallback){var container;if(this._confirmInsertion(aModelHandle)){container=this._configureAndGetContainerFor(aModelHandle,aPadding);aModelHandle.parentNode.insertBefore(container,aModelHandle);container.appendChild(aLensContent);if(aGrabCallback)
aGrabCallback();this.curDisplay='above';this.curHandle=aModelHandle;this.curLensContent=aLensContent;}},insertInline:function(aModelHandle,aLensContent,aPadding,aGrabCallback){var img,container,bbox,w,h;if(this._confirmInsertion(aModelHandle)){img=this.getFakeDiv();container=this._configureAndGetContainerFor(aModelHandle,aPadding);aModelHandle.parentNode.replaceChild(img,aModelHandle);img.parentNode.insertBefore(container,img);container.appendChild(aLensContent);if(aGrabCallback)
aGrabCallback();bbox=aLensContent.getBoundingClientRect();w=bbox?(bbox.right-bbox.left):0;h=bbox?(bbox.bottom-bbox.top):0;img.style.width=w+'px';img.style.height=h+'px';this.curDisplay='inline';this.curHandle=aModelHandle;this.curLensContent=aLensContent;}},restoreHandle:function(){var img;if(this.curHandle){if(this.curDisplay=='inline'){img=this.getFakeDiv();img.parentNode.replaceChild(this.curHandle,img);}else{this.curHandle.style.visibility='visible';}
xtdom.removeElement(this.curLensContent);xtdom.removeElement(this.getLayoutHandle());this.curHandle=this.curDisplay=this.curLensContent=undefined;}}}
xtiger.editor.LensDevice=function(aDocument){var _document=aDocument;var _keyboard=xtiger.session(aDocument).load('keyboard');var _currentModel;var _currentLCW;var _lensView;var _layoutManager;var _defaultParams={trigger:'click',display:'above',padding:"10px"};var _checkMouseReturn=false;var _keepAlive=false;var _this=this;var _dismissHandlers={'click':['click',function(ev){_this._onClick(ev)}],'mouseover':['mousemove',function(ev){_this._onMouseMove(ev)}]};var _getParam=function(name,aModel){return(aModel.getParam&&aModel.getParam(name))||_defaultParams[name];};var _getLayoutManager=function(){if(!_layoutManager){_layoutManager=new xtiger.editor.LayoutManager(_document);}
return _layoutManager;};var _getWrapperFor=function(aName){var w=xtiger.factory('lens').getWrapper(_document,aName);if(!w){xtiger.cross.log('warning','Missing wrapper "'+aWrapperName+'" in lens device, startEditing aborted')}
return w;};var _grabWrapper=function(aDeviceLens,aWrapperName,doSelect){try{_currentLCW.grab(aDeviceLens,doSelect);}catch(e){xtiger.cross.log('error ( '+e.message+' ) "',aWrapperName+'" failed to grab the lens device, startEditing compromised');}};var _terminate=function(that,doUpdateModel){if(!that.isEditing())
return;if(_currentLCW.isFocusable()){_keyboard.unregister(that,that._handlers);}
_getLayoutManager().restoreHandle();var mode=_getParam('trigger',_currentModel);if(_dismissHandlers[mode]){xtdom.removeEventListener(_document,_dismissHandlers[mode][0],_dismissHandlers[mode][1],true);_checkMouseReturn=false;}
if(doUpdateModel){_currentModel.update(_currentLCW.getData());}
_currentLCW.release();_currentModel=null;_currentLCW=null;_lensView=null;};this.startEditing=function startEditing(aModel,aWrapperName,aDoSelect){var display,padding,mode;var doSelect=aDoSelect?true:false;if(this.isEditing())
this.stopEditing();_currentLCW=_getWrapperFor(aWrapperName);if(_currentLCW){_currentModel=aModel;if(_currentLCW.isFocusable()){this._handlers=_keyboard.register(this);_keyboard.grab(this,aModel);}
padding=_getParam('padding',aModel).match(/\d*/)[0];padding=(padding&&padding!='')?parseInt(padding):10;_lensView=_currentLCW.getHandle();display=_getParam('display',_currentModel)
if(display=='above'){_getLayoutManager().insertAbove(_currentModel.getHandle(),_lensView,padding,function(){_grabWrapper(_this,aWrapperName,doSelect)});}else if(display=='inline'){_getLayoutManager().insertInline(_currentModel.getHandle(),_lensView,padding,function(){_grabWrapper(_this,aWrapperName,doSelect)});}else{xtiger.cross.log('error','unkown display "'+display+'" in lens device, startEditing compromised');}
mode=_getParam('trigger',aModel);if(_dismissHandlers[mode]){xtdom.addEventListener(_document,_dismissHandlers[mode][0],_dismissHandlers[mode][1],true);_checkMouseReturn=false;}else{xtiger.cross.log('error','unkown trigger mode "'+mode+'" in lens device, startEditing compromised');}}};this.stopEditing=function stopEditing(){_terminate(this,true);};this.cancelEditing=function cancelEditing(){_terminate(this,false);};this.isEditing=function isEditing(){return _currentModel?true:false;};this.getHandle=function getHandle(){if(_currentLCW)
return _currentLCW.getHandle();return null;};this.getCurrentModel=function getCurrentModel(){if(_currentModel)
return _currentModel;return null;};this.keepAlive=function keepAlive(aAlive){_keepAlive=aAlive;};this._onClick=function(ev){if(_keepAlive)
return;var outside=true;var target=xtdom.getEventTarget(ev);while(target.parentNode){if(target==_lensView){outside=false;break;}
target=target.parentNode;}
if(outside){this.stopEditing();}};this._onMouseMove=function(ev){if(_keepAlive)
return;var _mouseX=ev.clientX;var _mouseY=ev.clientY;var _bb=_lensView.getBoundingClientRect();if(_checkMouseReturn){if(!(_bb.left>_mouseX||_bb.top>_mouseY||_bb.right<=_mouseX||_bb.bottom<=_mouseY)){_checkMouseReturn=false;}}else if(_bb.left>_mouseX||_bb.top>_mouseY||_bb.right<=_mouseX||_bb.bottom<=_mouseY){this.stopEditing();xtdom.stopPropagation(ev);}}
this.doKeyUp=function doKeyUp(ev){};this.doKeyDown=function doKeyDown(ev){if(!this.isEditing())
return;if(ev.keyCode=="38"||ev.keyCode=="40")
_currentLCW.toggleField();if(ev.keyCode=="27")
this.cancelEditing();xtdom.stopPropagation(ev);};this.mouseMayLeave=function mouseMayLeave(){_checkMouseReturn=true;};}
xtiger.editor.LensDeviceFactory=function(){this.devKey='LensDeviceCache';this.wrappers={};}
xtiger.editor.LensDeviceFactory.prototype={_getCache:function(doc){var cache=xtiger.session(doc).load(this.devKey);if(!cache){cache={'device':null,'wrappers':{}};xtiger.session(doc).save(this.devKey,cache);}
return cache;},registerWrapper:function(aKey,aWrapperFactory){if(this.wrappers[aKey]){xtiger.cross.log('error',"Error (AXEL) attempt to register an already registered wrapper : '"+aKey+"' with 'lens' device !");}else{this.wrappers[aKey]=aWrapperFactory;}},getWrapper:function(aDocument,aKey){var cache=this._getCache(aDocument);var wrapper=cache['wrappers'][aKey];if(!wrapper){var wConstructor=this.wrappers[aKey];if(wConstructor){wrapper=cache['wrappers'][aKey]=wConstructor(aDocument);}}
if(!wrapper){xtiger.cross.log('error',"Error (AXEL) : unkown wrapper '"+aKey+"' requested in 'lens' device !");}
return wrapper;},getInstance:function(aDocument){var cache=this._getCache(aDocument);var device=cache['device'];if(!device){device=cache['device']=new xtiger.editor.LensDevice(aDocument);}
return device;}}
xtiger.resources.addBundle('lens',{'whiteIconURL':'white.png'});xtiger.registry.registerFactory('lens',new xtiger.editor.LensDeviceFactory());xtiger.editor.LinkFactory=(function LinkFactory(){var _deviceFactories={};var _LinkModel=function(aHandleNode,aDocument){var _DEFAULT_PARAMS={defaultText:'enter link\'s text here',defaultUrl:'http://',defaultDevice:'lens',wrapper:'togglewrapper',linkRefTagName:"linkRef",linkTextTagName:"linkText",trigger:"click",padding:'10'};this._handle=aHandleNode;this._data={text:_DEFAULT_PARAMS['defautText'],url:_DEFAULT_PARAMS['defautUrl']}
this._defaultData=this._data;this._document=aDocument;this._params=_DEFAULT_PARAMS;this._isOptional=false;this._isOptionSet=false;this._optCheckBox;this._device=null;this._seed=null;this._isModified=false;this._uniqueKey;this.create();};_LinkModel.prototype={_setData:function(aText,aUrl){this._data={text:aText,url:aUrl};this._handle.firstChild.data=aText;},create:function(){},init:function(aDefaultData,aParams,aOption,aUniqueKey,aRepeater){if(aParams){if(typeof(aParams)=='string')
xtiger.util.decodeParameters(aParams,this._params);else if(typeof(aParams)=='object')
this._params=aParams;}
if(aDefaultData&&aDefaultData.text&&aDefaultData.url){this._setData(aDefaultData.text,aDefaultData.url);this._defaultData=aDefaultData;}
if(aOption){this._isOptional=true;this._optCheckBox=this._handle.nextSibling;(aOption=='set')?this.set():this.unset();}
this._uniqueKey=aUniqueKey;var _deviceFactory=this._params['device']?xtiger.factory(this._params['device']):xtiger.factory(this._params['defaultDevice']);this._device=_deviceFactory.getInstance(this._document);this.awake();},makeSeed:function(){if(!this._seed)
this._seed=[xtiger.editor.LinkFactory,this._defaultData,this._params,this._isOptional];return this._seed;},can:function(aFunction){return typeof this[aFunction]=='function';},execute:function(aFunction,aParam){return this[aFunction](aParam);},load:function(aPoint,aDataSrc){var _url,_text;try{_url=aDataSrc.getDataFor(aDataSrc.getVectorFor('linkRef',aPoint));_text=aDataSrc.getDataFor(aDataSrc.getVectorFor('linkText',aPoint));}
catch(_err){tiger.cross.log('warning','Unable to load the link editor with the following content :\n text='+_text+', url='+_url);}
if(this.isOptional()){if(_url||_text)
this.set();else
this.unset();}
if(!_url)
_url=this._defaultData.url;if(!_text)
_text=this._defaultData.text;this._setData(_text,_url);},save:function(aLogger){if(this.isOptional()&&!this._isOptionSet){aLogger.discardNodeIfEmpty();return;}
var _data=this.getData();aLogger.openTag(this._params['linkRefTagName']);aLogger.write(_data.url);aLogger.closeTag(this._params['linkRefTagName']);aLogger.openTag(this._params['linkTextTagName']);aLogger.write(_data.text);aLogger.closeTag(this._params['linkTextTagName']);},update:function(aData){if(aData.text==this._data.text&&aData.url==this._data.url)
return;this._setData(aData.text,aData.url);this._isModified=true;if(this.isOptional()&&!this._isOptionSet)
this.set();},clear:function(){this._setData(this._defaultData.text,this._defaultData.url);this._isModified=false;if(this.isOptional()&&this.isSet())
this.unset();},getData:function(){return this._data;},getDefaultData:function(){return this._defaultData;},getHandle:function(){return this._handle;},getDocument:function(){return this._document;},getParam:function(aKey){return this._params[aKey];},getUniqueKey:function(){return this._uniqueKey;},isModified:function(){return this._isModified;},setModified:function(isModified){this._idModified=isModified;},isOptional:function(){return this._isOptional;},isSet:function(){return this._isOptional&&(this._isOptionSet?true:false);},set:function(){if(!this._isOptional)
return;xtdom.removeClassName(this._handle,'xtt-option-edit-unset');xtdom.addClassName(this._handle,'xtt-option-edit-set');this._isOptionSet=true;this._optCheckBox.checked=true;xtiger.editor.Repeat.autoSelectRepeatIter(this.getHandle());},unset:function(){if(!this._isOptional)
return;xtdom.removeClassName(this._handle,'xtt-option-edit-set');xtdom.addClassName(this._handle,'xtt-option-edit-unset');this._isOptionSet=false;this._optCheckBox.checked=false;},isFocusable:function(){return true;},focus:function(){this.startEditing(null);},unfocus:function(){this.stopEditing();},awake:function(){var _this=this;if(this.isOptional()){xtdom.addEventListener(this._optCheckBox,'click',function(ev){_this.onToggleOpt(ev);},true);}
xtdom.addEventListener(this._handle,this._params['trigger'],function(ev){_this.startEditing(ev);},true);},startEditing:function(aEvent){var _doSelect=aEvent?(!this._isModified||aEvent.shiftKey):false;this._device.startEditing(this,'linkLensWrapper',_doSelect);},stopEditing:function(){this._device.stopEditing();},onToggleOpt:function(ev){this._isOptionSet?this.unset():this.set();}};var _BASE_KEY='link';var _keyCounter=0;return{createModel:function createModel(aContainer,aXTUse,aDocument)
{var _h=xtdom.createElement(aDocument,'span');xtdom.addClassName(_h,'xtt-on');xtdom.addClassName(_h,'xtt-editable');xtdom.addClassName(_h,'xtt-link');_h.appendChild(xtdom.createTextNode(aDocument,''));aContainer.appendChild(_h);var _optional=aXTUse.getAttribute('option');if(_optional){var _checkbox=xtdom.createElement(aDocument,'input');xtdom.setAttribute(_checkbox,'type','checkbox');xtdom.addClassName(_checkbox,'xtiger-option-checkbox');aContainer.appendChild(_checkbox);}
return _h;},registerDeviceFactory:function registerDeviceFactory(aKey,aFactory){if(_deviceFactories[aKey])
return false;_deviceFactories[aKey]=aFactory;return true;},getDeviceFactory:function(aKey){return _deviceFactories[aKey];},getDevice:function(aWrapper){},createEditorFromTree:function createEditorFromTree(aHandleNode,aXTUse,aDocument){var _model=new _LinkModel(aHandleNode,aDocument);var _defaultData;var _aXTContent=aXTUse.childNodes;switch(_aXTContent.length){case 2:if(_aXTContent[0].nodeType==xtdom.ELEMENT_NODE&&_aXTContent[1].nodeType==xtdom.ELEMENT_NODE&&_aXTContent[0].nodeName=='linkText'&&_aXTContent[1].nodeName=='linkRef')
_defaultData={text:_aXTContent.childNodes[0].nodeValue,url:_aXTContent.childNodes[1].nodeValue};break;case 1:if(_aXTContent[0].nodeType==xtdom.ELEMENT_NODE&&(/^a$/i).test(_aXTContent[0].nodeName)){_defaultData={text:_aXTContent[0].firstChild.nodeValue,url:_aXTContent[0].getAttribute('href')};}else if(_aXTContent[0].nodeType==xtdom.TEXT_NODE){_defaultData={text:_aXTContent[0].nodeValue,url:'http://'};}
break;default:_defaultData={text:'link',url:'http://'}}
var _params={};xtiger.util.decodeParameters(aXTUse.getAttribute('param'),_params);if(_params['filter'])
_model=this.applyFilters(_model,_params['filter']);_model.init(_defaultData,aXTUse.getAttribute('param'),aXTUse.getAttribute('option'),this.createUniqueKey());return _model;},createEditorFromSeed:function createEditorFromSeed(aSeed,aClone,aDocument,aRepeater){var _model=new _LinkModel(aClone,aDocument);var _defaultData=aSeed[1];var _param=aSeed[2];var _option=aSeed[3];if(_param['filter'])
_model=this.applyFilters(_model,_param['filter']);_model.init(_defaultData,_param,_option,this.createUniqueKey(),aRepeater);return _model;},createUniqueKey:function createUniqueKey(){return _BASE_KEY+(_keyCounter++);}};})();xtiger.editor.Plugin.prototype.pluginEditors['link']=xtiger.util.filterable('link',xtiger.editor.LinkFactory);var _LinkLensWrapper=function(aDocument){this._handle;this._handleToRestore;this._document=aDocument;this._isFocused=false;this.build();};_LinkLensWrapper.prototype={build:function(){this._topDiv=xtdom.createElement(this._document,'div');xtdom.addClassName(this._topDiv,'xtt-lens');xtdom.addClassName(this._topDiv,'xtt-lensstyle');with(this._topDiv){style['display']='none';}
var _buf='';_buf+='<p style="margin: 0 0 15px 0; padding: 0; width: 100%>';_buf+='';this._upperP=xtdom.createElement(this._document,'p');with(this._upperP){style['margin']='0 0 15px 0';style['padding']='0px';style['width']='100%';}
this._anchorInput=xtdom.createElement(this._document,'input');with(this._anchorInput){type='text';}
xtdom.addClassName(this._anchorInput,'xtt-link');this._upperP.appendChild(this._anchorInput);this._topDiv.appendChild(this._upperP);this._lowerP=xtdom.createElement(this._document,'p');with(this._lowerP){style['margin']='0px';style['padding']='0px';style['width']='100%';}
this._urlInput=xtdom.createElement(this._document,'input');with(this._urlInput){style['width']='75%';}
this._goButtonLink=xtdom.createElement(this._document,'a');with(this._goButtonLink){href='';target='_blank';style['margin']='0 10px';style['width']='25%';}
this._goButton=xtdom.createElement(this._document,'img');with(this._goButton){src=xtiger.bundles.link.gotoURL;style.height='20px';style.width='30px';style.display='inline';style['verticalAlign']='bottom';}
this._goButtonLink.appendChild(this._goButton);this._lowerP.appendChild(this._urlInput);this._lowerP.appendChild(this._goButtonLink);this._topDiv.appendChild(this._lowerP);},grab:function(aDevice,aDoSelect){this._currentDevice=aDevice;var _data=this._currentDevice.getCurrentModel().getData();this.setData(_data.text,_data.url);var _handle=this._currentDevice.getCurrentModel().getHandle();var _pad=this._currentDevice.getCurrentModel().getParam('padding');with(this._topDiv){style.display='block';style.padding=_pad+'px';}
if(aDoSelect)
this.selectText(this._anchorInput);var _this=this;xtdom.addEventListener(this._anchorInput,'focus',function(ev){_this.onFocus(ev)},false);xtdom.addEventListener(this._urlInput,'focus',function(ev){_this.onFocus(ev)},false);xtdom.addEventListener(this._anchorInput,'blur',function(ev){_this.onBlur(ev)},false);xtdom.addEventListener(this._urlInput,'blur',function(ev){_this.onBlur(ev)},false);},release:function(){this._isFocused=false;xtdom.removeElement(this._topDiv);this._currentDevice=null;},getHandle:function(){return this._topDiv;},selectText:function(aField,aStartPos,aEndPos){if(aStartPos!=null&&aEndPos!=null){var _aStartPos=aStartPos;var _aEndPos=aEndPos;}
else{var _aStartPos=0;var _aEndPos=aField.value.length;}
try{if(aField.setSelectionRange){aField.setSelectionRange(_aStartPos,_aEndPos);}else if(aField.createTextRange){var oRange=aField.createTextRange();aField.moveStart("character",_aStartPos);aField.moveEnd("character",_aEndPos);aField.select();}
aField.focus();}catch(err){xtiger.cross.log('warning','Cannot select text');}},toggleField:function(){if(!this._isFocused)
return;if(this._focusedField==this._anchorInput){this._anchorInput.blur();this.selectText(this._urlInput);}else{this._urlInput.blur();this.selectText(this._anchorInput);}},getData:function(){return{url:this._urlInput.value,text:this._anchorInput.value}},setData:function(aText,aUrl){if(aText&&typeof(aText)=='string')
this._anchorInput.value=aText;if(aUrl&&typeof(aUrl)=='string'){this._urlInput.value=aUrl;this._goButtonLink.href=aUrl;}},reset:function(){},isFocusable:function(){return true;},onMouseOut:function(ev){if(!this._currentDevice)
return;if(this._isFocused)
return;var _mouseX=ev.clientX;var _mouseY=ev.clientY;var _bb=this._topDiv.getBoundingClientRect();if(_bb.left>_mouseX||_bb.top>_mouseY||_bb.right<=_mouseX||_bb.bottom<=_mouseY){this._currentDevice.onMouseOut(ev);}},onBlur:function(ev){var _target=xtdom.getEventTarget(ev);if(_target==this._urlInput)
this._goButtonLink.href=this._urlInput.value;this._isFocused=false;this._focusedField=null;this._currentDevice.keepAlive(false);},onFocus:function(ev){this._isFocused=true;this._currentDevice.keepAlive(true);this._focusedField=xtdom.getEventTarget(ev);},onMouseMove:function(ev){this.onMouseOut(ev);var _this=this;}};xtiger.resources.addBundle('link',{'gotoURL':'goto.png'});xtiger.factory('lens').registerWrapper('linkLensWrapper',function(aDocument){return new _LinkLensWrapper(aDocument)});xtiger.editor.RichTextFactory=(function RichTextFactory(){var _RichTextModel=function(aHandleNode,aDocument){var _DEFAULT_PARAMS={defaultDevice:'lens',trigger:"click",padding:'10'};this._handle=aHandleNode;this._data={}
this._updateFilter=['br','p','span','i','u','b','strong','em','a','font'];this._defaultData=this._data;this._document=aDocument;this._params=_DEFAULT_PARAMS;this._isOptional=false;this._isOptionSet=false;this._optCheckBox;this._device=null;this._seed=null;this._isModified=false;this._uniqueKey;this.create();};_RichTextModel.prototype={_setData:function(aData){this._handle.innerHTML=aData;this._treeFilter(this._handle,this._updateFilter);this._removeTrailingBRNodes(this._handle,true);},_sanitizeAttribute:function(aString){var _san=aString.replace(/"/g,'\'');_san=_san.replace(/&(?!\w{3,6};)/g,'&amp;');return _san;},_treeFilter:function(aNode,aFilter,doRecursion){if(!aNode||!aFilter)
return aNode;if(doRecursion!==false)
doRecursion=true;try{var _cur=aNode.firstChild;while(_cur){var _next=_cur.nextSibling;if(_cur.nodeType==xtdom.ELEMENT_NODE){if(doRecursion)
this._treeFilter(_cur,aFilter,doRecursion);var _isFound=false;for(var _f in aFilter)
if((aFilter[_f]).toLowerCase()==(_cur.nodeName).toLowerCase()){_isFound=true;break;}
if(!_isFound){var _curChild=_cur.firstChild;var _lastChild=_curChild;while(_curChild){var _nextChild=_curChild.nextSibling;aNode.insertBefore(_curChild,_cur);_curChild=_nextChild;}
xtdom.removeElement(_cur);}}
_cur=_next;}}catch(err){console.warn('(richtext.js: '+err.lineNumber+') Problem in tree conversion: '+err.message);return aNode;}},_removeTrailingBRNodes:function(aNode,isRecursive){if(!aNode||!aNode.lastChild)
return false;var _modified=false;for(var _i=aNode.childNodes.length-1;_i>=0;_i--){if(aNode.childNodes[_i].nodeName.toLowerCase()=='br'){xtdom.removeElement(aNode.childNodes[_i]);_modified=true;}
else{if(isRecursive===true)
return this._removeTrailingBRNodes(aNode.childNodes[_i],true);return _modified;}}},_saveData:function(aNode,aLogger){var _cur=aNode.childNodes[0];var _hasElement=false;var _doNext=true;while(_cur){_doNext=true;switch(_cur.nodeType){case xtdom.ELEMENT_NODE:_hasElement=true;var _sName=_cur.nodeName;var _styleAttr=null;switch(_sName){case'b':case'B':case'STRONG':_sName='span';_styleAttr='font-weight: bold';break;case'i':case'I':case'EM':_sName='span';_styleAttr='font-style: italic';break;case'u':case'U':_sName='span';_styleAttr='text-decoration: underline';break;}
aLogger.openTag(_sName.toLowerCase());if(_cur.attributes.length){for(var _i=0;_i<_cur.attributes.length;_i++){if(_cur.attributes[_i].nodeName=='_moz_dirty'||_cur.attributes[_i].nodeName=='xmlns'||(!_cur.attributes[_i].specified&&xtiger.cross.UA.IE))
continue;aLogger.openAttribute(_cur.attributes[_i].nodeName);if(_cur.attributes[_i].nodeName=='style'&&xtiger.cross.UA.IE)
aLogger.write(this._sanitizeAttribute(_cur.style.cssText.toLowerCase()));else
aLogger.write(this._sanitizeAttribute(_cur.getAttribute(_cur.attributes[_i].nodeName)));aLogger.closeAttribute(_cur.attributes[_i].nodeName);}}
if(_styleAttr){aLogger.openAttribute('style');aLogger.write(_styleAttr);aLogger.closeAttribute('style');}
this._saveData(_cur,aLogger);aLogger.closeTag(_sName.toLowerCase());break;case xtdom.TEXT_NODE:if(!_cur.nodeValue.match(/\S/)&&_cur.nodeValue!=' ')
break;var _text_buffer='';while(_cur&&_cur.nodeType==xtdom.TEXT_NODE){_text_buffer+=_cur.nodeValue;_cur=_cur.nextSibling;_doNext=false;}
if(_hasElement||_cur)
aLogger.openTag('span');_text_buffer=_text_buffer.replace(/&(?!\w{3,5};)/g,'&amp;');aLogger.write(_text_buffer);if(_hasElement||_cur)
aLogger.closeTag('span');break;default:}
if(_cur&&_doNext)
_cur=_cur.nextSibling;}},_loadData:function(aPoint,aDataSrc,aInsertPoint){if(aDataSrc.isEmpty(aPoint))
return;if(aPoint instanceof Array&&aPoint.length==2&&aPoint[1].nodeType==xtdom.TEXT_NODE){aInsertPoint.appendChild(xtdom.createTextNode(this._document,xtdom.getTextContent(aPoint[1])));}else if(aPoint instanceof Array&&aPoint.length==2&&typeof(aPoint[1])=='string'){aInsertPoint.appendChild(xtdom.createTextNode(this._document,aPoint[1]));}else if(aPoint instanceof Array&&aPoint.length>=2){for(var _i=1;_i<aPoint.length;_i++){if(aPoint[_i].nodeType==xtdom.TEXT_NODE)
continue;var _nodeName=xtdom.getLocalName(aPoint[_i]);switch(_nodeName){case'span':if(aPoint[_i].attributes.length==0){aInsertPoint.appendChild(xtdom.createTextNode(this._document,xtdom.getTextContent(aPoint[_i])));break;}
if(xtiger.cross.UA.IE||xtiger.cross.UA.opera){var _style=xtdom.getStyleAttribute(aPoint[_i]);if(_style&&_style!=''){var _tokens=_style.split(';');var _newNode;var _insertPoint;var _otherStyles='';for(var _j=0;_j<_tokens.length;_j++){switch(_tokens[_j]){case'font-weight: bold':_newNode=xtdom.createElement(this._document,'strong');if(_insertPoint)
_insertPoint.appendChild(_newNode);_insertPoint=_newNode;break;case'font-style: italic':_newNode=xtdom.createElement(this._document,'em');if(_insertPoint)
_insertPoint.appendChild(_newNode);_insertPoint=_newNode;break;case'text-decoration: underline':_newNode=xtdom.createElement(this._document,'u');if(_insertPoint)
_insertPoint.appendChild(_newNode);_insertPoint=_newNode;break;default:if(/\S/.test(_tokens[_j]))
_otherStyles+=_tokens[_j]+';';}}
if(_otherStyles!=''){_newNode=xtdom.createElement(this._document,'span');if(xtiger.cross.UA.IE)
_newNode.style.setAttribute('cssText',_otherStyles);else
_newNode.setAttribute('style',_otherStyles)
if(_insertPoint)
_insertPoint.appendChild(_newNode);_insertPoint=_newNode;}
for(var _k=0;_k<aPoint[_i].attributes.length;_k++){if(aPoint[_i].attributes[_k].nodeName!='style')
_newNode.setAttribute(aPoint[_i].attributes[_k].nodeName,aPoint[_i].attributes[_k].nodeValue);}
var _newVector=[null];for(var _l=0;_l<aPoint[_i].childNodes.length;_l++){_newVector.push(aPoint[_i].childNodes[_l]);}
this._loadData(_newVector,aDataSrc,_newNode);aInsertPoint.appendChild(_newNode);break;}}
default:var _newNode=xtdom.createElement(this._document,_nodeName);for(var _k=0;_k<aPoint[_i].attributes.length;_k++){_newNode.setAttribute(aPoint[_i].attributes[_k].nodeName,aPoint[_i].attributes[_k].nodeValue);}
var _newVector=[null];for(var _j=0;_j<aPoint[_i].childNodes.length;_j++){_newVector.push(aPoint[_i].childNodes[_j]);}
this._loadData(_newVector,aDataSrc,_newNode);aInsertPoint.appendChild(_newNode);}}}},create:function(){},init:function(aDefaultData,aParams,aOption,aUniqueKey,aRepeater){if(aParams){if(typeof(aParams)=='string')
xtiger.util.decodeParameters(aParams,this._params);else if(typeof(aParams)=='object')
this._params=aParams;}
if(aDefaultData){try{this._setData(aDefaultData);this._defaultData=aDefaultData;}
catch(_err){xtiger.cross.log('warning','Unable to init the rich text editor with the following content :\n'+aData);}}
if(aOption){this._isOptional=true;this._optCheckBox=this._handle.previousSibling;(aOption=='set')?this.set():this.unset();}
this._uniqueKey=aUniqueKey;var _deviceFactory=this._params['device']?xtiger.factory(this._params['device']):xtiger.factory(this._params['defaultDevice']);if(_deviceFactory)
this._device=_deviceFactory.getInstance(this._document);else
xtiger.cross.log('warning','no device for this editor '+this);this.awake();},makeSeed:function(){if(!this._seed)
this._seed=[xtiger.editor.RichTextFactory,this._defaultData,this._params,this._isOptional];return this._seed;},can:function(aFunction){return typeof this[aFunction]=='function';},execute:function(aFunction,aParam){return this[aFunction](aParam);},load:function(aPoint,aDataSrc){var _buffer=xtdom.createElement(this._document,'div');var _prevState=_buffer.innerHTML;try{this._loadData(aPoint,aDataSrc,_buffer);this._setData(_buffer.innerHTML);}catch(_err){xtiger.cross.log('error','Richtext.js : failed to load data : '+_err.message);}
if(_buffer.innerHTML==_prevState&&this.isOptional())
this.unset();if(_buffer.innerHTML!=_prevState&&this.isOptional())
this.set();},save:function(aLogger){aLogger.openAttribute('xml:space');aLogger.write('preserve');aLogger.closeAttribute('xml:space');if(this.isOptional()&&!this._isOptionSet){aLogger.discardNodeIfEmpty();return;}
this._saveData(this._handle,aLogger)},update:function(aData){if(this._data==aData)
return;if(!aData||aData.search(/\S/)==-1||(aData==this._defaultData)){this.clear(true);return;}
var _newData=aData;_newData=_newData.replace(/<br>/ig,'<br/>');_newData=_newData.replace(/<br\/>/gi,'<br></br>');try{this._setData(_newData);if(xtdom.getTextContent(this._handle).search(/\S/)==-1){this.clear(true);return;}
this._isModified=true;this.set(true);}catch(_err){xtiger.cross.log('warning','Unable to update the rich text editor with the following content :\n'+aData);}},clear:function(doPropagate){for(var i=this._handle.childNodes.length;i>0;i--){this._handle.removeChild(this._handle.childNodes[i-1]);}
this._setData(this._defaultData);this._isModified=false;if(this.isOptional()&&this.isSet())
this.unset(doPropagate);},getData:function(){return this._handle.innerHTML.replace(/^\s+|\s+$/g,'');},getDefaultData:function(){return this._defaultData;},getHandle:function(){return this._handle;},getDocument:function(){return this._document;},getParam:function(aKey){return this._params[aKey];},getUniqueKey:function(){return this._uniqueKey;},isModified:function(){return this._isModified;},setModified:function(isModified){this._idModified=isModified;},isOptional:function(){return this._isOptional;},isSet:function(){return this._isOptional&&(this._isOptionSet?true:false);},set:function(doPropagate){if(doPropagate){xtiger.editor.Repeat.autoSelectRepeatIter(this.getHandle(true));xtdom.removeClassName(this._handle,'xtt-repeat-unset');}
if(this._isOptionSet)
return;this._isOptionSet=true;if(this._isOptional){xtdom.removeClassName(this._handle,'xtt-option-edit-unset');xtdom.addClassName(this._handle,'xtt-option-edit-set');this._optCheckBox.checked=true;}},unset:function(){if(!this._isOptional)
return;xtdom.removeClassName(this._handle,'xtt-option-edit-set');xtdom.addClassName(this._handle,'xtt-option-edit-unset');this._isOptionSet=false;this._optCheckBox.checked=false;},isFocusable:function(){return true;},focus:function(aSet){if(this._isOptional&&aSet&&!this._isOptionSet)
this.set();this._handle.focus();this.startEditing();},unfocus:function(){this._handle.blur();this.stopEditing();},awake:function(){var _devName=this.getParam('device');var _this=this;xtdom.addEventListener(this._handle,this._params['trigger'],function(ev){if(_this._isOptional&&!_this._isOptionSet)
_this.set();_this.startEditing(ev);xtdom.stopPropagation(ev);},true);if(this.isOptional()){xtdom.addEventListener(this._optCheckBox,'click',function(ev){_this.onToggleOpt(ev);},true);}},startEditing:function(aEvent){var _doSelect=aEvent?(!this._isModified||aEvent.shiftKey):false;this._device.startEditing(this,'richtextwrapper',_doSelect);},stopEditing:function(){this._device.stopEditing();},onToggleOpt:function(ev){this._isOptionSet?this.unset():this.set();}};var _BASE_KEY='richtext';var _keyCounter=0;return{createModel:function createModel(aContainer,aXTUse,aDocument){var _params={};xtiger.util.decodeParameters(aXTUse.getAttribute('param'),_params);switch(_params['display']){case'inline':var _content=xtdom.createElement(aDocument,'span');break;case'single':var _content=xtdom.createElement(aDocument,'p');break;default:var _content=xtdom.createElement(aDocument,'div');}
xtdom.addClassName(_content,'xtt-on');xtdom.addClassName(_content,'xtt-editable');var _optional=aXTUse.getAttribute('option');if(_optional){var _checkbox=xtdom.createElement(aDocument,'input');xtdom.setAttribute(_checkbox,'type','checkbox');xtdom.addClassName(_checkbox,'xtiger-option-checkbox');aContainer.appendChild(_checkbox);}
aContainer.appendChild(_content);return _content;},createEditorFromTree:function createEditorFromTree(aHandleNode,aXTUse,aDocument){var _model=new _RichTextModel(aHandleNode,aDocument);var _buffer=xtdom.createElement(aDocument,'div');var _cur=aXTUse.firstChild;while(_cur){var _next=_cur.nextSibling;_buffer.appendChild(_cur);_cur=_next;}
var _params={};xtiger.util.decodeParameters(aXTUse.getAttribute('param'),_params);if(_params['filter'])
_model=this.applyFilters(_model,_params['filter']);_model.init(_buffer.innerHTML,aXTUse.getAttribute('param'),aXTUse.getAttribute('option'),this.createUniqueKey());return _model;},createEditorFromSeed:function createEditorFromSeed(aSeed,aClone,aDocument,aRepeater){var _model=new _RichTextModel(aClone,aDocument);var _defaultData=aSeed[1];var _params=aSeed[2];var _option=aSeed[3];if(_params['filter'])
_model=this.applyFilters(_model,_params['filter']);_model.init(_defaultData,_params,_option,this.createUniqueKey(),aRepeater);return _model;},createUniqueKey:function createUniqueKey(){return _BASE_KEY+(_keyCounter++);}};})();xtiger.editor.Plugin.prototype.pluginEditors['richtext']=xtiger.util.filterable('richtext',xtiger.editor.RichTextFactory);xtiger.resources.addBundle('richtext',{'plusIconURL':'plus.png','minusIconURL':'minus.png','uncheckedIconURL':'unchecked.png','checkedIconURL':'checked.png'});var _RichTextWrapper=function(aDocument){this._document=aDocument;this._handle=xtdom.createElement(aDocument,'div');with(this._handle.style){display='none';top='-30px';}
xtdom.addClassName(this._handle,'xtt-lens');xtdom.addClassName(this._handle,'xtt-lensstyle');xtdom.addClassName(this._handle,'xtt-editing');var _buttonbar=xtdom.createElement(aDocument,'div');with(_buttonbar){style.height='20px';style.padding='0';style.marginBottom='10px';style.width='100%';}
this._handle.appendChild(_buttonbar);var _this=this;var _buttonBL=xtdom.createElement(aDocument,'input');with(_buttonBL){type='button';value='bold';style.display='inline';style.marginRight='2px';style.height='20px';}
xtdom.addEventListener(_buttonBL,'click',function(ev){_this._document.execCommand('bold',false,false);_this._editablediv.focus();},true);_buttonbar.appendChild(_buttonBL);var _buttonUL=xtdom.createElement(aDocument,'input');with(_buttonUL){type='button';value='underline';style.display='inline';style.marginRight='2px';style.height='20px';}
xtdom.addEventListener(_buttonUL,'click',function(ev){_this._document.execCommand('underline',false,false);_this._editablediv.focus();},true);_buttonbar.appendChild(_buttonUL);var _buttonIT=xtdom.createElement(aDocument,'input');with(_buttonIT){type='button';value='italic';style.display='inline';style.marginRight='2px';style.height='20px';}
xtdom.addEventListener(_buttonIT,'click',function(ev){_this._document.execCommand('italic',false,false);_this._editablediv.focus();},true);_buttonbar.appendChild(_buttonIT);var _buttonOK=xtdom.createElement(aDocument,'input');with(_buttonOK){type='button';value='OK';style.marginRight='2px';style.marginLeft='40px';style.height='20px';style.width='50px';style.cssFloat='right';style.styleFloat='right';}
xtdom.addEventListener(_buttonOK,'click',function(ev){_this._currentDevice.keepAlive(false);_this._currentDevice.stopEditing();},true);_buttonbar.appendChild(_buttonOK);this._editablediv=xtdom.createElement(aDocument,'div');with(this._editablediv){style.backgroundColor='white';style.color='black';style.margin='0';style.overflowX='auto';style.width='auto';}
this._editablediv.setAttribute('contentEditable',"true");this._editablediv.setAttribute('contenteditable',"true");this._handle.appendChild(this._editablediv);xtdom.addEventListener(this._editablediv,'focus',function(ev){_this.onInputFocus(ev)},false);xtdom.addEventListener(this._editablediv,'blur',function(ev){_this.onInputBlur(ev)},true);};_RichTextWrapper.prototype={grab:function(aDevice,aDoSelect){if(this._currentDevice)
this.release();this._currentDevice=aDevice;var _modelHandle=this._currentDevice.getCurrentModel().getHandle();with(this._handle){style.display='block';}
var _display=this._currentDevice.getCurrentModel().getParam('display');var _pad=this._currentDevice.getCurrentModel().getParam('padding')
var _newwidth=(_display=='inline')?null:(_modelHandle.offsetWidth);if(xtiger.cross.UA.IE){_newwidth+=2*_pad;}
with(this._handle.style){minHeight=(_modelHandle.offsetHeight+40)+'px';minWidth=(_display=='inline')?(_modelHandle.offsetWidth)+'px':null;maxWidth=(_display=='inline')?(_modelHandle.parentNode.offsetWidth)+'px':null;width=_newwidth+'px';padding=_pad+'px';}
with(this._editablediv.style){paddingLeft=xtdom.getComputedStyle(_modelHandle,'padding-left');paddingRight=xtdom.getComputedStyle(_modelHandle,'padding-right');paddingTop=xtdom.getComputedStyle(_modelHandle,'padding-top');paddingBottom=xtdom.getComputedStyle(_modelHandle,'padding-bottom');}
this.setData(this._currentDevice.getCurrentModel().getData());this.selectData();},release:function(){if(!this._currentDevice)
return;this.setData('');xtdom.removeElement(this._handle);this._currentDevice=null;},isFocusable:function(){return false;},getData:function(){return this._editablediv.innerHTML;},setData:function(aData){if(!typeof(aData)=='string')
return;this._editablediv.innerHTML=aData;},toggleField:function(){},selectData:function(){try{this._editablediv.focus();var _selObj=window.getSelection();var _range=document.createRange();_range.setStart(this._editablediv.firstChild,0);if(this._editablediv.lastChild.nodeType==xtdom.TEXT_NODE){_range.setEnd(this._editablediv.lastChild,this._editablediv.lastChild.textContent.length);}}
catch(_err){xtiger.cross.log('warning','Unable to move the caret at the end of the contentEditable field'+"\n\t"+'Cause: '+_err.message);}},getHandle:function(){return this._handle;},onInputFocus:function(ev){this._currentDevice.keepAlive(true);},onInputBlur:function(ev){this._currentDevice.keepAlive(false);}}
xtiger.factory('lens').registerWrapper('richtextwrapper',function(aDocument){return new _RichTextWrapper(aDocument)});xtiger.editor.UploadManager=function(doc){this.available=[];this.curDoc=doc;}
xtiger.editor.UploadManager.prototype={_reset:function(uploader){if(this.inProgress!=uploader){alert('Warning: attempt to close an unkown transmission !')}
uploader.reset();this.available.push(uploader);this.inProgress=null;},getUploader:function(){return(this.available.length>0)?this.available.pop():new xtiger.editor.FileUpload(this);},isReady:function(){return(null==this.inProgress);},isTransmitting:function(uploader){return(uploader&&(uploader==this.inProgress));},startTransmission:function(uploader,client){this.inProgress=uploader;uploader.start(client);},reportEoT:function(status,urlormsg){if(!this.inProgress){}else{if(status==1){this.notifyComplete(this.inProgress,urlormsg);}else{this.notifyError(this.inProgress,0,urlormsg);}}},notifyComplete:function(uploader,answer){var tmp=uploader.client;this._reset(uploader);tmp.onComplete(answer);},notifyError:function(uploader,code,message){var tmp=uploader.client;this._reset(uploader);tmp.onError(message);},cancelTransmission:function(uploader){var tmp=uploader.client;uploader.cancel();this._reset(uploader);tmp.onCancel();}}
xtiger.editor.FileUpload=function(mgr){this.manager=mgr;this.xhr=null;this.defaultUrl="/upload";}
xtiger.editor.FileUpload.prototype={reset:function(){delete this.url;},setDataType:function(kind){this.dataType=kind;},setAction:function(aUrl){this.url=aUrl;},getClient:function(){return this.client;},setClient:function(c){this.client=c;},start:function(client){this.client=client;try{if(this.dataType=='dnd'){this.startXHR();}else{var form=this.client.getPayload();if(this.url){xtdom.setAttribute(form,'action',this.url);}else if(!form.getAttribute('action')){xtdom.setAttribute(form,'action',this.defaultUrl);}
form['documentId'].value=this.client.getDocumentId()||'noid';form.submit();}}catch(e){this.manager.notifyError(this,e.name,e.message);}},startXHR:function(){this.xhr=new XMLHttpRequest();var _this=this;this.xhr.onreadystatechange=function(){try{if(4==_this.xhr.readyState){if(_this.xhr.status==201){_this.manager.notifyComplete(_this,_this.xhr.responseText);}else{_this.manager.notifyError(_this,_this.xhr.status,_this.xhr.statusText);}}
_this.xhr=null;}catch(e){_this.manager.notifyError(_this,e.name,e.message);}}
this.xhr.open("POST",this.url||this.defaultUrl);this.xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');var id=this.client.getDocumentId()||'noid';this.xhr.sendAsBinary(id+"$$$"+this.client.getPayload().getAsBinary());},cancel:function(){if(this.xhr){this.xhr.abort();}else{var form=this.client.getPayload();form.reset();}}}
var _UploadFactory={getInstance:function(doc){var cache=xtiger.session(doc).load('upload');if(!cache){cache=new xtiger.editor.UploadManager(doc);xtiger.session(doc).save('upload',cache);}
return cache;}}
xtiger.registry.registerFactory('upload',_UploadFactory);xtiger.editor.PhotoState=function(client){this.status=this.READY;this.photoUrl=null;this.errMsg=null;this.transmission=null;this.delegate=client;}
xtiger.editor.PhotoState.prototype={READY:0,ERROR:1,UPLOADING:2,COMPLETE:3,setDelegate:function(client){this.delegate=client;},getPayload:function(){return this.payload;},getDocumentId:function(){return xtiger.session(this.myDoc).load('documentId');},startTransmission:function(doc,kind,payload,url){this.cached=[this.status,this.photoUrl,this.errMsg];var manager=xtiger.factory('upload').getInstance(doc);this.myDoc=doc;this.transmission=manager.getUploader();this.transmission.setDataType(kind);if(url){this.transmission.setAction(url);}
this.payload=payload;this.status=this.UPLOADING;manager.startTransmission(this.transmission,this);this.delegate.redraw();},cancelTransmission:function(){if(this.transmission){var manager=xtiger.factory('upload').getInstance(this.myDoc);manager.cancelTransmission(this.transmission);}},onComplete:function(photoUrl){this.status=this.COMPLETE;this.photoUrl=photoUrl;this.errMsg=null;this.transmission=null;this.delegate.redraw();},onError:function(error,dontResetPhotoUrl){this.status=this.ERROR;if(!dontResetPhotoUrl){this.photoUrl=null;}
this.errMsg=error;this.transmission=null;this.delegate.redraw();},onCancel:function(){this.status=this.cached[0];this.photoUrl=this.cached[1];this.errMsg=this.cached[2];this.transmission=null;this.delegate.redraw();}}
xtiger.editor.PhotoModel=function(){}
xtiger.editor.PhotoModel.prototype={createModel:function(container,useNode,curDoc){var viewNode=xtdom.createElement(curDoc,'img');xtdom.setAttribute(viewNode,'src',xtiger.bundles.photo.photoIconURL);xtdom.addClassName(viewNode,'xtt-drop-target');xtdom.addClassName(viewNode,'xtt-photo');container.appendChild(viewNode);return viewNode;},createEditorFromTree:function(handleNode,xtSrcNode,curDoc){var data=xtdom.extractDefaultContentXT(xtSrcNode);var s=new xtiger.editor.Photo();var param=xtSrcNode.getAttribute('param');s.initFromTree(handleNode,curDoc,data,param,false);return s;},createEditorFromSeed:function(seed,clone,curDoc){var s=new xtiger.editor.Photo();s.initFromSeed(seed,clone,curDoc);return s;}}
xtiger.editor.Photo=function(){this.defaultContent=null;this.param=null;this.state=new xtiger.editor.PhotoState(this);}
xtiger.editor.Photo.prototype={defaultParams:{trigger:'click'},getParam:function(name){return(this.param&&this.param[name])||this.defaultParams[name];},initFromTree:function(handleNode,doc,userdata,parameters,option){this.param={}
this.curDoc=doc;this.handle=handleNode;this.defaultContent=userdata;xtiger.util.decodeParameters(parameters,this.param);this.awake();},initFromSeed:function(seed,clone,doc){this.curDoc=doc;this.handle=clone;this.defaultContent=seed[1];this.param=seed[2];this.awake();},awake:function(){this.device=xtiger.factory('lens').getInstance(this.curDoc);var _this=this;xtdom.addEventListener(this.handle,"error",function(ev){_this.state.onError('Broken Image',true)},false);xtdom.addEventListener(this.handle,this.getParam('trigger'),function(ev){_this.device.startEditing(_this,'photo');xtdom.preventDefault(ev);xtdom.stopPropagation(ev);},false);this._constructStateFromUrl(this.defaultContent);this.redraw(false);},makeSeed:function(){if(!this.seed){var factory=xtiger.editor.Plugin.prototype.pluginEditors['photo'];this.seed=[factory,this.defaultContent,this.param];}
return this.seed;},_constructStateFromUrl:function(value){if(value&&(value.search(/\S/)!=-1)){this.state.status=xtiger.editor.PhotoState.prototype.COMPLETE;this.state.photoUrl=value;}else{this.state.status=xtiger.editor.PhotoState.prototype.READY;this.state.photoUrl=null;}},_dump:function(){return(this.state.photoUrl)?this.state.photoUrl:'';},redraw:function(doPropagate){var src;switch(this.state.status){case xtiger.editor.PhotoState.prototype.READY:src=xtiger.bundles.photo.photoIconURL;break;case xtiger.editor.PhotoState.prototype.ERROR:src=xtiger.bundles.photo.photoBrokenIconURL;break;case xtiger.editor.PhotoState.prototype.UPLOADING:src=xtiger.bundles.photo.spiningWheelIconURL;break;case xtiger.editor.PhotoState.prototype.COMPLETE:if(doPropagate){var cur=this.handle.getAttribute('src');if(cur!=this.state.photoUrl){xtiger.editor.Repeat.autoSelectRepeatIter(this.handle);}}
src=this.state.photoUrl;break;default:src=xtiger.bundles.photo.photoBrokenIconURL;}
xtdom.setAttribute(this.handle,'src',src);},load:function(point,dataSrc){var value=(point!==-1)?dataSrc.getDataFor(point):this.defaultContent;this._constructStateFromUrl(value);this.redraw(false);},save:function(logger){logger.write(this._dump());},update:function(data){this.redraw(true);},getData:function(){return this.state;},can:function(action){return false;},getFile:function(){return this.file;},isFocusable:function(){return false;},getHandle:function(){return this.handle;},onDragEnter:function(ev){xtdom.addClassName(this.handle,'xtt-dnd-over');xtdom.stopPropagation(ev);xtdom.preventDefault(ev);},onDragOver:function(ev){xtdom.stopPropagation(ev);xtdom.preventDefault(ev);},onDragLeave:function(ev){xtdom.removeClassName(this.handle,'xtt-dnd-over');xtdom.stopPropagation(ev);xtdom.preventDefault(ev);},onDrop:function(ev){var dt=ev.dataTransfer;var files=dt.files;xtdom.stopPropagation(ev);xtdom.preventDefault(ev);for(var i=0;i<files.length;i++){var file=files[i];var imageType=/image.*/;if(!file.type.match(imageType)){continue;}
this.state.startTransmission(this.curDoc,'dnd',file,this.getParam('photo_URL'));}}}
xtiger.editor.PhotoViewer=function(url,doc,target,wrapper){var lensDiv=this.view=xtdom.createElement(doc,'div');xtdom.setAttribute(lensDiv,'id','xt-photo');xtdom.addClassName(lensDiv,'xtt-lens');xtdom.addClassName(lensDiv,'xtt-lensstyle');target.appendChild(this.view);try{var xhr=xtiger.cross.getXHRObject();xhr.open("GET",url,false);xhr.send(null);if((xhr.status==200)||(xhr.status==0)){if(xhr.responseText){lensDiv.innerHTML=xhr.responseText;}else{throw{name:'Error',message:'Photo plugin initialization failed : empty lens bundle content'}}}else{throw{name:'Error',message:'Photo plugin initialization failed : HTTP error ('+xhr.status+')'}}
this.formular=doc.getElementById('xt-photo-form');this.icon=doc.getElementById('xt-photo-icon');this.infobox=doc.getElementById('xt-photo-info');this.errorbox=doc.getElementById('xt-photo-error');this.filemenu=doc.getElementById('xt-photo-form-body');this.btnselfile=doc.getElementById('xt-photo-file');this.btnupload=doc.getElementById('xt-photo-save');this.btncancel=doc.getElementById('xt-photo-cancel');this.result=doc.getElementById('xt-photo-target');var _this=this;xtdom.addEventListener(this.btnselfile,'click',function(){_this.startSelectCb();},false);xtdom.addEventListener(this.btnupload,'click',function(){_this.saveCb();},false);xtdom.addEventListener(this.btncancel,'click',function(){_this.cancelCb();},false);this.btncancel.style.display='none';this.failed=false;this.hide();}catch(e){this.view.innerHTML="<p>File Upload is not available...<br/><br/>Failed to make lens with '"+url
+"'.<br/><br/>"+e.name+' : '+e.message
+"</p>";this.failed=true;}
this.ready();this.wrapper=wrapper;}
xtiger.editor.PhotoViewer.prototype={showPhoto:function(src){if(this.failed){return}
if(this.btnselfile.value.length>0){this.formular.reset();}
this.icon.setAttribute('src',src);this.icon.style.visibility='visible';if(src==xtiger.bundles.photo.spiningWheelIconURL){this.btncancel.style.display='block';}else{this.btncancel.style.display='none';}},hideError:function(){if(this.failed){return}
this.errorbox.style.display='none';},hideMessage:function(){if(this.failed){return}
this.infobox.style.display='none';},showError:function(msg){if(this.failed){return}
this.errorbox.style.display='block';this.errorbox.firstChild.data=msg;},showUplButtons:function(){if(this.failed){return}
this.filemenu.style.display='';},hideUplButtons:function(){if(this.failed){return}
this.filemenu.style.display='none';},hide:function(){this.view.style.display='none';},show:function(){this.view.style.display='';},showMessage:function(msg){if(this.failed){return}
this.infobox.style.display='block';this.infobox.firstChild.data=msg;},getTopDiv:function(){return this.view;},ready:function(){this.showPhoto(xtiger.bundles.photo.photoIconURL);this.showMessage("You can select a file and upload it");this.hideError();this.showUplButtons();},complete:function(photoUrl){this.showPhoto(photoUrl);this.hideMessage();this.hideError();this.showUplButtons();},loading:function(){this.showPhoto(xtiger.bundles.photo.spiningWheelIconURL);this.showMessage("Wait while loading");this.hideError();this.hideUplButtons();},error:function(msg){this.showPhoto(xtiger.bundles.photo.photoBrokenIconURL);this.showError(msg);this.hideMessage();this.showUplButtons();},busy:function(){this.btncancel.style.display='none';this.icon.style.visibility='hidden';this.hideError();this.showMessage('Another upload is in progress, please wait until it finishes.');this.hideUplButtons();},activateUpload:function(){this.btnupload.removeAttribute('disabled');},deactivateUpload:function(){xtdom.setAttribute(this.btnupload,'disabled','true');},startSelectCb:function(){this.wrapper.onStartSelect();},saveCb:function(){if(this.btnselfile.value.length>0){this.wrapper.onStartUpload(this.formular);}},cancelCb:function(){this.wrapper.onCancelUpload();}}
xtiger.editor.PhotoWrapper=function(aDoc){this._handle;this._handleToRestore;this.myDoc=aDoc;var form=xtiger.session(aDoc).load('form');var root=(form&&form.getRoot())||aDoc.getElementsByTagName('body')[0];this.view=new xtiger.editor.PhotoViewer(xtiger.bundles.photo.lensBoxURL,aDoc,root,this);this.state=null;}
xtiger.editor.PhotoWrapper.prototype={isFocusable:function(){return false;},getHandle:function(){return this.view.getTopDiv();},getData:function(){return this.state;},grab:function(dev){this.device=dev;this.editor=dev.getCurrentModel();this.state=this.editor.getData();this.state.setDelegate(this);this.redraw();this.view.show();var _pad=this.editor.getParam('padding');_pad=_pad?_pad:10;this.view.getTopDiv().style.padding=_pad+'px';},release:function(){this.view.hide();this.device=null;this.state.setDelegate(this.editor);this.editor.redraw();},onStartSelect:function(){this.device.mouseMayLeave();},onStartUpload:function(form){this.state.startTransmission(this.myDoc,'upload',form,this.editor.getParam('photo_URL'));},onCancelUpload:function(form){this.state.cancelTransmission();},redraw:function(){var mgr=xtiger.factory('upload').getInstance(this.myDoc);if(mgr.isReady()||mgr.isTransmitting(this.state.transmission)){switch(this.state.status){case xtiger.editor.PhotoState.prototype.READY:this.view.ready();break;case xtiger.editor.PhotoState.prototype.ERROR:this.view.error(this.state.errMsg);break;case xtiger.editor.PhotoState.prototype.UPLOADING:this.view.loading();break;case xtiger.editor.PhotoState.prototype.COMPLETE:this.view.complete(this.state.photoUrl);break;default:this.view.error('Unkown Photo status '+this.state.status);break;}}else{this.view.busy();}}}
xtiger.editor.Plugin.prototype.pluginEditors['photo']=new xtiger.editor.PhotoModel();xtiger.resources.addBundle('photo',{'photoIconURL':'icons/photo.png','photoBrokenIconURL':'icons/photobroken.png','spiningWheelIconURL':'icons/spiningwheel.gif','lensBoxURL':'photo.xhtml'});xtiger.factory('lens').registerWrapper('photo',function(doc){return new xtiger.editor.PhotoWrapper(doc)});var _DocumentIdFilter=(function _DocumentIdFilter(){return{'->':{'_setData':'__DocumentIdSuperSetData'},_setData:function(aData){this.__DocumentIdSuperSetData(aData);xtiger.session(this.getDocument()).save('documentId',aData);}};})();xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('documentId',_DocumentIdFilter);var _ClearFilter=(function _ClearFilter(){var _setStyle=function _setStyle(h,text,levels){var n=h;for(var i=levels;i>0;i--){n=n.parentNode;}
if((text=='both')||(text=='left')||(text=='right')){n.style.clear=text;}else{n.style.clear='';}}
return{'->':{'load':'__ClearSuperLoad','update':'__ClearSuperUpdate'},load:function(point,dataSrc){var value;if(!dataSrc.isEmpty(point)){value=dataSrc.getDataFor(point);var levels=parseInt(this.getParam('clear'));_setStyle(this.getHandle(),value,levels);}
this.__ClearSuperLoad(point,dataSrc);},update:function(text){var levels=parseInt(this.getParam('clear'));_setStyle(this.getHandle(true),text,levels);this.__ClearSuperUpdate(text);}}})();xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('clear',_ClearFilter);var _PositionFilter=(function _PositionFilter(){var _setStyle=function _setStyle(h,text){var n=h.parentNode.parentNode.parentNode;var m=n.parentNode.getElementsByTagName('span')[0];if((text=='left')||(text=='right')){n.style.cssFloat=m.style.cssFloat=text;if(text=='right'){n.style.marginLeft='20px';n.style.marginRight='';}else{n.style.marginRight='20px';n.style.marginLeft='';}}else{n.style.cssFloat=m.style.cssFloat='';n.style.marginRight='';n.style.marginLeft='';}}
return{'->':{'load':'__PositionSuperLoad','update':'__PositionSuperUpdate'},load:function(point,dataSrc){var value;if(!dataSrc.isEmpty(point)){value=dataSrc.getDataFor(point);_setStyle(this.getHandle(),value);}
this.__PositionSuperLoad(point,dataSrc);},update:function(text){_setStyle(this.getHandle(true),text);this.__PositionSuperUpdate(text);}};})();xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('position',_PositionFilter);xtiger.editor.VideoFactory=(function VideoFactory(){var _VideoModel=function(aHandleNode,aDocument){var _DEFAULT_PARAMS={defaultDevice:'lens',trigger:"mouseover",lang:'fr_FR',inputFieldMessage:'Paste the video\'s link here'};this._handle=aHandleNode;this._data=null;this._defaultData=this._data;this._noData=this._handle.firstChild;this._document=aDocument;this._params=_DEFAULT_PARAMS;this._isOptional=false;this._isOptionSet=false;this._optCheckBox;this._device=null;this._seed=null;this._isModified=false;this._uniqueKey;this.create();};_VideoModel.prototype={_isValidUrl:function(aInput){var _URL_R=/^(http\:\/\/|~\/|\/)?(\w+:\w+@)?(([-\w\d{1-3}]+\.)+(com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2})?)(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:[\?&](?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?(?:&)?$/;return _URL_R.test(aInput);},_removeLTSpaces:function(aInput){if(!aInput||aInput=='')
return'';return aInput.replace(/^\s+|\s+$/g,'');},_buildYoutubeSnippet:function(aVideoID,aSize,aParams){var _params=aParams?aParams:{};_params['movie']=aVideoID;if(!_params['allowFullScreen'])
_params['allowFullScreen']='true';if(!_params['alloscriptaccess'])
_params['alloscriptaccess']='always';var _obj=xtdom.createElement(this._document,'object');if(aSize){_obj.height=aSize[0];_obj.width=aSize[1];}else{_obj.height=344;_obj.width=425;}
_obj.style.zIndex=1000;for(var _param in _params){var _p=xtdom.createElement(this._document,'param');_p.name=_param;_p.value=_params[_param];_obj.appendChild(_p);}
var _embed=xtdom.createElement(this._document,'embed');xtdom.setAttribute(_embed,'src',aVideoID);xtdom.setAttribute(_embed,'type','application/x-shockwave-flash');xtdom.setAttribute(_embed,'allowfullscreen','true');xtdom.setAttribute(_embed,'allowscriptaccess','always');xtdom.setAttribute(_embed,'width','425');xtdom.setAttribute(_embed,'height','344');_embed.style.zIndex=1000;if(xtiger.cross.UA.IE){_obj=_embed;}else{_obj.appendChild(_embed);}
return _obj;},_extractVideoId:function(aValidUrl){var _tmp=aValidUrl.match(/^[^&]*/)[0];return _tmp.match(/[^\=\/]*$/)[0];},_isCodeSnippet:function(aInput){var _SNIPPET_O_R=/(<object>).*(<param[^>]*(name\="movie"))/;var _SNIPPET_E_R=/(<embed\s)([^>]+)(\ssrc\=")([^"]+)"/;return _SNIPPET_O_R.test(aInput)||_SNIPPET_E_R.test(aInput);},_setData:function(aData){var _tdata=this._removeLTSpaces(aData);if(!this._isValidUrl(_tdata)){if(this._isCodeSnippet(_tdata))
_tdata=this._extractUrlFromSnippet(_tdata);else
return false;}
var _type='youtube';switch(_type){case'youtube':var _videoID=this._extractVideoId(_tdata);var _newdata='http://www.youtube.com/v/'+_videoID;if(this._data==_newdata)
return false;this._data=_newdata;_newdata+='&hl='+this._params['lang']+'&fs=1&';var _newContent=this._buildYoutubeSnippet(this._data,null,null);try{var _tmp=xtdom.createElement(this._document,'div');_tmp.style.visibility='hidden';this._document.getElementsByTagName('body')[0].appendChild(_tmp);_tmp.appendChild(_newContent);with(this._handle.style){width='425px';height='344px';}
this._handle.replaceChild(_newContent,this._handle.firstChild);this.setModified(true);xtdom.removeElement(_tmp);}
catch(err){xtiger.cross.log('warning',err);return false;}
break;default:xtiger.cross.log('warning','Video type '+type+' is currently unsupported');return false;}
return true;},create:function(){},init:function(aDefaultData,aParams,aOption,aUniqueKey,aRepeater){if(aParams){if(typeof(aParams)=='string')
xtiger.util.decodeParameters(aParams,this._params);else if(typeof(aParams)=='object')
this._params=aParams;}
if(aDefaultData){if(this._isValidUrl(aDefaultData)||this._isCodeSnippet(aDefaultData)){this._setData(aDefaultData);this._defaultData=this._data;}
else
this._params['inputFieldMessage']=aDefaultData;}
if(aOption){this._isOptional=true;this._optCheckBox=this._handle.previousSibling;(aOption=='set')?this.set(false):this.unset(false);}
this._uniqueKey=aUniqueKey;var _deviceFactory=this._params['device']?xtiger.factory(this._params['device']):xtiger.factory(this._params['defaultDevice']);this._device=_deviceFactory.getInstance(this._document);this.awake();},makeSeed:function(){if(!this._seed)
this._seed=[xtiger.editor.VideoFactory,this._defaultData,this._params,this._isOptional];return this._seed;},can:function(aFunction){return typeof this[aFunction]=='function';},execute:function(aFunction,aParam){return this[aFunction](aParam);},load:function(aPoint,aDataSrc){if(aPoint!==-1){var _value=aDataSrc.getDataFor(aPoint);this._setData(_value)||this.clear();this.set(false);}else{this.clear()
this.unset(false);}},save:function(aLogger){if(this.isOptional()&&!this._isOptionSet){aLogger.discardNodeIfEmpty();return;}
if(!this._data)
return;aLogger.write(this._data);},update:function(aData){var _success=false;if(aData&&(typeof(aData)=='string')&&(aData.search(/\S/)!=-1)){_success=(aData==this._data)||this._setData(aData);}
if(_success){this.set(true);}},clear:function(){this._data='';this.setModified(false);this._handle.replaceChild(this._noData,this._handle.firstChild);var _width=this._noData.offsetWidth;var _height=this._noData.offsetHeight;with(this._handle.style){width=(_width>2?_width:80)+'px';height=(_height>2?_height:80)+'px';}},getData:function(){if(this._data&&this._data!='')
return this._data;return null;},getDefaultData:function(){return this._defaultData;},getHandle:function(){return this._handle;},getDocument:function(){return this._document;},getParam:function(aKey){return this._params[aKey];},getUniqueKey:function(){return this._uniqueKey;},isModified:function(){return this._isModified;},setModified:function(isModified){this._isModified=isModified;},isFocusable:function(){return true;},focus:function(){this.startEditing(null);},unfocus:function(){this._device.stopEditing();},isOptional:function(){return this._isOptional;},isSet:function(){return this._isOptional&&(this._isOptionSet?true:false);},set:function(doPropagate){if(doPropagate){xtiger.editor.Repeat.autoSelectRepeatIter(this.getHandle());}
if(this._isOptional&&!this._isOptionSet){this._isOptionSet=true;xtdom.removeClassName(this._handle,'xtt-option-edit-unset');xtdom.addClassName(this._handle,'xtt-option-edit-set');this._optCheckBox.checked=true;}},unset:function(doPropagate){if(this._isOptional&&this._isOptionSet){this._isOptionSet=false;xtdom.removeClassName(this._handle,'xtt-option-edit-set');xtdom.addClassName(this._handle,'xtt-option-edit-unset');this._optCheckBox.checked=false;}},awake:function(){var _this=this;if(this.isOptional()){xtdom.addEventListener(this._optCheckBox,'click',function(ev){_this.onToggleOpt(ev);},true);}
xtdom.addEventListener(this._handle,'mouseover',function(ev){_this.startEditing(ev);},true);},startEditing:function(aEvent){var _doSelect=aEvent?(!this._isModified||aEvent.shiftKey):false;this._device.startEditing(this,'videoLensWrapper',_doSelect);},stopEditing:function(){this._device.stopEditing();},onToggleOpt:function(ev){this._isOptionSet?this.unset(true):this.set(true);}};var _BASE_KEY='video';var _keyCounter=0;return{createModel:function createModel(aContainer,aXTUse,aDocument){var _h=xtdom.createElement(aDocument,'div');xtdom.addClassName(_h,'xtt-on');xtdom.addClassName(_h,'xtt-editable');var _img=xtdom.createElement(aDocument,'img');_img.src=xtiger.bundles.video.tvIconURL;var _optional=aXTUse.getAttribute('option');if(_optional){var _checkbox=xtdom.createElement(aDocument,'input');xtdom.setAttribute(_checkbox,'type','checkbox');xtdom.addClassName(_checkbox,'xtiger-option-checkbox');aContainer.appendChild(_checkbox);}
_h.appendChild(_img);var _tmp=xtdom.createElement(aDocument,'div');_tmp.style.visibility='hidden';aDocument.getElementsByTagName('body')[0].appendChild(_tmp);_tmp.appendChild(_h);var _width,_height;_width=_img.offsetWidth;_height=_img.offsetHeight;_h.style.width=(_width>2?_width:80)+'px';_h.style.height=(_height>2?_height:80)+'px';aContainer.appendChild(_h);xtdom.removeElement(_tmp);return _h;},createEditorFromTree:function createEditorFromTree(aHandleNode,aXTUse,aDocument){var _model=new _VideoModel(aHandleNode,aDocument);var _data,_cur;_cur=aXTUse.firstChild;while(_cur&&!_data)
{switch(_cur.nodeType){case aDocument.TEXT_NODE:if((/\w+/).test(_cur.nodeValue))
{var _data=_cur.nodeValue;}
break;case aDocument.ELEMENT_NODE:if(_cur.localName='object')
var _data=_cur;}
_cur=_cur.nextSibling;}
var _param={};xtiger.util.decodeParameters(aXTUse.getAttribute('param'),_param);if(_param['filter'])
_model=this.applyFilters(_model,_param['filter']);_model.init(_data,aXTUse.getAttribute('param'),aXTUse.getAttribute('option'),this.createUniqueKey());return _model;},createEditorFromSeed:function createEditorFromSeed(aSeed,aClone,aDocument,aRepeater){var _model=new _VideoModel(aClone,aDocument);var _defaultData=aSeed[1];var _param=aSeed[2];var _option=aSeed[3];if(_param['filter'])
_model=this.applyFilters(_model,_param['filter']);_model.init(_defaultData,_param,_option,this.createUniqueKey(),aRepeater);return _model;},createUniqueKey:function createUniqueKey(){return _BASE_KEY+(_keyCounter++);}}})();xtiger.resources.addBundle('video',{'tvIconURL':'tv.png'});xtiger.editor.Plugin.prototype.pluginEditors['video']=xtiger.util.filterable('video',xtiger.editor.VideoFactory);var _VideoLensWrapper=function(aDocument){this._handle;this._handleToRestore;this._document=aDocument;this._isFocused=false;this._loaded=false;this.build();}
_VideoLensWrapper.prototype={build:function(){this._topdiv=xtdom.createElement(this._document,'div');xtdom.addClassName(this._topdiv,'xtt-lens');with(this._topdiv){style.display='none';style.minWidth='200px';}
var _innerHTML='';_innerHTML+='<div style="background: none; position: relative"> </div>';_innerHTML+='<div class="xtt-lensstyle" style="width: 410px; padding: 5px; position: relative">';_innerHTML+='<p style="';_innerHTML+='display: none; font-size: 7pt; cursor: pointer; ';_innerHTML+='text-decoration:underline; text-align: right; margin: 0;';_innerHTML+='">delete</p>';_innerHTML+='<div>';_innerHTML+='<label for="videolensinput" style="display: block">Paste url here</label>';_innerHTML+='<input type="text" name="videolensinput" value="" style="width: 90%"></input>';_innerHTML+='</div>';_innerHTML+='<div style="text-align: center">';_innerHTML+='<button>Cancel</button>';_innerHTML+='<button>Save</button>';_innerHTML+='</div></div>';this._topdiv.innerHTML=_innerHTML;this._maskdiv=this._topdiv.firstChild;this._contentdiv=this._maskdiv.nextSibling;this._deletespan=this._contentdiv.firstChild;this._inputdiv=this._deletespan.nextSibling;this._input=this._inputdiv.firstChild.nextSibling;this._buttondiv=this._inputdiv.nextSibling;this._cancelbutton=this._buttondiv.firstChild;this._savebutton=this._buttondiv.firstChild.nextSibling;},grab:function(aDevice,aDoSelect){if(this._currentDevice)
this.release();this._currentDevice=aDevice;var _handle=this._currentDevice.getCurrentModel().getHandle();var _pad=this._currentDevice.getCurrentModel().getParam('padding');_pad=(_pad&&_pad>=10)?_pad:10;var _width=_handle.offsetWidth;var _height=_handle.offsetHeight;if(xtiger.cross.UA.IE){_width+=2*_pad;_height+=2*_pad;}
with(this._topdiv.style){display='block';width=_width+'px';padding=_pad+'px';}
with(this._maskdiv.style){border=''+_pad+'px solid rgb(115, 166, 42)';width=_width+'px';height=_height+'px';if(!xtiger.cross.UA.IE){left='-'+_pad+'px';top='-'+_pad+'px';}}
with(this._contentdiv.style){if(!xtiger.cross.UA.IE){left='-'+_pad+'px';top='-'+_pad+'px';}}
this._cancelbutton.disabled=false;this._savebutton.disabled=true;if(this._currentDevice.getCurrentModel().isModified()){this.setData(this._currentDevice.getCurrentModel().getData());this._deletespan.style.display='block';this._loaded=true;}
else{var _message=this._currentDevice.getCurrentModel().getParam('inputFieldMessage');this.setData(_message);this._loaded=false;}
var _this=this;this._handlers={clearModel:function(ev){_this.clearModel()},onInputBlur:function(ev){_this._onInputBlur(ev)},onInputFocus:function(ev){_this._onInputFocus(ev)},onInputKeyDown:function(ev){_this._onInputKeyDown(ev)},onInputKeyUp:function(ev){_this._onInputKeyUp(ev)},onCancel:function(ev){_this._onCancel(ev)},onSave:function(ev){_this._onSave(ev)}}
xtdom.addEventListener(this._input,'blur',_this._handlers.onInputBlur,true);xtdom.addEventListener(this._input,'focus',_this._handlers.onInputFocus,true);xtdom.addEventListener(this._input,'keydown',_this._handlers.onInputKeyDown,true);xtdom.addEventListener(this._input,'keyup',_this._handlers.onInputKeyUp,true);xtdom.addEventListener(this._deletespan,'click',_this._handlers.clearModel,true);xtdom.addEventListener(this._cancelbutton,'click',_this._handlers.onCancel,true);xtdom.addEventListener(this._savebutton,'click',_this._handlers.onSave,true);},release:function(){if(!this._currentDevice)
return;var _this=this;xtdom.removeEventListener(this._input,'blur',_this._handlers.onInputBlur,true);xtdom.removeEventListener(this._input,'focus',_this._handlers.onInputFocus,true);xtdom.removeEventListener(this._input,'keydown',_this._handlers.onInputKeyDown,true);xtdom.removeEventListener(this._input,'keyup',_this._handlers.onInputKeyUp,true);xtdom.removeEventListener(this._deletespan,'click',_this._handlers.clearModel,true);xtdom.removeEventListener(this._cancelbutton,'click',_this._handlers.onCancel,true);xtdom.removeEventListener(this._savebutton,'click',_this._handlers.onSave,true);this._deletespan.style.display='none';this._currentDevice=null;xtdom.removeElement(this._topdiv);},getHandle:function(){return this._topdiv;},getData:function(){return this._input.value;},setData:function(aData){this._input.value=(aData&&typeof(aData)=='string')?aData:'';},isFocusable:function(){return true;},clearModel:function(){if(!this._currentDevice)
return;this._input.value='';this._currentDevice.getCurrentModel().clear();this._currentDevice.keepAlive(false);this._currentDevice.getCurrentModel().unfocus();},toggleField:function(){},_onInputBlur:function(ev){this._currentDevice.keepAlive(false);},_onInputFocus:function(ev){if(this._loaded){var _aStartPos=0;var _aEndPos=this._input.value.length;if(this._input.setSelectionRange){this._input.setSelectionRange(_aStartPos,_aEndPos);}else if(this._input.createTextRange){var oRange=this._input.createTextRange();oRange.moveStart("character",_aStartPos);oRange.moveEnd("character",_aEndPos);oRange.select();}}
else{this._input.value='';}
this._currentDevice.keepAlive(true);},_onInputKeyDown:function(ev){this._savedValue=this._input.value;},_onInputKeyUp:function(ev){if(this._input.value!=this._savedValue){this._cancelbutton.disabled=false;this._savebutton.disabled=false;}},_onCancel:function(ev){if(!this._currentDevice)
return;this._currentDevice.cancelEditing();xtdom.stopPropagation(ev);},_onSave:function(ev){if(!this._currentDevice)
return;this._currentDevice.stopEditing();xtdom.stopPropagation(ev);}}
xtiger.factory('lens').registerWrapper('videoLensWrapper',function(aDocument){return new _VideoLensWrapper(aDocument)});var _VideoFilter=(function _VideoFilter(){var _extractVideoId=function _extractVideoId(aValidUrl){var _tmp=aValidUrl.match(/^[^&]*/)[0];return _tmp.match(/[^\=\/]*$/)[0];}
var _buildYoutubeSnippet=function _buildYoutubeSnippet(aVideoID,aSize,aParams,targetDoc){var _params=aParams||{};_params['movie']=aVideoID;if(!_params['allowFullScreen'])
_params['allowFullScreen']='true';if(!_params['alloscriptaccess'])
_params['alloscriptaccess']='always';var _obj=xtdom.createElement(targetDoc,'object');if(aSize){_obj.height=aSize[0];_obj.width=aSize[1];}else{_obj.height=344;_obj.width=425;}
_obj.style.zIndex=1000;for(var _param in _params){var _p=xtdom.createElement(targetDoc,'param');_p.name=_param;_p.value=_params[_param];_obj.appendChild(_p);}
var _embed=xtdom.createElement(targetDoc,'embed');xtdom.setAttribute(_embed,'src',aVideoID);xtdom.setAttribute(_embed,'type','application/x-shockwave-flash');xtdom.setAttribute(_embed,'allowfullscreen','true');xtdom.setAttribute(_embed,'allowscriptaccess','always');xtdom.setAttribute(_embed,'width','425');xtdom.setAttribute(_embed,'height','344');_embed.style.zIndex=1000;if(xtiger.cross.UA.IE){_obj=_embed;}else{_obj.appendChild(_embed);}
return _obj;}
var _getHandleExtension=function _getHandleExtension(that){var h=that.getHandle(true);var hook=h.nextSibling?h.nextSibling.nextSibling:undefined;var isVideo=false;if(hook){var name=xtdom.getLocalName(hook);if((name.toLowerCase()=='object')||(name.toLowerCase()=='embed')){isVideo=true;}else if(name.toLowerCase()!='img'){hook=undefined;}}
return[hook,isVideo];}
return{'->':{'init':'__videoSuperInit','set':'__videoSuperSet','unset':'__videoSuperUnset','_setData':'__videoSuperSetData'},_setData:function(text){var extension=_getHandleExtension(this);var filtered=text;if(extension[0]){if(text!=this.getDefaultData()){var cur=this.getData();var _videoID=_extractVideoId(text);var data='http://www.youtube.com/v/'+_videoID;if(cur!=data){var _newContent=_buildYoutubeSnippet(data,null,null,this.getDocument());extension[0].parentNode.replaceChild(_newContent,extension[0]);filtered=data;}}else if(extension[1]){var img=xtdom.createElement(this.getDocument(),'img');img.src=xtiger.bundles.video.tvIconURL;extension[0].parentNode.replaceChild(img,extension[0]);}}
this.__videoSuperSetData(filtered);},init:function(aDefaultData,aParams,aOption,aUniqueKey,repeater){if(!repeater){var h=this.getHandle();var br=xtdom.createElement(this.getDocument(),'br');var img=xtdom.createElement(this.getDocument(),'img');var guard=xtdom.createElement(this.getDocument(),'span');xtdom.addClassName(guard,'xtt-boundary');img.src=xtiger.bundles.video.tvIconURL;var parent=h.parentNode;if(h.nextSibling){parent.insertBefore(guard,h.nextSibling,true);parent.insertBefore(img,guar,true);parent.insertBefore(br,img,true);}else{parent.appendChild(br);parent.appendChild(img);parent.appendChild(guard);}}
this.__videoSuperInit(aDefaultData,aParams,aOption,aUniqueKey);},set:function(doPropagate){this.__videoSuperSet(doPropagate);if(this.isOptional()){var h=this.getHandle(true);if(h.nextSibling&&h.nextSibling.nextSibling){xtdom.replaceClassNameBy(h.nextSibling.nextSibling,'xtt-option-edit-unset','xtt-option-edit-set');}}},unset:function(doPropagate){this.__videoSuperUnset(doPropagate);if(this.isOptional()){var h=this.getHandle(true);if(h.nextSibling&&h.nextSibling.nextSibling){xtdom.replaceClassNameBy(h.nextSibling.nextSibling,'xtt-option-edit-set','xtt-option-edit-unset');}}}}})();xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('video',_VideoFilter);var _ServiceFilter=(function _ServiceFilter(){return{'->':{'init':'__serviceSuperInit','update':'__serviceSuperUpdate','remove':'__serviceSuperRemove'},_invokeService:function _invokeService(aService,aMessage,aData,aResourceKey){if(aService[aMessage]&&typeof aService[aMessage]=='function')
aService[aMessage](this,aData,aResourceKey);},_notifyServices:function _notifyServices(aProducersList,aMessage,aData,aStartNode){var r;var cur=aStartNode;var startCount=0;var endCount=0;while(cur){if(cur.xttService){var curKey=cur.xttService.getKey();if(curKey){for(var i=0;i<aProducersList.length;i++){if(curKey==aProducersList[i].key){this._invokeService(cur.xttService,aMessage,aData,aProducersList[i].resource);}}}}
if(cur.startRepeatedItem){startCount++;}
if((cur!=aStartNode)&&cur.endRepeatedItem){endCount++;}
if(startCount>endCount){r=cur.startRepeatedItem;cur=r.getFirstNodeForSlice(0);startCount=endCount=0;}
cur=cur.previousSibling;}
if(aStartNode.parentNode){this._notifyServices(aProducersList,aMessage,aData,aStartNode.parentNode);}},_getServiceKey:function _getServiceKey(){var keyString=this.getParam('service_key');var keys=keyString.split(' ');var spec={};for(var i=0;i<keys.length;i++){var m=keys[i].match(/^(\w+):(\w+)\[(.*)\]$/);var role=m[2];if(role){if(!spec[role])
spec[role]=[];spec[role].push({key:m[1],resource:m[3]});}}
return spec;},checkServiceKey:function checkServiceKey(aKey){var spec=this._getServiceKey();if(spec.consumer){for(var i=0;i<spec.consumer.length;i++){if(aKey.key==spec.consumer[i].key&&aKey.resource==spec.consumer[i].resource){return true;}}}
return false;},init:function init(aDefaultData,aParams,aOption,aUniqueKey,aRepeater){this.__serviceSuperInit(aDefaultData,aParams,aOption,aUniqueKey,aRepeater);if(aRepeater){var _serviceKey=this._getServiceKey();if(_serviceKey.consumer){this._notifyServices(_serviceKey.consumer,'doBroadcastOnce',null,aRepeater.getFirstNodeForSlice(0));}}},update:function update(aData){var _serviceKey=this._getServiceKey();if(_serviceKey.producer&&aData!=this.getData()){this._notifyServices(_serviceKey.producer,'onUpdate',aData,this.getHandle(true));}
this.__serviceSuperUpdate(aData);},remove:function remove(){var _serviceKey=this._getServiceKey();if(_serviceKey.producer){this._notifyServices(_serviceKey.producer,'onRemove',this.getData(),this.getHandle(true));}
this.__serviceSuperRemove();}}})();xtiger.editor.Plugin.prototype.pluginEditors['video'].registerFilter('service',_ServiceFilter);xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('service',_ServiceFilter);xtiger.editor.Plugin.prototype.pluginEditors['richtext'].registerFilter('service',_ServiceFilter);xtiger.editor.Plugin.prototype.pluginEditors['link'].registerFilter('service',_ServiceFilter);var _AutocompleteFilter=(function _AutocompleteFilter(){return{'->':{'init':'__autocompleteSuperInit','update':'__autocompleteSuperUpdate','startEditing':'__autocompleteSuperStartEditing'},init:function init(aDefaultData,aParams,aOption,aUniqueKey){this.__autocompleteSuperInit(aDefaultData,aParams,aOption,aUniqueKey);this._autocompleteDevice=xtiger.editor.AutocompleteDevice.getInstance(this.getDocument()).validateParameters(this);},update:function update(aData){this.__autocompleteSuperUpdate(aData);this._device.cancelEditing();if(this._autocompleteDevice)
this._autocompleteDevice.release();},startEditing:function startEditing(aEvent){this.__autocompleteSuperStartEditing(aEvent);if(this._autocompleteDevice)
this._autocompleteDevice.grab(this._device,this._device.getHandle());},onkeyup:function(){if(this._autocompleteDevice)
this._autocompleteDevice.onKeyUp();}}})();xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('autocomplete',_AutocompleteFilter);xtiger.editor.AutocompleteDevice=(function AutocompleteDevice(){var _instance;var _AutocompleteDeviceInstance=function(aDocument){var _DEFAULT_PARAMS={'limit':200,'delay':200,'display_max':10,'suggestclass':'ac_suggest','matchclass':'ac_match','baselayout':'<span class="ac_suggest">%suggest%</span>'}
this._document=aDocument;this._currentDevice;this._currentField;this._timer;this._currentMatch;this._cache;this._serviceURL;this._resourceURI;this._viewer;this._pendingRequests;this._sessionParams=_DEFAULT_PARAMS;}
_AutocompleteDeviceInstance.prototype={_createViewer:function(){var _devKey='popupdevice';this._popupdevice=xtiger.session(this._document).load(_devKey);if(!this._popupdevice){this._popupdevice=new xtiger.editor.PopupDevice(this._document);xtiger.session(this._document).save(_devKey,this._popupdevice);}},_formatSuggest:function(aSuggest,aMatch,aBaseLayout){var _suggest=aSuggest;if(aMatch&&typeof(aMatch)=='String'&&aMatch!=''){try{var _matcher=new RegExp(aMatch,'i');_suggest=_suggest.replace(_matcher,function(m){return'<span class="'+this._sessionParams['matchclass']+'">'+m+'</span>';});}catch(_err){xtiger.cross.log('warning','AutocompleteDevice: wrong syntax in matcher '+aMatch);}}
return _suggest;},_showResults:function(aResultsList){if(aResultsList&&aResultsList.length>0)
this._popupdevice.startEditing(this._currentModel,aResultsList,this._currentMatch,this._currentField);},_prepareRequest:function(aMatch,aLimit){var _xhr=xtiger.cross.getXHRObject();var _url=this._serviceURL+'/'+this._resourceURI;_url+='?query='+aMatch;if(aLimit&&aLimit>0)
_url+='&limit='+aLimit;_xhr.open('GET',_url,true);return _xhr;},_fetchSuggests:function(aMatch){var _xhr=this._prepareRequest(aMatch,this._sessionParams['limit']);var _this=this;_xhr.onreadystatechange=function(){if(_xhr.readyState==4){if(_xhr.status==200){_this._onRequestReceived(aMatch,_xhr);}
else{xtiger.cross.log('warning','Suggest device: request failed for query '+aMatch+' with status '+_xhr.status);}}}
try{_xhr.send(null);}catch(e){xtiger.cross.log('warning','Exception while contacting autocomplete service : '+e.name);}},_updateCache:function(aMatch,aResultsList,hasMore){if(this._cache[aMatch]){if(this._cache[aMatch].hasMore&&!hasMore)
this._cache[aMatch]={'suggests':aResultsList,'hasMore':false};}
else{this._cache[aMatch]={'suggests':aResultsList,'hasMore':hasMore};}},_extractFromCache:function(aMatch,aMax){var _res;var _match=aMatch;while(!_res&&_match.length>0){if(this._cache[_match])
_res=xtiger.util.array_map(this._cache[_match]['suggests'],function(e){return e.value});if(!_res)
_match=_match.slice(0,-1);}
if(!_res)
return null;if(_match!=aMatch){var _r=new RegExp('^'+aMatch,'i');_res=xtiger.util.array_filter(_res,function(s){return _r.test(s)});}
if(aMax&&typeof(aMax)=='number'&&aMax>0&&aMax<_res.length)
_res=_res.slice(0,aMax-1);return _res;},_hasFullMatch:function(aMatch){var _testMatch=aMatch;while(_testMatch.length>0){if(this._cache[_testMatch])
return!this._cache[_testMatch].hasMore;_testMatch=_testMatch.slice(0,-1);}
return false;},_updateState:function(){this._currentMatch=this._currentField.value;if(this._timer)
clearTimeout(this._timer);if(this._hasFullMatch(this._currentMatch)){this._showResults(this._extractFromCache(this._currentMatch,this._sessionParams['display_max']));}
else{if(this._currentMatch!='')
this._timer=setTimeout('xtiger.editor.AutocompleteDevice.getInstance().onTimeout()',this._sessionParams['delay']);}},_onRequestReceived:function(aMatch,aRequest){xtiger.cross.log('debug','Suggest for '+aMatch+': '+aRequest.responseText);try{var _parsedResults=eval('('+aRequest.responseText+')');this._updateCache(aMatch,_parsedResults.results,_parsedResults.hasMore);this._showResults(this._extractFromCache(aMatch,this._sessionParams['display_max']));}
catch(err){xtiger.cross.log('warning','AutocompleteDevice: '+err.message);}},onTimeout:function(){this._fetchSuggests(this._currentMatch);},validateParameters:function(aModel){var _url=aModel.getParam('autocomplete_URL');var _rsrc=aModel.getParam('autocomplete_resource');_url||xtiger.cross.log('warning','missing "autocomplete_URL" parameter on autocomplete filter');_rsrc||xtiger.cross.log('warning','missing "autocomplete_resource" parameter on autocomplete filter');return(_url&&_rsrc)?this:false;},grab:function(aDevice,aInputField){if(this._currentDevice)
this.release();this._currentDevice=aDevice;this._currentField=aInputField;if(!this._popupdevice)
this._createViewer();this._currentModel=aDevice.getCurrentModel();this._serviceURL=this._currentModel.getParam('autocomplete_URL');this._resourceURI=this._currentModel.getParam('autocomplete_resource');this._sessionParams['limit']=this._currentModel.getParam('autocomplete_limit');this._currentMatch=this._currentField.value;this._cache={};},release:function(){this._currentDevice=null;this._currentField=null;this._currentModel=null;for(var _m in this._pendingRequests){this._pendingRequests[_m].abort();}
this._pendingRequests={};this._cache=null;},onKeyUp:function(ev){if(!this._currentDevice)
return;if(this._currentField.value!=this._currentMatch)
this._updateState();}}
return{getInstance:function getInstance(aDocument){if(!_instance)
_instance=new _AutocompleteDeviceInstance(aDocument);return _instance;}}})();var _DebugFilter=(function _DebugFilter(){function _printDebugTrace(aModel,aFunction,aValue,aComment){var _buf='';_buf+='['+aModel.getUniqueKey()+']';_buf+=' : '+aFunction;_buf+='(';if(aValue)
_buf+=aValue;_buf+=')'
if(aComment)
_buf+=' : '+aComment;xtiger.cross.log('debug',_buf);};function _arrayPP(aArray){var _buf='['
for(var _i=0;_i<aArray.length;_i++){_buf+=aArray[_i]+', ';}
return _buf;}
return{'->':{'create':'__debugSuperCreate','init':'__debugSuperInit','load':'__debugSuperLoad','save':'__debugSuperSave','update':'__debugSuperUpdate','clear':'__debugSuperClear','getData':'__debugSuperGetData','focus':'__debugSuperFocus','unfocus':'__debugSuperUnfocus','set':'__debugSuperSet','unset':'__debugSuperUnset','awake':'__debugSuperAwake','startEditing':'__debugSuperStartEditing','stopEditing':'__debugSuperStopEditing'},create:function create(){_printDebugTrace(this,'create');this.__debugSuperCreate();},init:function init(aDefaultData,aParams,aOption,aUniqueKey){var _params=''+aDefaultData
if(typeof aParams=='string')
_params+=aParams;else
_params+=', '+_arrayPP(aParams);_params+=', '+aOption
_params+=', '+aUniqueKey;_printDebugTrace(this,'init',_params);this.__debugSuperInit(aDefaultData,aParams,aOption,aUniqueKey);},load:function load(aPoint,aDataSrc){_printDebugTrace(this,'load');this.__debugSuperLoad(aPoint,aDataSrc);},save:function save(aLogger){_printDebugTrace(this,'save');this.__debugSuperSave(aLogger);},update:function update(aData){_printDebugTrace(this,'update',aData,'Old data = '+this.__debugSuperGetData());this.__debugSuperUpdate(aData);},clear:function clear(){_printDebugTrace(this,'clear',null,'Old data = '+this.__debugSuperGetData());this.__debugSuperClear();},getData:function getData(){_printDebugTrace(this,'getData');return this.__debugSuperGetData();},focus:function focus(){_printDebugTrace(this,'focus');this.__debugSuperFocus();},unfocus:function unfocus(){_printDebugTrace(this,'unfocus');this.__debugSuperUnocus();},set:function set(){if(this.isOptional())
_printDebugTrace(this,'set');else
_printDebugTrace(this,'set',null,'Warning, thring to set a non-optional editor');this.__debugSuperSet();},unset:function unset(){if(this.isOptional())
_printDebugTrace(this,'unset');else
_printDebugTrace(this,'unset',null,'Warning, thring to unset a non-optional editor');this.__debugSuperUnet();},awake:function awake(){_printDebugTrace(this,'awake');this.__debugSuperAwake();},startEditing:function startEditing(aEvent){_printDebugTrace(this,'startEditing');this.__debugSuperStartEditing(aEvent);},stopEditing:function stopEditing(){_printDebugTrace(this,'stopEditing');this.__debugSuperStopEditing();}}})();xtiger.editor.Plugin.prototype.pluginEditors['video'].registerFilter('debug',_DebugFilter);xtiger.editor.Plugin.prototype.pluginEditors['text'].registerFilter('debug',_DebugFilter);xtiger.editor.Plugin.prototype.pluginEditors['richtext'].registerFilter('debug',_DebugFilter);xtiger.editor.Plugin.prototype.pluginEditors['link'].registerFilter('debug',_DebugFilter);xtiger.service.ServiceFactory=(function _ServiceFactory(){var _GenericService=function(aHandleNode,aDocument){var _DEFAULT_PARAMS={};this._handle=aHandleNode;this._document=aDocument;this._params=_DEFAULT_PARAMS;this._key;this._types;};_GenericService.prototype={getKey:function(){return this._key;},getHandle:function(){return this._handle;},getParam:function(aKey){return this._params[aKey];},init:function(aType,aDefaultData,aKey,aParams){this._types=aType;if(aDefaultData){this._defaultData=aDefaultData;}
this._key=aKey;if(aParams){if(typeof(aParams)=='string')
xtiger.util.decodeParameters(aParams,this._params);else if(typeof(aParams)=='object')
this._params=aParams;}},makeSeed:function(){return[xtiger.factory('service'),this._types,this._defaultData,this._key,this._params];},_broadcast:function(aResourceKey,aData,aStartNode){var r;var _cur=aStartNode;var startCount=0;var endCount=0;var _key={key:this.getKey(),resource:aResourceKey};while(_cur){var editor=_cur.xttPrimitiveEditor;if(editor&&(editor.can('checkServiceKey'))){if(editor.execute('checkServiceKey',_key)){this.onBroadcast(editor,aData,aResourceKey);}}
if(_cur.firstChild){this._broadcast(aResourceKey,aData,_cur.firstChild);}
if(_cur.endRepeatedItem){endCount++;}
if((_cur!=aStartNode)&&_cur.startRepeatedItem){startCount++;}
if(endCount>startCount){return;}
_cur=_cur.nextSibling;}},_collectRegistrations:function(aRoleKey){var __innerCollectRegistrations=function(aService,aStartNode,aAccu){var _cur=aStartNode;var startCount=0;var endCount=0;while(_cur){var editor=_cur.xttPrimitiveEditor;if(editor){var _skparam=editor.getParam('service_key');if(_skparam&&_skparam!=''){var _sks=_skparam.split(' ');for(var _i=0;_i<_sks.length;_i++){var _m=_sks[_i].match(/^(\w+):(\w+)\[(.*)\]$/);if(_m[1]==aService.getKey()&&(!aRoleKey||_m[2]==aRoleKey)){aAccu.push(_m[3]);}}}}
if(_cur.firstChild){__innerCollectRegistrations(aService,_cur.firstChild,aAccu);}
if(_cur.endRepeatedItem){endCount++;}
if((_cur!=aStartNode)&&_cur.startRepeatedItem){startCount++;}
if(endCount>startCount){return;}
_cur=_cur.nextSibling;}};var _res=[];__innerCollectRegistrations(this,this.getHandle(),_res);return _res;},onUpdate:function(aProducer,aData,aResourceKey){this._broadcast(aResourceKey,aData,this.getHandle());},onBroadcast:function(aConsumer,aData,aResourceKey){},doBroadcastOnce:function(aConsumer,aData,aResourceKey){},onRemove:function(aModel,aData,aResourceKey){}};return{createModel:function createModel(aContainer,aXTService,aDocument){var hook=xtdom.createElement(aDocument,'span');xtdom.addClassName(hook,'xtt-service');aContainer.appendChild(hook);return hook;},createServiceFromTree:function createEditorFromTree(aHandleNode,aXTService,aDocument){var _instance=new _GenericService(aHandleNode,aDocument);var _types=aXTService.getAttribute('types');_instance=this.applyFilters(_instance,_types);_instance.init(_types,undefined,aXTService.getAttribute('key'),aXTService.getAttribute('param'));return _instance;},createServiceFromSeed:function createEditorFromSeed(aSeed,aClone,aDocument,aRepeater){var _instance=new _GenericService(aClone,aDocument);var _types=aSeed[1];var _defaultData=aSeed[2];var _key=aSeed[3];var _params=aSeed[4];_instance=this.applyFilters(_instance,_types);_instance.init(_types,_defaultData,_key,_params);return _instance;}}})();xtiger.registry.registerFactory('service',xtiger.util.filterable('service',xtiger.service.ServiceFactory));var _CopyService=(function(){return{'->':{'onBroadcast':'__duplicateBroadcast2Next'},onBroadcast:function(aModel,aData,aKey){aModel.update(aData);this.__duplicateBroadcast2Next(aModel,aData,aKey);}}})();xtiger.factory('service').registerDelegate('copy',_CopyService);var _CapitalizeService=(function(){return{'->':{'onBroadcast':'__capitalizeBroadcast2Next'},onBroadcast:function(aModel,aData,aKey){this.__capitalizeBroadcast2Next(aModel,aData.toUpperCase(),aKey);}}})();xtiger.factory('service').registerDelegate('capitalize',_CapitalizeService);xtiger.service.SuggestService=(function _SuggestService(){var _DEFAULT_PARAMS={'suggest_limit':8}
var _Suggester=function _Suggester(aModel){this._targetmodel=aModel;this._modelhandle=this._targetmodel.getHandle();this._document=this._modelhandle.ownerDocument;this._handle;this._popupmenu;this._popupdevice;this._suggests;};_Suggester.prototype={init:function(){this._handle=xtdom.createElement(this._document,'img');with(this._handle){src=xtiger.bundles.service_suggest.light_on;height=20;width=20;style.height=20;style.width=20;}
this._handle.xttSuggestServiceHandle=this;if(this._modelhandle.nextSibling)
this._modelhandle.parentNode.insertBefore(this._handle,this._modelhandle.nextSibling);else
this._modelhandle.parentNode.appendChild(this._handle);this._suggests=[];var _devKey='popupdevice';this._popupdevice=xtiger.session(this._document).load(_devKey);if(!this._popupdevice){this._popupdevice=new xtiger.editor.PopupDevice(this._document);xtiger.session(this._document).save(_devKey,this._popupdevice);}
var _this=this;xtdom.addEventListener(this._handle,'click',function(_ev){_this.onClick(_ev)},true);},update:function(aSuggests){this._handle.src=xtiger.bundles.service_suggest.light_on;this._suggests=aSuggests;},display:function(){this._handle.style.display='inline';},onClick:function(aEvent){this._handle.src=xtiger.bundles.service_suggest.light_off;if(this._suggests.length>0){this._popupdevice.startEditing(this._targetmodel,this._suggests,null,this._modelhandle)}},onPeekOption:function(aEvent){var _sel=this._popupmenu.peekEvent(aEvent);if(!_sel)
return;this._targetmodel.update(_sel);this._popupmenu.hide();}}
var _prepareRequest=function _prepareRequest(aServiceURL,aResource,aJsonQuery,aSelector,aLimit){var _xhr=xtiger.cross.getXHRObject();var _url=aServiceURL+'/'+aResource;_url+='?query='+aJsonQuery;_url+='&selector='+aSelector;if(aLimit&&aLimit>0)
_url+='&limit='+aLimit;_xhr.open('GET',_url,true);return _xhr;};var _toJSON=function _toJSON(aObject){var _parts=[];var is_list=(Object.prototype.toString.apply(aObject)==='[object Array]');for(var key in aObject){var value=aObject[key];if(typeof value=="function")
continue;if(typeof value=="object"){if(is_list)
_parts.push(_toJSON(value));else
_parts.push('"'+key+'":'+_toJSON(value));}else{var str="";if(!is_list)
str='"'+key+'":';if(typeof value=="number")
str+=value;else if(value===false)
str+='false';else if(value===true)
str+='true';else
str+='"'+value+'"';_parts.push(str);}}
var json=_parts.join(",");if(is_list)return'['+json+']';return'{'+json+'}';};var _onRequestReceived=function _onRequestReceived(aService,aRequest){try{var _datas=eval('('+aRequest.responseText+')');var _modrk=[];for(var _i=0;_i<_datas.length;_i++){var _forkey=_buildForKey(_datas[_i]['for']);for(_key in _datas[_i]){if(_key=='for')
continue;if(aService.updateResultsCache(_forkey,_key,_datas[_i][_key]))
_modrk.push(_key);}}
for(var _j=0;_j<_modrk.length;_j++)
aService._broadcast(_modrk[_j],aService.getResultsFromCache(_modrk[_j]),aService.getHandle());}catch(_err){xtiger.cross.log('warning','Suggest service : Server\'s answer is not understandable:'+"\n\t\""+
aRequest.responseText+'"'+"\n"+'Error message: '+"\n\t"+
_err.message+' ('+_err.fileName+':'+_err.lineNumber+')');}};var _buildForKey=function _buildForKey(aForKey){return''+aForKey['key']+':'+aForKey['value'];};return{'->':{'init':'__suggestSuperInit','onBroadcast':'__onBroadcast','onUpdate':'__onUpdate'},updateQueriesCache:function updateQueriesCache(aRKey,aProducer,aData){if(!this._cachedqueries[aRKey]){this._cachedqueries[aRKey]={};}
var _prodKey=aProducer.getUniqueKey();_prodKey=_prodKey?_prodKey:'nokey';if(aData!==null&&this._cachedqueries[aRKey][_prodKey]!=aData){this._cachedqueries[aRKey][_prodKey]=aData;return true;}
else if(aData==null&&this._cachedqueries[aRKey][_prodKey]!==null){delete this._cachedqueries[aRKey][_prodKey];return true;}
return false;},updateResultsCache:function updateResultsCache(aForKey,aResourceKey,aValues){if(!this._resultscache)
this._resultscache={};if(!this._resultscache[aForKey])
this._resultscache[aForKey]={};if(!this._resultscache[aForKey][aResourceKey])
this._resultscache[aForKey][aResourceKey]=[];var _newentry=false;for(var _i=0;_i<aValues.length;_i++){if(!xtiger.util.array_contains(this._resultscache[aForKey][aResourceKey],aValues[_i])){this._resultscache[aForKey][aResourceKey].push(aValues[_i]);_newentry=true;}}
return _newentry;},pruneResultsCache:function pruneResultsCache(aForKey){if(!this._resultscache)
return false;if(!this._resultscache[aForKey])
return false;delete this._resultscache[aForKey];return true;},clearResultsCache:function clearResultsCache(){this._resultscache={};},getResultsFromCache:function getResultsFromCache(aResourceKey,aForKey){if(aForKey){if(this._resultscache[aForKey]){return this._resultscache[aForKey][aResourceKey];}}
else{var _results=[];for(_fk in this._resultscache){if(this._resultscache[_fk][aResourceKey]){for(var _i=0;_i<this._resultscache[_fk][aResourceKey].length;_i++){if(!xtiger.util.array_contains(_results,this._resultscache[_fk][aResourceKey][_i]))
_results.push(this._resultscache[_fk][aResourceKey][_i]);}}}
return _results;}},getResourceKeysFromCache:function getResourceKeysFromCache(aForKey){var _results=[];if(aForKey){if(this._resultscache[aForKey]){for(_rk in this._resultscache[aForKey])
_results.push(_rk);}}
else{for(_fk in this._resultscache){for(_rk in this._resultscache[_fk])
_results.push(_rk);}}
return _results;},getJSONQuery:function getJSONQuery(){var _buf={}
for(_rk in this._cachedqueries){_buf[_rk]=[];for(_prodKey in this._cachedqueries[_rk])
_buf[_rk].push(this._cachedqueries[_rk][_prodKey]);}
return escape(_toJSON(_buf));},fetchSuggests:function fetchSuggests(){var _jsonQuery=this.getJSONQuery();var _selector=escape(_toJSON(this._collectRegistrations('consumer')));var _limit=this.getParam('suggest_limit')||_DEFAULT_PARAMS['suggest_limit'];var _xhr=_prepareRequest(this._params['suggest_URL'],this._params['suggest_resource'],_jsonQuery,_selector,_limit);var _this=this;_xhr.onreadystatechange=function(){if(_xhr.readyState==4){if(_xhr.status==200){_onRequestReceived(_this,_xhr);}
else{xtiger.cross.log('warning','Suggest service: request failed for query '+
_jsonQuery+' with status '+_xhr.status);}}}
try{_xhr.send(null);}catch(e){xtiger.cross.log('warning','Exception while contacting suggestion service : '+e.name);}},init:function init(aType,aDefaultData,aKey,aParams){this.__suggestSuperInit(aType,aDefaultData,aKey,aParams);var _url=this.getParam('suggest_URL');var _rsrc=this.getParam('suggest_resource');_url||xtiger.cross.log('warning','missing "sugest_URL" parameter on suggest service');_rsrc||xtiger.cross.log('warning','missing "suggest_resource" parameter on suggest service');this._suggestSavvy=_url&&_rsrc;this._cachedqueries={};this._pendingrequests=[];this._resultscache={};},onUpdate:function onUpdate(aModel,aData,aResourceKey){if(this._suggestSavvy&&this.updateQueriesCache(aResourceKey,aModel,aData)){this.fetchSuggests();}},onBroadcast:function onBroadcast(aConsumer,aData,aResourceKey){if(this._suggestSavvy){var _suggester;if(aConsumer.getHandle().nextSibling&&aConsumer.getHandle().nextSibling.xttSuggestServiceHandle)
_suggester=aConsumer.getHandle().nextSibling.xttSuggestServiceHandle;else{_suggester=new _Suggester(aConsumer);_suggester.init();}
_suggester.update(aData);_suggester.display();}},doBroadcastOnce:function doBroadcastOnce(aConsumer,aData,aResourceKey){if(this._suggestSavvy){this.onBroadcast(aConsumer,this.getResultsFromCache(aResourceKey),aResourceKey);}},onRemove:function onRemove(aProducer,aData,aResourceKey){if(this.suggestSavvy&&this.updateQueriesCache(aResourceKey,aProducer,null)){var _fk=_buildForKey({key:aResourceKey,value:aData});var _rks=this.getResourceKeysFromCache(_fk);if(this.pruneResultsCache(_fk)){for(var _i=0;_i<_rks.length;_i++)
this._broadcast(_rks[_i],this.getResultsFromCache(_rks[_i]),this.getHandle());}}}}})();xtiger.factory('service').registerDelegate('suggest',xtiger.service.SuggestService);xtiger.resources.addBundle('service_suggest',{'light_on':'light_on.png','light_off':'light_off.png'});var _TocService=(function(){return{'->':{'init':'__init','onBroadcast':'__duplicateBroadcast2Next'},_createEntry:function(id,data){var doc=this._container.ownerDocument;var entry=xtdom.createElement(doc,'li');var t=xtdom.createTextNode(doc,data);entry.appendChild(t);this._container.appendChild(entry);this._entries[id]=entry;},_updateEntry:function(id,data){this._entries[id].firstChild.data=data;},_deleteEntry:function(id){this._entries[id].parentNode.removeChild(this._entries[id]);this._deleted[id]=this._entries[id];this._entries[id]='removed';},init:function(aType,aDefaultData,aKey,aParams){this.__init(aType,aDefaultData,aKey,aParams);this._entries={};this._deleted={};var h=this.getHandle();var doc=h.ownerDocument;this._container=xtdom.createElement(doc,'ul');h.parentNode.insertBefore(this._container,h);},onUpdate:function(aModel,aData,aResourceKey){var id=aModel.getUniqueKey();if(!this._entries[id]){this._createEntry(id,aData);}else{if(this._entries[id]=='removed'){this._entries[id]=this._deleted[id];this._container.appendChild(this._entries[id]);delete this._deleted[id];}
this._updateEntry(id,aData);}},onRemove:function(aModel,aData,aResourceKey){var id=aModel.getUniqueKey();if(this._entries[id]){this._deleteEntry(id);}}}})();xtiger.factory('service').registerDelegate('toc',_TocService);xtiger.util.Logger=function(){this.errors=[];}
xtiger.util.Logger.prototype={inError:function(){return(this.errors.length>0);},logError:function(msg,url){if(msg.indexOf('$$$')!=-1){var m=url.match(/([^\/]*)$/);var name=m?m[1]:url;this.errors.push(msg.replace('$$$','"'+name+'"'));}else{this.errors.push(msg);}},printErrors:function(){return this.errors.join(';');}}
xtiger.util.LogWin=function(name,width,height,isTranscoding){var params="width="+width+",height="+height+",status=yes,resizable=yes,scrollbars=yes,title="+name;if(xtiger.cross.UA.IE){this.window=window.open('about:blank');}else{this.window=window.open(null,name,params);}
this.doc=this.window.document;this.doc.open();this.isTranscoding=isTranscoding;}
xtiger.util.LogWin.prototype={dumpSchema:function(form,stylesheet,template){var dump=new xtiger.util.SchemaLogger();form.setSerializer(new xtiger.editor.SchemaSerializer());var data=form.serializeData(dump);this.write(dump.dump('*'));this.close();},dump:function(form,stylesheet,template){var buffer;var dump=new xtiger.util.DOMLogger();form.setSerializer(new xtiger.editor.BasicSerializer());var data=form.serializeData(dump);buffer="<?xml version=\"1.0\"?>\n"
if(stylesheet){buffer+='<?xml-stylesheet type="text/xml" href="'+stylesheet+'"?>\n';}
if(template){buffer+='<?xtiger template="'+template+'" version="1.0" ?>\n';}
buffer+=dump.dump('*');this.write(buffer);this.close();},transcode:function(text){var filter1=text.replace(/</g,'&lt;');var filter2=filter1.replace(/\n/g,'<br/>');var filter3=filter2.replace(/ /g,'&nbsp;');return filter3;},write:function(text){var t=this.isTranscoding?this.transcode(text):text;this.doc.writeln(t);},close:function(text){this.doc.close();},dispose:function(){this.doc.close();}}
xtiger.util.fileDialog=function(mode,filter,msg){var fp;try{netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");}catch(e){alert("Permission to get enough privilege was denied.");return false;}
var nsIFilePicker=Components.interfaces.nsIFilePicker;fp=Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);if(filter){fp.appendFilter("My filter",filter);}
var m;if(mode=='open'){m=nsIFilePicker.modeOpen;}else if(mode=='save'){m=nsIFilePicker.modeSave;}else{m=nsIFilePicker.modeGetFolder;}
fp.init(window,msg,m);var res=fp.show();if((res==nsIFilePicker.returnOK)||(res==nsIFilePicker.returnReplace)){return fp.file.path;}else{return false;}}
var DynamicFilterManager=Class.create({initialize:function(){this.timer=null;this.filters=[];var me=this;Event.observe(window,'resize',function(){me.resize()});},addFilter:function(filter){if(this.hasFilter(filter.filterName)){return;}
this.filters.push(filter);},addFilters:function(){var me=this;$$('.dynamic_filter').each(function(filter){var f=new DynamicFilter(filter.id.substring(20));f.reset();me.addFilter(f);});},hasFilter:function(filterName){return this.filters.any(function(filter){return filter.filterName==filterName;});},getFilter:function(filterName){return this.filters.find(function(filter){return filter.filterName==filterName;});},resize:function(){var height=document.viewport.getHeight()
-168
-30
-28;this.filters.each(function(filter){filter.setHeight(height);});},open:function(filterName){if(!this.hasFilter(filterName)){return;}
this.resize();this.filters.each(function(filter){if(filter.filterName==filterName){filter.open();}else{filter.hide();}});},close:function(filterName){if(!this.hasFilter(filterName)){return;}
this.getFilter(filterName).close();},hide:function(filterName){if(!this.hasFilter(filterName)){return;}
this.getFilter(filterName).hide();},restore:function(filterName){this.filters.each(function(filter){if(filter.filterName==filterName){filter.restore();}else{filter.hide();}});},reset:function(filterName){if(!this.hasFilter(filterName)){return;}
this.getFilter(filterName).reset();},showLinksIfNeeded:function(filterName){if(this.hasFilter(filterName)){$('dynamic_filter_links_'+filterName).show();}},getSearchParameters:function(filterName){var parameters={};if(this.hasFilter(filterName)){parameters=this.getFilter(filterName).getSearchParameters();}
if(typeof parameters['filters']=='undefined'){parameters['filters']=[];}
if(typeof parameters['ranking']=='undefined'){parameters['ranking']='friends';}
if(typeof parameters['ranking_only']=='undefined'){parameters['ranking_only']=false;}
if(typeof parameters['tags']=='undefined'){parameters['tags']=[];}
if(typeof parameters['price_range']=='undefined'){parameters['price_range']='';}
return parameters;},willUpdate:function(){var me=this;gSpinner.show(false);this.clearTimer();this.timer=setTimeout(function(){me.update();},2000);},update:function(){this.clearTimer();pm.getActiveSearchTab().requestUpdateCache();},clearTimer:function(){if(this.timer){clearTimeout(this.timer);this.timer=null;}}});var DynamicFilter=Class.create({initialize:function(filterName){this.filterName=filterName;this.filterPane=$('dynamic_filter_pane_'+this.filterName);this.filterPaneContent=$$('#dynamic_filter_pane_'+this.filterName+' .content')[0];this.isOpened=false;this.isVisible=false;this.bindEvents();},bindEvents:function(){var me=this;$$('#dynamic_filter_pane_'+this.filterName+' .filters input').each(function(input){input.observe('click',function(event){if(input.checked){$('dynamic_filter_'+me.filterName+'_filter_showcase').checked=true;}
dynamicFilterManager.willUpdate();});});$$('#dynamic_filter_'+this.filterName+'_filter_showcase').each(function(element){element.observe('click',function(event){if(!Event.element(event).checked){$$('#dynamic_filter_pane_'+me.filterName+' .filters input').each(function(input){input.checked=false;});}
dynamicFilterManager.willUpdate();});});$$('#dynamic_filter_pane_'+this.filterName+' .tags input[type=radio]').each(function(input){input.observe('change',function(event){dynamicFilterManager.willUpdate();});});$$('#dynamic_filter_pane_'+this.filterName+' .price_range select').each(function(select){select.observe('change',function(event){dynamicFilterManager.willUpdate();});});$$('#dynamic_filter_pane_'+this.filterName+' .ranking input').each(function(input){input.observe('click',function(event){dynamicFilterManager.willUpdate();});});},setHeight:function(height){this.filterPaneContent.setStyle({height:height+'px'});},open:function(){this.isOpened=true;this.show();},close:function(){this.isOpened=false;this.hide();},hide:function(){var me=this;if(this.isVisible){new Effect.Fade(this.filterPane,{duration:0.1,afterFinish:function(){me.isVisible=false;me.updateDisplayHideLinks();}});}},show:function(){var me=this;if(!this.isVisible){new Effect.Appear(this.filterPane,{duration:0.1,to:0.9,afterFinish:function(){me.isVisible=true;me.updateDisplayHideLinks();}});}},restore:function(){if(this.isOpened){this.show();}},reset:function(){$$('#dynamic_filter_pane_'+this.filterName+' .filters input').each(function(input){input.checked=false;});if($('dynamic_filter_'+this.filterName+'_ranking_friends')!=null){$('dynamic_filter_'+this.filterName+'_ranking_friends').checked=true;}
$$('#dynamic_filter_pane_'+this.filterName+' .tags select').each(function(select){select.value='';});},updateDisplayHideLinks:function(){if(this.isVisible){$$('.dynamic_filter_link_open').invoke('hide');$$('.dynamic_filter_link_close').invoke('show');}else{$$('.dynamic_filter_link_open').invoke('show');$$('.dynamic_filter_link_close').invoke('hide');}},getSearchParameters:function(){var parameters={filters:[],tags:[],ranking:'friends',ranking_only:false,price_range:''};$$('#dynamic_filter_pane_'+this.filterName+' .filters input').each(function(input){if(input.checked){parameters['filters'].push(input.value);}});$$('#dynamic_filter_pane_'+this.filterName+' .ranking input[type=radio]').each(function(input){if(input.checked){parameters['ranking']=input.value;var only=$(input.id+"_only");if(only!=null&&only.checked){parameters['ranking_only']=true;}}});$$('#dynamic_filter_pane_'+this.filterName+' .tags input[type=radio]').each(function(input){if(input.checked&&input.value!=''){parameters['tags'].push(input.value);}});$$('#dynamic_filter_pane_'+this.filterName+' .price_range select').each(function(select){if(select.value!=''){parameters['price_range']=select.value;}});return parameters;}});var dynamicFilterManager=new DynamicFilterManager();function df_showSubTags(e,filter_for,level){$$('#dynamic_filter_pane_'+filter_for+' .level'+level+' ul').invoke('hide');var ul=$(e).up().down('ul');if(ul!=null){ul.show();}}
function displayCalendar(keyword){if(typeof keyword!='undefined'){page_navigate('calendar-'+keyword);}else{page_navigate('calendar');}}
function requestCalendar(keyword){introDestroy();RedBox.close();var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();var parameters={swlat:sw.lat(),swlng:sw.lng(),nelat:ne.lat(),nelng:ne.lng()};if(typeof keyword!='undefined'){parameters['name_or_tag']=keyword;}
if(typeof keyword!='undefined'&&keyword=='fornoise'){parameters['from']=0;parameters['to']=84;}
if(typeof keyword!='undefined'&&keyword=='festival'){parameters['from']=0;parameters['to']=84;}
new Ajax.Request('/events/calendar',{parameters:parameters,asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()}});}
function initCalendar(from,to){calendar.init(from,to);}
var calendar=null;var Calendar=Class.create({initialize:function(position,dates){var me=this;this.dates=dates;this.sliderDom=null;this.handlersDom=null;this.slider=null;this.doUpdate=true;this.page=1;this.filter='';this.lastPredefiedFilter='';this.order='quality';this.from=0;this.to=21;this.swlat=position.swlat;this.swlng=position.swlng;this.nelat=position.nelat;this.nelng=position.nelng;},init:function(from,to){var me=this;if(typeof from!='undefined'){this.from=from;}
if(typeof to!='undefined'){this.to=to;}
this.filter='';this.handlersDom=[$$('#events_slider .left_handle')[0],$$('#events_slider .right_handle')[0]];this.sliderDom=$$('#events_slider .track')[0];this.slider=new Control.Slider(this.handlersDom,this.sliderDom,{range:$R(0,84),sliderValue:[me.from,me.to],restricted:true,spans:$$('#events_slider .between_handles'),values:[0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,56,70,84],onSlide:function(hvalues){$$('#calendar .dates span:nth-child(1)')[0].innerHTML=me.dates[hvalues[0]];$$('#calendar .dates span:nth-child(2)')[0].innerHTML=me.dates[hvalues[1]];},onChange:function(hvalues,slider){if(hvalues[0]<hvalues[1]){if(me.doUpdate&&(hvalues[0]!=me.from||hvalues[1]!=me.to)){me.setLimits(hvalues);}
me.doUpdate=true;}else{me.doUpdate=false;if(me.from!=hvalues[0]){me.slider.setValue(me.from,0);}else{me.slider.setValue(me.to,1);}}}});$('order_by').observe('change',function(){me.setOrder(this.value);});$('update_filter').observe('click',function(){me.setFilter($('name_or_tag_filter').value);});},ajaxizePaginationLinks:function(){$$('#calendar_content .pagination a').each(function(link){Event.observe(link,'click',function(event){new Ajax.Updater('calendar_content',this.href,{method:'get',evalScripts:true,onCreate:showGlobalSpinner,onComplete:hideGlobalSpinner});event.stop();});});},setOrder:function(order){this.order=order;this.page=1;this.updateList();},setLimits:function(values){this.from=values[0];this.to=values[1];this.page=1;this.updateList();},setFilter:function(filter){if(filter!=this.filter){var e1='tag_filter_'+this.filter;var e2='tag_filter_'+filter;if($(e1)){$(e1).removeClassName('selected');}else{if(this.filter==''){$('tag_filter_all').removeClassName('selected');}else{$('tag_filter_custom').removeClassName('selected');}}
if($(e2)){$(e2).addClassName('selected');this.lastPredefiedFilter=filter;}else{if(filter==''){$('tag_filter_all').addClassName('selected');this.lastPredefiedFilter=filter;}else{$('tag_filter_custom').addClassName('selected');}}
this.filter=filter;this.page=1;this.updateList();}},updateList:function(hvalues,slider){var me=this;new Ajax.Updater('calendar_content','/events/update_calendar',{evalScripts:true,method:'get',parameters:{order:me.order,swlat:me.swlat,swlng:me.swlng,nelat:me.nelat,nelng:me.nelng,from:me.from,to:me.to,name_or_tag:me.filter,page:me.page},onCreate:showGlobalSpinner,onComplete:hideGlobalSpinner});},updateTimeline:function(){var parameters=$H({swlat:this.swlat,swlng:this.swlng,nelat:this.nelat,nelng:this.nelng,name_or_tag:this.filter});loadTimeline('/events/timeline?'+parameters.toQueryString(),'my-timeline');},showCustomFilter:function(){$('predefined_filter').hide();$('custom_filter').show();if($('name_or_tag_filter').value!=''){this.setFilter($('name_or_tag_filter').value);}},hideCustomFilter:function(){this.setFilter(this.lastPredefiedFilter);$('custom_filter').hide();$('predefined_filter').show();}});function calendarNameOrTagKeypress(event){if(event.keyCode==Event.KEY_RETURN){calendar.setFilter(Event.element(event).value);return false;}
return true;}
function displayMyspace(parameters){if(typeof parameters=='undefined'){parameters={};}
if(typeof parameters.tab!='undefined'){myspace_tabToShow=parameters.tab}
if(typeof parameters.subtab!='undefined'){myspace_subTabToShow=parameters.subtab}
if(typeof parameters.thread!='undefined'){myspace_threadToShow=parameters.thread}
page_navigate('myspace');}
function requestMyspace(){introDestroy();RedBox.close();parameters={tab:myspace_tabToShow,subtab:myspace_subTabToShow,thread:myspace_threadToShow};new Ajax.Request('/myspace',{method:'get',parameters:parameters,asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()}});myspace_tabToShow=null;myspace_subTabToShow=null;myspace_threadToShow=null;}
function displayUser(id){page_navigate('user-'+id);}
function requestUser(id){introDestroy();RedBox.close();new Ajax.Request('/users/show/'+id,{asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()}});}
var myspace_tabToShow=null;var myspace_subTabToShow=null;var myspace_threadToShow=null;var myspace=null;var Myspace=Class.create({initialize:function(uid,loadedPanes){this.uid=uid;if(typeof loadedPanes=='undefined'){loadedPanes=[];}
this.panes=$H({newsfeed:false,friends:false,profile:false,rendezvous:false,suggest:false});for(var i=0;i<loadedPanes.length;i++){this.panes.set(loadedPanes[i],true);}},abortRequests:function(){var me=this;this.panes.each(function(p){if(typeof p.value=='object'){p.value.abort();me.panes.set(p.key,false);}});},loadPane:function(paneName){if(!this.panes.get(paneName)){this.reloadPane(paneName);}},reloadPane:function(paneName){var me=this;this.panes.set(paneName,new Ajax.Updater('pane_'+paneName,'/myspace/pane_'+paneName,{asynchronous:true,evalScripts:true,method:'get',parameters:{id:this.uid},onSuccess:function(){me.panes.set(paneName,true);}}));},loadPanes:function(paneNames){if(typeof paneNames=='undefined'){paneNames=this.panes.keys();}
for(var i=0;i<paneNames.length;i++){this.loadPane(paneNames[i]);}},reloadPanes:function(paneNames){if(typeof paneNames=='undefined'){paneNames=this.panes.keys();}
for(var i=0;i<paneNames.length;i++){this.reloadPane(paneNames[i]);}}});function myspace_selectTab(tabName){myspace_selectPane(tabName);}
function myspace_selectPane(paneName){if(paneName!=null&&paneName!=''&&$('pane_'+paneName)){$$('#myspace .myspacecontent .panes li.pane').invoke('hide');$$('#myspace .myspacecontent .tabs li.tab').invoke('removeClassName','selected');$('pane_'+paneName).show();if($('tab_'+paneName)){$('tab_'+paneName).addClassName('selected');}}}
function myspace_selectSubTab(tabName,subTabName){myspace_selectSubPane(tabName,subTabName);}
function myspace_selectSubPane(paneName,subPaneName){myspace_closeThread();myspace_selectPane(paneName,true);if(subPaneName!=null&&subPaneName!=''&&$('pane_'+paneName)&&$('subpane_'+paneName+'_'+subPaneName)){$$('#myspace .myspacecontent #pane_'+paneName+' .subpanes li.subpane').invoke('hide');$$('#myspace .myspacecontent #pane_'+paneName+' .subtabs li.subtab').invoke('removeClassName','selected');$('subpane_'+paneName+'_'+subPaneName).show();if($('subtab_'+paneName+'_'+subPaneName)){$('subtab_'+paneName+'_'+subPaneName).addClassName('selected');}}}
var myspace_openedThreadId=null;function myspace_openThread(threadId,filter){if(threadId==myspace_openedThreadId){myspace_closeThread(threadId);}else{myspace_closeThread(myspace_openedThreadId);new Ajax.Request('/messages/touch/'+threadId);if(typeof filter!='undefined'){content_element='message_content_'+threadId+'_'+filter;unread_element='message_unread_'+threadId+'_'+filter;}else{content_element='message_content_'+threadId;unread_element='message_unread_'+threadId}
new Effect.Parallel([new Effect.SlideDown(content_element,{sync:true}),new Effect.Appear(content_element,{sync:true})],{queue:'end'});if($(unread_element)){$(unread_element).fade();}
myspace_openedThreadId=threadId;}}
function myspace_closeThread(){if(myspace_openedThreadId!=null){new Ajax.Request('/messages/stop_reading',{method:'get',parameters:{id:myspace_openedThreadId}});var content_in_feed=$('message_content_'+myspace_openedThreadId);if(content_in_feed&&content_in_feed.visible()){new Effect.Parallel([new Effect.SlideUp(content_in_feed,{sync:true}),new Effect.Fade(content_in_feed,{sync:true})],{queue:'end'});}
var content_in_messages=$('message_content_'+myspace_openedThreadId+'_messages');if(content_in_messages&&content_in_messages.visible()){new Effect.Parallel([new Effect.SlideUp(content_in_messages,{sync:true}),new Effect.Fade(content_in_messages,{sync:true})],{queue:'end'});}
myspace_openedThreadId=null;}}
function myspace_showReply(threadId,filter){if(typeof filter!='undefined'){$('message_replylink_'+threadId+'_'+filter).show();$('message_form_'+threadId+'_'+filter).show();}else{$('message_replylink_'+threadId).show();$('message_form_'+threadId).show();}}
function myspace_updateThread(threadId){new Ajax.Request('/users/message_thread_content/'+threadId,{method:'get',onCreate:function(){gSpinner.show()},onSuccess:function(response){var content_in_feed=$('message_content_'+threadId);if(content_in_feed){content_in_feed.innerHTML=response.responseText;}
var content_in_messages=$('message_content_'+threadId+'_messages');if(content_in_messages){content_in_messages.innerHTML=response.responseText;}
gSpinner.hide();}})}
function myspace_toggleReadersList(link_element){link_element.next().toggle();}
function myspace_initFriendPicker(friends,groups){myspace_friendPicker=new FriendsAutocompleter($('message_friends_entry'),$('message_friends_suggestions'),friendspicker_normalize(friends,groups),{partialChars:1,fullSearch:true,set:new FriendsSet({formUpdater:new FormUpdater('message[participants]','message_send_form'),friendsListContainer:$('message_friends_list_container'),afterUpdate:function(set){var email=$('also_send_by_mail');var help=$('message_friends_list_help');if(set.size()==0){help.show();if(email!=null){email.hide();}}else{help.hide();if(email!=null){email.show();}}}})});}
function myspace_orderFriends(e){if(e.value=='points'){$('friends_ordered_by_points').show();$('friends_ordered_by_alpha').hide();}else{$('friends_ordered_by_points').hide();$('friends_ordered_by_alpha').show();}}
var myspace_friendPicker=null;var NewsfeedPaginator=Class.create({initialize:function(filter){this.isFirstPageDisplayed=false
this.page=0;this.filter=filter;this.element=null;},nextPage:function(){if(this.element==null){this.element=$$('#newsfeed_'+this.filter+'_content .stories').first();}
this.page++;this.update();},firstPage:function(){if(!this.isFirstPageDisplayed){var me=this;if(this.filter.startsWith('my_')){var filter=me.filter.substring(3);var only_mine=1;}else{var filter=me.filter;var only_mine=0;}
new Ajax.Updater($('newsfeed_'+this.filter+'_content'),'/users/feeds',{method:'get',evalScripts:true,parameters:{page:me.page,filter:filter,only_mine:only_mine}});this.isFirstPageDisplayed=true;}},update:function(){gSpinner.show();var me=this;if(this.filter.startsWith('my_')){var filter=me.filter.substring(3);var only_mine=1;}else{var filter=me.filter;var only_mine=0;}
new Ajax.Updater(this.element,'/users/more_feeds',{method:'get',insertion:'bottom',evalScripts:true,onComplete:function(){gSpinner.hide();},parameters:{page:me.page,filter:filter,only_mine:only_mine}});}});function myspace_toggleReviewFilter(e){if(e.checked){$('newsfeed_reviews_content').hide();$('newsfeed_my_reviews_content').show();newsfeedPaginators['my_reviews'].firstPage();}else{-
$('newsfeed_reviews_content').show();$('newsfeed_my_reviews_content').hide();newsfeedPaginators['reviews'].firstPage();}}
var newsfeedPaginators=[];function myspace_changeProfilePicture(link){link.hide();$$('#myspace .change_profile_picture')[0].show();}
function myspace_importProfileFromFacebook(){$('myspace_subpane_profile_edit_fb_button').hide();$('subtab_profile_facebook').show();myspace_selectSubPane('profile','facebook');new Ajax.Updater($$('#subpane_profile_facebook .panecontent .spinner')[0],'/fb_connect/import_data',{insertion:Element.replace});}
function myspace_cancelImportProfileFromFacebook(){myspace_selectSubPane('profile','edit')}
var listManager=null;var ListManager=Class.create({initialize:function(lists,users,newListText){this.newListText=newListText;this.init(lists,users);},init:function(lists,users){$('list_contacts').hide();var me=this;this.users=users;this.lists=[];this.filter=null
this.patterns=[];lists.each(function(list){members=[];list.members.each(function(member){members.push(me.findUser(member['id']));});me.lists.push({name:list['name'],id:list['id'],members:members});});var lists_list='';this.lists.each(function(list){lists_list+='<li id="list_'+list['id']+'"><a href="#" onclick="listManager.setCurrentList('+list['id']+');return false;">'+list['name']+'</a></li>';});lists_list+='<li id="list_0"><strong><a href="#" onclick="listManager.setCurrentList(0);return false;">'+this.newListText+'</a></strong></li>';$('lists_list').innerHTML=lists_list;this.currentList=null;},findList:function(listId){var list=this.lists.find(function(l){return l['id']==listId;});if(list==null){list={name:this.newListText,members:[],id:0};}
return list;},findUser:function(userId){return this.users.find(function(user){return user['id']==userId;});},setCurrentList:function(listId){this.currentList=Object.clone(this.findList(listId));this.filter='all';if(this.currentList['id']==0){$('save_list').show();$('delete_list').hide();$('rename_list_field').show();$('rename_list_switch').hide();setTimeout(function(){$('contact_list_name').focus();$('contact_list_name').select();},1);this.setFilter('all');}else{$('save_list').show();$('delete_list').show();$('rename_list_field').hide();$('rename_list_switch').show();this.setFilter('in');}
$('delete_list_confirm').hide();$$('#lists_list li').each(function(li){li.removeClassName('selected');})
$('list_'+this.currentList['id']).addClassName('selected');$('name_error').hide();$('list_error').hide();$('list_help').hide();$('list_saved').hide();$('list_deleted').hide();$('list_contacts').show();$('list_name').innerHTML=this.currentList['name'];$('contact_list_name').value=this.currentList['name'];this.drawList();},drawList:function(){var me=this;var users='';this.users.each(function(user){var isUserInCurrentList=me.isUserInCurrentList(user['id']);var includeUser=me.filter=='all'||(me.filter=='in'&&isUserInCurrentList)||(me.filter=='out'&&!isUserInCurrentList);var splittedName=user['name'].toLowerCase().split(new RegExp(' '));var doesUserMatchesSubstring=me.patterns==[]||me.patterns.all(function(p){return splittedName.any(function(s){return s.startsWith(p);});});if(includeUser&&doesUserMatchesSubstring){users+=me.buildUserBox(user,isUserInCurrentList);}});$$('#list_contacts .users_selector li').each(function(li){li.removeClassName('selected');});$$('#list_contacts .users_selector li.'+this.filter)[0].addClassName('selected');$('users_list_pane').innerHTML=users;},isUserInCurrentList:function(userId){return this.currentList.members.any(function(member){return member['id']==userId;});},toggleUser:function(userId){if(this.isUserInCurrentList(userId)){this.currentList.members=this.currentList.members.reject(function(member){return member['id']==userId;});}else{this.currentList.members.push(this.findUser(userId));}
this.drawList();},setFilter:function(filter){this.filter=filter;this.drawList();},setPattern:function(pattern){this.patterns=pattern.toLowerCase().split(new RegExp(' ')).without('').sortBy(function(e){return-e.length;});this.drawList();},updateListName:function(listName){if(listName!=''){$('list_name').innerHTML=listName;}else{$('list_name').innerHTML='&nbsp';}},listNameKeyPressed:function(event){if(event.keyCode==Event.KEY_RETURN){this.saveCurrentList();return false;}
return true;},showRenameListField:function(){$('rename_list_field').show();$('rename_list_switch').hide();$('contact_list_name').focus();$('contact_list_name').select();},showError:function(errorMessages){$('list_error').show();errorMessages=errorMessages.map(function(msg){return'<li>'+msg+'</li>';});$$('#list_error ul')[0].innerHTML=errorMessages.join('');},buildUserBox:function(user,inList){var htmlClass='';var selected='';if(inList){htmlClass=' class="selected"'
selected='<img class="selected" src="/images/user_selected.png" alt="selected" title="selected" />';}
var username=user['name'].split(new RegExp(' '));this.patterns.each(function(p){username=username.map(function(u){return u.replace(new RegExp('^('+p+')','i'),'<strong>$1</strong>');});});username=username.join(' ');var template='<a href="#"'+htmlClass+' onclick="listManager.toggleUser('+user['id']+');return false;">'
+'<img src="'+user['picture']+'" alt="'+user['name']+'" title="'+user['name']+'" />'
+selected
+username
+'</a>';return template;},deleteCurrentList:function(){if(this.currentList&&this.currentList['id']!=0){$('delete_list_confirm').show();$('save_list').hide();$('delete_list').hide();}},deleteCurrentListConfirmed:function(){if(this.currentList&&this.currentList['id']!=0){var me=this;showGlobalSpinner();new Ajax.Request('/users/delete_contact_list',{method:'post',parameters:{id:me.currentList['id']}});}},deleteCurrentListCancelled:function(){$('delete_list_confirm').hide();$('delete_list').show();$('save_list').show();},saveCurrentList:function(){if(this.currentList&&$F('contact_list_name')!=''){var me=this;var list='';showGlobalSpinner();this.currentList.members.each(function(user){list+=' '+user['id'];});new Ajax.Request('/users/save_contact_list',{method:'post',parameters:{id:me.currentList['id'],name:$F('contact_list_name'),list:list}});}else if($F('contact_list_name')==''){$('name_error').show();}}});var gSpinner=null;var Spinner=Class.create({initialize:function(element){this.element=element;this.count=0;},show:function(incrementCount){if(incrementCount==null){incrementCount=true;}
if(incrementCount){this.count++;}
$(this.element).show();},hide:function(force){force=true;if(this.count>0){this.count--;}
if(force){this.count=0;}
if(this.count==0){$(this.element).hide();}}});gSpinner=new Spinner('global_spinner');var geocoder=null;var map=null;var gdir=null;var marker=null;var simpleMarker=null;var isInIntro=false;var redboxOpenedWindowUrl=null;var pm=null;var isSideBarExtended=false;var isSideBarLeftExtended=0;var crossHairActive=false;var myplaces=new Array();var name;var currheight;var currwidth;var party=null;var acc_status=[true,true];var pictureGalleryPage=0;var contactLists;var RecaptchaOptions={theme:'clean',lang:I18n.locale};function getIeVersion(){var ua=navigator.userAgent;var ua=navigator.userAgent;var re=new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");if(re.exec(ua)!=null){rv=parseFloat(RegExp.$1);return rv;}
return-1;}
Ajax.Request.prototype.abort=function(){this.transport.onreadystatechange=Prototype.emptyFunction;this.transport.abort();Ajax.activeRequestCount--;};function addslashes(str){return(str+'').replace(/([\\"'])/g,"\\$1").replace(/\0/g,"\\0");}
function load(lat,lng,zoomlevel){if(GBrowserIsCompatible()){map=new GMap2(document.getElementById("map"));map.addControl(new GSmallMapControl(),new GControlPosition(G_ANCHOR_BOTTOM_LEFT,new GSize(5,5)));map.addControl(new GMapTypeControl(true),new GControlPosition(G_ANCHOR_BOTTOM_LEFT,new GSize(45,5)));map.setCenter(new GLatLng(lat,lng),zoomlevel);map.enableScrollWheelZoom();geocoder=new GClientGeocoder();pm=new PlaceManager(map);GEvent.bind(map,"click",this,clickOnMap);GEvent.bind(map,"moveend",pm,pm.mapMoved);GEvent.bind(pm,"rankingchanged",this,rankingChanged);var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();document.forms.what_form.swlat.value=sw.lat();document.forms.what_form.swlng.value=sw.lng();document.forms.what_form.nelat.value=ne.lat();document.forms.what_form.nelng.value=ne.lng();initializeMapDirections();YAHOO.util.History.initialize("yui-history-field","yui-history-iframe");}}
function initLocales(){_translations=I18n.t('calendar_date_select.translations');Date.first_day_of_week=I18n.t('calendar_date_select.date.first_day_of_week');Date.weekdays=I18n.t('calendar_date_select.date.weekdays');Date.months=I18n.t('calendar_date_select.date.months');}
function setLocale(locale){var currentLocation=window.location.href.split('#');var currentPage=currentLocation[0];var newPage;if(/locale=([a-zA-Z_-]+)/.test(currentPage)){newPage=currentPage.replace(/locale=([a-zA-Z_-]+)/,"locale="+locale)}else if(/\?/.test(currentPage)){newPage=currentPage+"&locale="+locale;}else{newPage=currentPage+"?locale="+locale;}
if(typeof(currentLocation[1])=='undefined'){window.location.replace(newPage);}else{window.location.replace(newPage+"#"+currentLocation[1]);}}
function transformInsideLabels(){$$('label.inside').each(function(label){var input=$(label.readAttribute('for'));if(input&&((input.tagName.toLowerCase()=='input'&&input.readAttribute('type').toLowerCase()=='text')||input.tagName.toLowerCase()=='textarea')){if(input.labelValue==undefined){input.labelValue=label.textContent||label.innerHTML;input.styleInsideLabel=styleInsideLabel;input.styleInsideLabelWithFocus=styleInsideLabelWithFocus;input.styleInsideLabel();label.hide();input.observe('focus',input.styleInsideLabelWithFocus);input.observe('blur',input.styleInsideLabel);}}});$$('form').each(function(form){if(!form.clearInsideLabelsTemporarly){form.clearInsideLabelsTemporarly=clearInsideLabelsTemporarly;form.observe('submit',form.clearInsideLabelsTemporarly);form.serialize=Form.serialize.methodize()}});}
function styleInsideLabel(){this.removeClassName('focused');if(this.value&&this.value!=this.labelValue){this.addClassName('active');this.removeClassName('inactive');}else{this.addClassName('inactive');this.removeClassName('active');this.value=this.labelValue;}}
function styleInsideLabelWithFocus(){this.addClassName('focused');this.removeClassName('active');this.removeClassName('inactive');if(this.value==this.labelValue)this.value="";}
function clearInsideLabelsTemporarly(){this.descendants().each(function(input){if(input.labelValue){if(input.value==input.labelValue){input.value=null;setTimeout(function(){input.styleInsideLabel();},10);}}});}
Form.Methods.serializeWithInsideLabelsRemoved=function(form,options){if(form.clearInsideLabelsTemporarly)form.clearInsideLabelsTemporarly();return Form.serializeWithoutInsideLabelsRemoved(form,options);};Form.Methods.serializeWithoutInsideLabelsRemoved=Form.Methods.serialize;Form.Methods.serialize=Form.Methods.serializeWithInsideLabelsRemoved;Object.extend(Form,Form.Methods);function onAjaxFormLoading(formId){var form=$(formId);if(!form)return;var buttons=form.select('input[type="submit"]','input[type="image"]','input[type="button"]');buttons.invoke('disable');var spinners=form.select('.spinner');spinners.invoke('show');}
function onAjaxFormComplete(formId){var form=$(formId);if(!form)return;var buttons=form.select('input[type="submit"]','input[type="image"]','input[type="button"]');buttons.invoke('enable');var spinners=form.select('.spinner');spinners.invoke('hide');}
function showGlobalSpinner(){gSpinner.show();}
function hideGlobalSpinner(){gSpinner.hide();}
function keypressed(event){var key=event.which||event.keyCode;if(key==Event.KEY_ESC){gSpinner.hide();displayMap();}}
function filterAndOrderReviews(type,id){gSpinner.show();url='/'+type+'/reviews/'+id
new Ajax.Updater('reviews_pane',url,{parameters:{lang:$F('review_language'),order:$F('review_order')},evalScripts:true,onComplete:function(){gSpinner.hide();}});}
function transformReviewsWillPaginateLinksToAjaxCalls(){$$('.pagination a').each(function(link){Event.observe(link,'click',function(event){gSpinner.show();url=this.href.replace('info','reviews')
new Ajax.Updater('reviews_pane',url,{evalScripts:true,onComplete:function(){gSpinner.hide();}});event.stop();});});}
function showSimpleMarker(id,type,name,lat,lng,street,city,country){var point=new GLatLng(lat,lng);pm.simpletags.clearMarkers();var currentTab=pm.getActiveSearchTab();simpleMarker=null;if(simpleMarker==null){simpleMarker=new BallMarker(point);simpleMarker.id=id;}
if(id==0){var parameters=addslashes($H({lat:lat,lng:lng,st:street,ci:city,co:country}).toQueryString());simpleMarker.bindInfoWindowHtml("<a href=# onclick=\"new Ajax.Request('/places/new?"+parameters+"');return false;\">"+I18n.t('create_place')+"</a>");}else{if(type=='Event'){new Ajax.Request('/events/smallinfo/'+id,{onLoading:function(){gSpinner.show()},onSuccess:function(transport){simpleMarker.bindInfoWindowHtml(transport.responseText,noCloseOnClick=true);simpleMarker.openInfoWindowHtml(transport.responseText,noCloseOnClick=true);}});}else if(type=='Place'){new Ajax.Request('/places/smallinfo/'+id,{onLoading:function(){gSpinner.show()},onSuccess:function(transport){simpleMarker.bindInfoWindowHtml(transport.responseText,noCloseOnClick=true);simpleMarker.openInfoWindowHtml(transport.responseText,noCloseOnClick=true);}});}else{new Ajax.Request('/users/smallinfo/'+id,{onLoading:function(){gSpinner.show()},onSuccess:function(transport){simpleMarker.bindInfoWindowHtml(transport.responseText,noCloseOnClick=true);simpleMarker.openInfoWindowHtml(transport.responseText,noCloseOnClick=true);}});}}
pm.simpletags.addMarker(simpleMarker,0);pm.simpletags.refresh();moveMap(lat,lng);setTimeout(function(){pm.simpletags.clearMarkers()},10000);}
function cancelPropagation(e){if(typeof e=='undefined')var e=window.event;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();}
function gotoPlace(placeId){new Ajax.Request('/places/goto_place/'+placeId);closeSideBarLeft();}
function gotoEvent(eventId){new Ajax.Request('/events/goto_event/'+eventId);closeSideBarLeft();}
function removeSimpleMarkers(){pm.simpletags.clearMarkers();pm.simpletags.refresh();pm.map.closeInfoWindow();}
function openMarkerInfo(id){var marker=pm.getMarkerFromActiveSearchTab(id);GEvent.trigger(marker,"click");}
function animateMarker(id){var marker=pm.getMarkerFromActiveSearchTab(id);marker.startBouncing();}
function unanimateMarker(id){var marker=pm.getMarkerFromActiveSearchTab(id);marker.stopBouncing();}
function selectSearchBlock(block){if(block=='search'){$$('#search_widget .move').invoke('hide');$$('#search_widget .search').invoke('show');}else{$$('#search_widget .move').invoke('show');$$('#search_widget .search').invoke('hide');}}
function setIconClicked(el){if($$('a.clicked').size()>0)
$$('a.clicked')[0].removeClassName('clicked');$(el).toggleClassName('clicked');}
function slideSideBar(){if(!isSideBarExtended){var newwidth=document.body.clientWidth-200;new Effect.Morph('map',{style:'width:'+newwidth+'px',afterFinish:function(){map.checkResize();GEvent.trigger(map,"moveend");}});new Effect.toggle('sideBarContents','blind',{scaleX:'true',scaleY:'true;',scaleContent:false,afterFinish:function(){isSideBarExtended=true;pm.populateSearchTabs();}});$('sideBarArrow').addClassName('extended');}else{if($$('a.clicked').size()>0)
$$('a.clicked')[0].removeClassName('clicked');new Effect.Morph('map',{style:'width:'+document.body.clientWidth+'px',afterFinish:function(){map.checkResize();GEvent.trigger(map,"moveend");}});new Effect.toggle('sideBarContents','blind',{scaleX:'true',scaleY:'true;',scaleContent:false,afterFinish:function(){isSideBarExtended=false;}});$('sideBarArrow').removeClassName('extended');}}
function slideSideBarLeft(){killPopup();new Effect.toggle('sideBarLeftContents','blind',{scaleX:'true',scaleY:'true;',scaleContent:false});if(isSideBarLeftExtended==0){isSideBarLeftExtended++;var sideBarLeftTabImage=$$('#sideBarLeftTab img')[0];sideBarLeftTabImage.src=sideBarLeftTabImage.src.replace(/(\.[^.]+)$/,'-active$1');}
else{isSideBarLeftExtended=0;var sideBarLeftTabImage=$$('#sideBarLeftTab img')[0];sideBarLeftTabImage.src=sideBarLeftTabImage.src.replace(/-active(\.[^.]+)$/,'$1');}}
function openSideBar(){if(!isSideBarExtended){slideSideBar();}}
function openSideBarLeft(){$('sideBarLeft').show();killPopup();if(isSideBarLeftExtended==0){slideSideBarLeft();}}
function closeSideBarLeft(){killPopup();if(isSideBarLeftExtended!=0){slideSideBarLeft();}}
function newRdv(){if(party){slideSideBarLeft();}else{new Ajax.Request('/rdv',{asynchronous:true,evalScripts:true});}}
function killSideBarLeft(){killPopup();var saveButton=$('rendezvous_save_button');if(saveButton!=undefined&&!saveButton.hasClassName('greyed')){if(!confirm(I18n.t('rendezvous.confirm.close')))
return false;}
if(isSideBarLeftExtended!=0){slideSideBarLeft();}
setTimeout("$('sideBarLeft').hide()",1500);party=undefined;}
function isSideBarLeftOpen(){try{var never_used_variable=party.name;return true;}catch(ex){return false;}}
function moveMap(a,b){map.setCenter(new GLatLng(a,b));}
function moveMapToBounds(swlat,swlng,nelat,nelng){var sw=new GLatLng(swlat,swlng);var ne=new GLatLng(nelat,nelng);var bounds=new GLatLngBounds(sw,ne);map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));}
function resizeMap(){if(currheight!=document.documentElement.clientHeight||currwidth!=document.documentElement.clientWidth){if(!isSideBarExtended){$('map').setStyle({width:document.body.clientWidth+'px'});}
else{$('map').setStyle({width:document.body.clientWidth-200+'px'});}
if(map){map.checkResize();GEvent.trigger(map,"moveend");}}
currheight=document.documentElement.clientHeight;currwidth=document.documentElement.clientWidth;}
function rankingChanged(tabId,rankinglist){var tn='ul_'+tabId;$(tn).immediateDescendants().each(function(elem){elem.hide();elem.removeClassName('odd');elem.removeClassName('even');});var tab=pm.searchTabs.get(tabId);rankinglist.each(function(rankingItem,index){var li=$('li_'+rankingItem.id+'_'+tabId);new Insertion.Bottom(tn,li.remove());li.addClassName((index%2)?'odd':'even');li.select('.ranking_marker_content').each(function(content){content.update(index+1+tab.searchParams['from']);});li.show();});}
function importanceOrder(marker,b){return marker.importance*2+1000000;}
function BocadilloIcon(){this.image='/images/bocadillos/bocadillo_image.png';this.shadow='/images/bocadillos/bocadillo_shadow.png';this.printImage='/images/bocadillos/bocadillo_print_image.gif';this.mozPrintImage='/images/bocadillos/bocadillo_moz_print_image.gif';this.printShadow='/images/bocadillos/bocadillo_print_shadow.gif';this.transparent='/images/bocadillos/bocadillo_transparent.png';this.iconSize=new GSize(73,103);this.shadowSize=new GSize(144,103);this.iconAnchor=new GPoint(18,99);this.infoWindowAnchor=new GPoint(36,36);this.imageMap=[18,97,33,71,2,71,2,2,71,2,71,71,57,71];}
BocadilloIcon.prototype=new GIcon();function RankingIcon(){this.image='/images/markers/marker_ranking.png';this.shadow='/images/markers/marker_ranking_shadow.png';this.iconSize=new GSize(30,30);this.shadowSize=new GSize(46,30);this.iconAnchor=new GPoint(14,14);this.infoWindowAnchor=new GPoint(14,14);this.imageMap=[15,1,25,5,29,15,25,25,29,14,5,25,0,14,5,5];}
RankingIcon.prototype=new GIcon();function PointIcon(){this.image='/images/markers/marker_small.png';this.iconSize=new GSize(10,10);this.iconAnchor=new GPoint(5,5);this.infoWindowAnchor=new GPoint(5,5);}
PointIcon.prototype=new GIcon();function BallIcon(){this.image='/images/ball-02.gif';this.iconSize=new GSize(25,32);this.iconAnchor=new GPoint(12,24);this.infoWindowAnchor=new GPoint(12,24);}
BallIcon.prototype=new GIcon();function RankingMarker(latLng,rank,title){var options={icon:new RankingIcon(),title:title,labelText:rank,labelClass:"ranking_marker_content",labelOffset:new GSize(-14,-8)}
if(!(Prototype.Browser.IE&&getIeVersion()==8)){options['zIndexProcess']=importanceOrder;}
LabeledMarker.call(this,latLng,options);}
RankingMarker.prototype=new LabeledMarker(new GLatLng(0,0),{});function PointMarker(latLng,title){GMarker.call(this,latLng,{title:title,icon:new PointIcon()});}
PointMarker.prototype=new GMarker(new GLatLng(0,0));function BallMarker(latLng){GMarker.call(this,latLng,{icon:new BallIcon()});}
BallMarker.prototype=new GMarker(new GLatLng(0,0));function BocadilloMarker(latLng,marker){var filename=marker.picture_public_filename;var labelText="<img class=\"user_picture user_"+marker.id+"_picture small\" src=\""+filename+"\" />";LabeledMarker.call(this,latLng,{icon:new BocadilloIcon(),labelText:labelText,labelClass:"bocadillo_content",labelOffset:new GSize(-11,-92)});}
BocadilloMarker.prototype=new LabeledMarker(new GLatLng(0,0),{});GMarker.prototype.startBouncing=function(){this.continueBouncing_=true;this.bounce();}
GMarker.prototype.stopBouncing=function(){this.continueBouncing_=false;}
GMarker.prototype.bounce=function(){try{if(this.bouncingEffect_||!this.continueBouncing_)return;var pulseOnce=function(pos){return 0.5-0.5*Math.cos(pos*2*Math.PI);}
var afterBounce=function(){this.bouncingEffect_=null;this.bounce();}
var effects=[];this.getVisibleElements().each(function(el){effects.push(new Effect.Move(el,{x:0,y:-30,mode:'relative',sync:true,transition:pulseOnce}));});this.getShadowElements().each(function(el){effects.push(new Effect.Move(el,{x:21,y:-21,mode:'relative',sync:true,transition:pulseOnce}));});this.bouncingEffect_=new Effect.Parallel(effects,{afterFinish:afterBounce.bind(this)});}catch(e){}}
GMarker.prototype.getVisibleElements=function(){return[this.V[0],this.V[2]].compact();}
GMarker.prototype.getShadowElements=function(){return[this.V[1]].compact();}
LabeledMarker.prototype.getVisibleElements=function(){return GMarker.prototype.getVisibleElements.apply(this).concat(this.div_);}
function PlaceManager(map){var me=this;me.map=map;me.searchTabs=new Hash();me.simpletags=new MarkerManager(map);}
PlaceManager.prototype.mapMoved=function(){var me=this;me.searchTabs.each(function(tab){tab.value.mapMoved(me.map.getBounds());});Cookies.create('initial_lat',map.getCenter().lat());Cookies.create('initial_lng',map.getCenter().lng());Cookies.create('initial_zoom',map.getZoom());messaging.updateMarkers();if(me.searchTabs.size()==0){messaging.searchMessages();}}
PlaceManager.prototype.addSearchTab=function(tab){tab.markerManager=new MarkerManager(map);this.searchTabs.set(tab.id,tab);dynamicFilterManager.showLinksIfNeeded(tab.id);}
PlaceManager.prototype.removeSearchTab=function(tabId){dynamicFilterManager.reset(tabId);dynamicFilterManager.hide(tabId);if(typeof this.searchTabs.get(tabId)!='undefined'){this.searchTabs.get(tabId).markerManager.clearMarkers();this.searchTabs.unset(tabId);}}
PlaceManager.prototype.setActiveSearchTab=function(tabId){var currentTab=this.getActiveSearchTab();if(!currentTab||currentTab.id!=tabId){var titleId='li_'+tabId;var rankingId='div_'+tabId;$$('#taglist li.search_tab_title').each(function(tabTitle){if(tabTitle.id==titleId){tabTitle.removeClassName('tag_not_selected');tabTitle.addClassName('tag_selected');}else{tabTitle.removeClassName('tag_selected');tabTitle.addClassName('tag_not_selected');}});$$('#ranking div.search_tab_content').each(function(tabContent){if(tabContent.id==rankingId){tabContent.removeClassName('tag_not_selected');tabContent.addClassName('tag_selected');}else{tabContent.removeClassName('tag_selected');tabContent.addClassName('tag_not_selected');}});this.searchTabs.each(function(tab){if(tab.value.id==tabId){tab.value.activate();}else{tab.value.desactivate();}});GEvent.trigger(map,"moveend");this.map.closeInfoWindow();}}
PlaceManager.prototype.getActiveSearchTab=function(){return this.searchTabs.values().find(function(tab){return tab.active;});}
PlaceManager.prototype.getMarkerFromActiveSearchTab=function(id){var tab=this.getActiveSearchTab();if(tab){return tab.mapMarkers.find(function(m){return(m.mid==id);});}}
PlaceManager.prototype.updateSearchTab=function(id,jsonMarkers,jsonResults,jsonAllMarkers,searchParams,discountValues,hasMoreResults){var markers=jsonMarkers.evalJSON();var results=jsonResults.evalJSON();var allMarkers=jsonAllMarkers.evalJSON();var tab=this.searchTabs.get(id);if(typeof tab=='undefined'){var tab=new SearchTab(id,markers,results,allMarkers,searchParams,discountValues,hasMoreResults);this.addSearchTab(tab);}else{tab.updateCache(markers,results,allMarkers,searchParams,discountValues,hasMoreResults);}}
PlaceManager.prototype.updateResultsCount=function(count){$('results_count_'+this.getActiveSearchTab().id).innerHTML=count;}
PlaceManager.prototype.emptyCache=function(){var me=this;me.searchTabs.each(function(tab){tab.value.emptyCache();});}
PlaceManager.prototype.populateSearchTabs=function(){this.searchTabs.each(function(tab){tab.value.populate();});}
function searchTabIdFromSearchParameters(params){var tokens=[params.search_type,params.name,params.tag,params.name_or_tag];tokens=tokens.reject(function(token){return(!token||token.blank());});var result=tokens.join('_').toLowerCase();result=result.replace(/\W/g,'');result=result.replace(/_+/g,'_');result=result.replace(/^_/,'');result=result.replace(/_$/,'');return result;}
function isSearchTabAlreadyOpened(tabId){if(pm.searchTabs.get(tabId)==undefined){return false;}else{pm.setActiveSearchTab(tabId);displayNotice(I18n.t('search_tab_already_open'));return true;}}
function changeRankingPage(delta){var tab=pm.getActiveSearchTab();var from=tab.searchParams.from+parseInt(delta)*tab.pageSize;from=Math.max(from,0);tab.searchParams.from=from;tab.requestUpdateCache();pm.map.closeInfoWindow();}
function removeSearchTabFromSideBar(tabId){new Effect.Parallel([new Effect.Fade('li_'+tabId,{sync:true,afterFinish:function(){$('li_'+tabId).remove();var otherTabs=$$('#taglist li.search_tab_title')
if(otherTabs.size()>0){tabIdWithPrefix=otherTabs[0].id;tabIdWithoutPrefix=tabIdWithPrefix.gsub(/^li_/,"");pm.setActiveSearchTab(tabIdWithoutPrefix);}
else{slideSideBar();}}}),new Effect.Fade('div_'+tabId,{sync:true,afterFinish:function(){$('div_'+tabId).remove();pm.removeSearchTab(tabId);}})]);}
function removeSearchTabIfExists(tabId){if($('li_'+tabId)){$('li_'+tabId).remove();}
if($('div_'+tabId)){$('div_'+tabId).remove();}
if(pm.searchTabs.get(tabId)){pm.removeSearchTab(tabId);}}
function SearchTab(id,markers,results,allMarkers,searchParams,discountValues,hasMoreResults){this.id=id;this.active=false;this.pageSize=10;this.canHaveDiscount=false;this.initializingDiscountSlider=false;this.markerManager=null;this.mapMarkers=new Array();this.isDirty=false;this.updateCacheInProgress=false;this.updateCache(markers,results,allMarkers,searchParams,discountValues,hasMoreResults);}
SearchTab.prototype.populate=function(){if(isSideBarExtended&&!this.populated&&this.active){var ul=$('ul_'+this.id);var i=0;var li=null;ul.immediateDescendants().each(function(e){e.remove();});if(this.results.size()>0){do{ul.insert({bottom:this.results[i]});li=$('li_'+this.markers[i].id+"_"+this.id);}while(++i<this.results.size()&&this.isResultVisible(li));if(!this.isResultVisible(li)){li.remove();i--;this.hasMoreResults=true;this.pageSize=i;this.results=this.results.slice(0,i);this.markers=this.markers.slice(0,i);}else if(this.pageSize<i){this.pageSize=i;}}else{if(this.searchParams.from>0){this.searchParams.from=0;this.requestUpdateCache();}
this.hasMoreResults=false;}
this.updatePagination();this.populated=true;GEvent.trigger(map,"moveend");}}
SearchTab.prototype.activate=function(){this.active=true;this.populate();this.updatePagination();dynamicFilterManager.restore(this.id);}
SearchTab.prototype.desactivate=function(){this.active=false;}
SearchTab.prototype.isResultVisible=function(li){var ul_bottom=document.viewport.getHeight()
-$('commercial_bottom').getDimensions().height;if($('ranking_navigation_'+this.id)){ul_bottom-=30;}
var li_bottom=li.viewportOffset().top+li.getDimensions().height;if(li_bottom>ul_bottom){return false;}else{return true;}}
SearchTab.prototype.initDiscountSlider=function(discountValues){this.initializingDiscountSlider=true;if(!discountValues||discountValues.length<=1){if($$('#div_'+this.id+' .discount_slider_div').size()>0){$$('#div_'+this.id+' .discount_slider_div')[0].hide();}
delete this.discountSlider;this.canHaveDiscount=false;this.searchParams.discount=0;}else{if($$('#div_'+this.id+' .discount_slider_div').size()>0){$$('#div_'+this.id+' .discount_slider_div')[0].show();}
this.canHaveDiscount=true;if(!this.discountSlider){this.discountSlider={band:$$('#div_'+this.id+' .discount_slider_band')[0],handles:$$('#div_'+this.id+' .discount_slider_handle')};this.discountSlider.control=new Control.Slider(this.discountSlider.handles,this.discountSlider.band,{values:discountValues,range:$R(0,discountValues.max()),sliderValue:this.searchParams.discount,onChange:this.discountSliderChanged.bind(this)});}else{this.discountSlider.control.allowedValues=discountValues.sortBy(Prototype.K);this.discountSlider.control.minimum=this.discountSlider.control.allowedValues.min();this.discountSlider.control.maximum=this.discountSlider.control.allowedValues.max();this.discountSlider.control.range=$R(this.discountSlider.control.minimum,this.discountSlider.control.maximum);this.discountSlider.control.setValue(this.discountSlider.control.value);}
$$('#div_'+this.id+' .discount_slider_max_value')[0].innerHTML=this.discountSlider.control.maximum;$$('#div_'+this.id+' .discount_slider_value')[0].innerHTML=this.discountSlider.control.value;this.initializingDiscountSlider=false;}}
SearchTab.prototype.discountSliderChanged=function(value){if(this.initializingDiscountSlider){return;}
$$('#div_'+this.id+' .discount_slider_value')[0].innerHTML=value;if(this.searchParams.discount!=value){this.searchParams.from=0;this.requestUpdateCache();}}
SearchTab.prototype.getDiscount=function(){if(this.canHaveDiscount){return this.discountSlider.control.value;}else{return 0;}}
SearchTab.prototype.mapMoved=function(bounds){var me=this;if(!me.populated){return;}
if(me.active){if(me.isCacheOk(bounds)){var markersInMapArea=new Array();for(var i=0;i<me.markers.length;++i){if(bounds.containsLatLng(new GLatLng(me.markers[i].lat,me.markers[i].lng))){markersInMapArea.push(me.markers[i]);}}
var allMarkersInMapArea=new Array();for(var i=0;i<me.allMarkers.length;++i){if(bounds.containsLatLng(new GLatLng(me.allMarkers[i].lat,me.allMarkers[i].lng))){allMarkersInMapArea.push(me.allMarkers[i]);}}
var googleMarkers=new Array();var displayedRankingMarkers=new Array();for(var i=0;i<markersInMapArea.length;++i){var point=new GLatLng(markersInMapArea[i].lat,markersInMapArea[i].lng);var googleMarker;if(me.searchParams.search_type=='friends'){googleMarker=new BocadilloMarker(point,markersInMapArea[i]);}else{googleMarker=new RankingMarker(point,me.searchParams.from+i+1,markersInMapArea[i].name);}
googleMarker.mid=markersInMapArea[i].id;googleMarker.className=markersInMapArea[i].class_name;googleMarker.importance=1/i;GEvent.addListener(googleMarker,"click",function(){var m=this;new Ajax.Request('/'+m.className.toLowerCase()+'s/smallinfo/'+m.mid,{method:'get',evalScripts:true,asynchronous:true,onSuccess:function(transport){m.openInfoWindowHtml(transport.responseText,noCloseOnClick=true);hideGlobalSpinner();},onLoading:showGlobalSpinner()});});displayedRankingMarkers.push(markersInMapArea[i].id);googleMarkers.push(googleMarker);}
for(var i=0;i<allMarkersInMapArea.length;++i){if(!displayedRankingMarkers.include(allMarkersInMapArea[i].id)){var point=new GLatLng(allMarkersInMapArea[i].lat,allMarkersInMapArea[i].lng);var googleMarker=new PointMarker(point,allMarkersInMapArea[i].name);googleMarker.mid=allMarkersInMapArea[i].id;googleMarker.className=allMarkersInMapArea[i].class_name;googleMarker.importance=-i;GEvent.addListener(googleMarker,"click",function(){var m=this;new Ajax.Request('/'+m.className.toLowerCase()+'s/smallinfo/'+m.mid,{method:'get',evalScripts:true,asynchronous:true,onSuccess:function(transport){m.openInfoWindowHtml(transport.responseText,noCloseOnClick=true);gSpinner.hide();},onLoading:gSpinner.show()});});googleMarkers.push(googleMarker);}}
GEvent.trigger(pm,"rankingchanged",me.id,markersInMapArea);me.markerManager.clearMarkers();me.markerManager.addMarkers(googleMarkers.reverse(),0);me.markerManager.refresh();me.mapMarkers=googleMarkers;}else{me.requestUpdateCache();}}else{me.markerManager.clearMarkers();}}
SearchTab.prototype.isCacheOk=function(bounds){var boundsN=bounds.getNorthEast().lat();var boundsE=bounds.getNorthEast().lng();var boundsS=bounds.getSouthWest().lat();var boundsW=bounds.getSouthWest().lng();var boundsArea=bounds.getSouthWest().distanceFrom(new GLatLng(boundsN,boundsW))*bounds.getSouthWest().distanceFrom(new GLatLng(boundsS,boundsE));var cacheN=this.searchParams.bounds.getNorthEast().lat();var cacheE=this.searchParams.bounds.getNorthEast().lng();var cacheS=this.searchParams.bounds.getSouthWest().lat();var cacheW=this.searchParams.bounds.getSouthWest().lng();var cacheArea=this.searchParams.bounds.getSouthWest().distanceFrom(new GLatLng(cacheN,cacheW))*this.searchParams.bounds.getSouthWest().distanceFrom(new GLatLng(cacheS,cacheE));if(cacheArea>boundsArea&&Math.abs(cacheN-boundsN)<0.0000001&&Math.abs(cacheW-boundsW)<0.0000001){return true;}
var overN=Math.min(boundsN,cacheN);var overE=Math.min(boundsE,cacheE);var overS=Math.min(overN,Math.max(boundsS,cacheS));var overW=Math.min(overE,Math.max(boundsW,cacheW));var overSW=new GLatLng(overS,overW);var overArea=overSW.distanceFrom(new GLatLng(overN,overW))*overSW.distanceFrom(new GLatLng(overS,overE));return(overArea/boundsArea>0.95&&overArea/cacheArea>0.95);}
SearchTab.prototype.emptyCache=function(){var me=this;me.markers=null;me.searchParams.swlat=0;me.searchParams.swlng=0;me.searchParams.nelat=0;me.searchParams.nelng=0;me.searchParams.bounds=new GLatLngBounds(new GLatLng(0,0),new GLatLng(0,0));}
SearchTab.prototype.requestUpdateCache=function(){if(!this.updateCacheInProgress){this.updateCacheInProgress=true;this.isDirty=false;this.searchParams.swlat=map.getBounds().getSouthWest().lat();this.searchParams.swlng=map.getBounds().getSouthWest().lng();this.searchParams.nelat=map.getBounds().getNorthEast().lat();this.searchParams.nelng=map.getBounds().getNorthEast().lng();if(this.getDiscount()>0){this.searchParams.discount=this.getDiscount();}else{delete this.searchParams.discount;}
if(this.searchParams.from==0){delete this.searchParams.from;}
this.buildAdvancedSearchParams();gSpinner.show();var me=this;new Ajax.Request('/search/update_cache/',{method:'get',parameters:this.searchParams,onComplete:function(){me.updateCacheInProgress=false;if(me.isDirty){me.requestUpdateCache()}}});}else{this.isDirty=true;}}
SearchTab.prototype.buildAdvancedSearchParams=function(){var dynamicFilters=dynamicFilterManager.getSearchParameters(this.id);if(dynamicFilters['filters'].include('showcase')){this.searchParams.place_privileged=true;}
dynamicFilters['filters']=dynamicFilters['filters'].without('showcase');if(dynamicFilters['filters'].size()>0){this.searchParams.advanced_filters=dynamicFilters['filters'].join(' ');}
if(dynamicFilters['tags'].size()>0){this.searchParams.tags=dynamicFilters['tags'].join(',');}
if(dynamicFilters['ranking']!='friends'){this.searchParams.ranking=dynamicFilters['ranking'];}
if(dynamicFilters['ranking_only']!=false){this.searchParams.ranking_only=1;}
if(dynamicFilters['price_range']!=''){this.searchParams.price_range=dynamicFilters['price_range'];}}
SearchTab.prototype.updateCache=function(markers,results,allMarkers,searchParams,discountValues,hasMoreResults){this.populated=false;this.markers=markers;this.results=results;this.allMarkers=allMarkers;this.searchParams={from:searchParams.from,name_or_tag:searchParams.name_or_tag,search_type:searchParams.search_type};this.searchParams.bounds=new GLatLngBounds(new GLatLng(searchParams.swlat,searchParams.swlng),new GLatLng(searchParams.nelat,searchParams.nelng));this.hasMoreResults=hasMoreResults;this.initDiscountSlider(discountValues);this.populate();}
SearchTab.prototype.updatePagination=function(){if(this.results.size()==0){$('ranking_navigation_'+this.id).hide();$('ranking_found_nothing_'+this.id).show();}else{$('ranking_navigation_'+this.id).show();$('ranking_found_nothing_'+this.id).hide();if(this.hasMoreResults){$('next_enabled_'+this.id).show();$('next_disabled_'+this.id).hide();}else{$('next_enabled_'+this.id).hide();$('next_disabled_'+this.id).show();}
if(this.searchParams.from>0){$('prev_enabled_'+this.id).show();$('prev_disabled_'+this.id).hide();}else{$('prev_enabled_'+this.id).hide();$('prev_disabled_'+this.id).show();}}}
function sortMarkersByPoints(a,b){return b.points-a.points;}
function updateMarks(points,id){points=Math.round(parseFloat(points));if(!isNaN(points)){$$('.'+id+'_mark').each(function(el){el.update(points);});pm.mapMoved();}}
function selectRedBoxTab(tabId,paneId){if(!tabId){var firstTab=$$('#RB_window .tab')[0];var firstPane=$$('#RB_window .pane')[0];if(firstTab&&firstPane){tabId=firstTab.id;paneId=firstPane.id;}else{return;}}
if(!paneId){var name=tabId;tabId=name+'_tab'
paneId=name+'_pane'}
$$('#RB_window .tab').each(function(element){selectElementIfIdMatches(element,tabId);});$$('#RB_window .pane').each(function(element){selectElementIfIdMatches(element,paneId);});}
function selectRedBoxSubtab(tabId,paneId){if(!tabId){var firstTab=$$('#RB_window .subtab')[0];var firstPane=$$('#RB_window .subpane')[0];if(firstTab&&firstPane){tabId=firstTab.id;paneId=firstPane.id;}else{return;}}
if(!paneId){var name=tabId;tabId=name+'_subtab'
paneId=name+'_subpane'}
$$('#RB_window .subtab').each(function(element){selectElementIfIdMatches(element,tabId);});$$('#RB_window .subpane').each(function(element){selectElementIfIdMatches(element,paneId);});}
function selectElementIfIdMatches(element,id){if(element.id==id){element.addClassName('selected');element.removeClassName('unselected');}else{element.addClassName('unselected');element.removeClassName('selected');}}
function chooseBookingOffer(pPlaceId,pPrice){document.payment_form.price.value=pPrice;document.payment_form.placeId.value=pPlaceId;$('payment_price').innerHTML=pPrice;$('offer_'+pPlaceId).addClassName('offer_selected');$('price_and_payment_options_div').show();}
function showCreditCardForm(){$('paypal_form_div').hide();$('account_form_div').hide();$('credit_card_form_div').show();}
function showPaypalForm(){$('credit_card_form_div').hide();$('account_form_div').hide();$('paypal_form_div').show();}
function showAccountForm(){$('credit_card_form_div').hide();$('paypal_form_div').hide();$('account_form_div').show();}
function addBookingWithAccount(){document.payment_form.payment_method.value="account";new Ajax.Updater('account_payment_result','/bookings/account_payment_complete',{asynchronous:true,evalScripts:true,parameters:Form.serialize($('payment_form'))});}
function BookingCalendar(bookings){this.bookings=new Array()
for(var i=0;i<bookings.length;++i){this.bookings.push({start:new Date(bookings[i].start_date).stripTime(),end:new Date(bookings[i].end_date).stripTime()});}}
var bookingCalendar;BookingCalendar.prototype.dateChanged=function(){if($('booking_start_date').calendar_date_select){$('booking_start_date').calendar_date_select.refresh();}
if($('booking_end_date').calendar_date_select){$('booking_end_date').calendar_date_select.refresh();if(this.getEndDate()!=undefined)
new Ajax.Request('/bookings/precalc_price',{parameters:Form.serialize($('booking_form'),true),onLoading:function(){$('booking_price').next('span.spinner').show()},onComplete:function(){$('booking_price').next('span.spinner').hide()}})}
$('booking_start_date_display').update($('booking_start_date').value);$('booking_end_date_display').update($('booking_end_date').value);}
BookingCalendar.prototype.getStartDate=function(){if($('booking_start_date').value&&$('booking_start_date').value!=""){var finnishDate=$('booking_start_date').value
var dateComponents=finnishDate.split(/\./);var startDate=new Date();startDate.setFullYear(parseInt(dateComponents[2]));startDate.setMonth(parseInt(dateComponents[1])-1);startDate.setDate(parseInt(dateComponents[0]));return startDate.stripTime();}else{return null;}}
BookingCalendar.prototype.getEndDate=function(){if($('booking_end_date').value&&$('booking_end_date').value!=""){var finnishDate=$('booking_end_date').value
var dateComponents=finnishDate.split(/\./);var endDate=new Date();endDate.setFullYear(parseInt(dateComponents[2]));endDate.setMonth(parseInt(dateComponents[1])-1);endDate.setDate(parseInt(dateComponents[0]));return endDate.stripTime();}else{return null;}}
BookingCalendar.prototype.getEarliestDate=function(){return(new Date()).stripTime();}
BookingCalendar.prototype.getLatestDate=function(){var start=this.getEarliestDate();var end=start;end.setFullYear(end.getFullYear()+2)
return end.stripTime();}
BookingCalendar.prototype.checkStartDate=function(date){if(!this.dateInRange(date,this.getEarliestDate(),this.getLatestDate())){return false;}
if(this.getEndDate()&&date>this.getEndDate()){return false;}
if(this.getStartDate()&&date<this.getStartDate()){return false;}
for(var i=0;i<this.bookings.length;++i){var booking=this.bookings[i];if(this.dateInRange(date,booking.start,booking.end)){return false;}
if(this.getEndDate()&&this.getEndDate()>=booking.start&&date<=booking.end){return false;}}
return true;}
BookingCalendar.prototype.checkEndDate=function(date){if(!this.dateInRange(date,this.getEarliestDate(),this.getLatestDate())){return false;}
if(this.getStartDate()&&date<this.getStartDate()){return false;}
if(this.getEndDate()&&date>this.getEndDate()){return false;}
for(var i=0;i<this.bookings.length;++i){var booking=this.bookings[i];if(this.dateInRange(date,booking.start,booking.end)){return false;}
if(this.getStartDate()&&this.getStartDate()<=booking.end&&date>=booking.start){return false;}}
return true;}
BookingCalendar.prototype.dateInRange=function(date,start,end){return(date>=start&&date<=end);}
BookingCalendar.prototype.startDateSelected=function(){$('booking_start_date_selection').hide();$('booking_end_date_selection').show();$('booking_start_date').writeAttribute("readonly","readonly");if($('booking_end_date').value==""&&$('booking_end_date').calendar_date_select){$('booking_end_date').calendar_date_select.navMonth($('booking_start_date').calendar_date_select.selected_date.getMonth());}
this.dateChanged();}
BookingCalendar.prototype.endDateSelected=function(){$('booking_end_date').writeAttribute("readonly","readonly");this.dateChanged();}
BookingCalendar.prototype.clearSelection=function(){$('booking_price').update('-')
$('booking_start_date').value="";$('booking_start_date').writeAttribute("readonly",null);$('booking_end_date').value="";$('booking_end_date').writeAttribute("readonly",null);$('booking_end_date_selection').hide();$('booking_start_date_selection').show();this.dateChanged();}
function goFifa2010(){var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();document.forms.what_form.swlat.value=sw.lat();document.forms.what_form.swlng.value=sw.lng();document.forms.what_form.nelat.value=ne.lat();document.forms.what_form.nelng.value=ne.lng();var parameters=Form.serialize($('what_form'),true);parameters['name_or_tag']='fifa2010';var tabId=searchTabIdFromSearchParameters(parameters);if(!isSearchTabAlreadyOpened(tabId)){gSpinner.show();new Ajax.Request('/search/',{parameters:parameters,onLoading:onAjaxFormLoading.curry('what_form'),onComplete:onAjaxFormComplete.curry('what_form')});}}
function goWhatButton(){var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();document.forms.what_form.swlat.value=sw.lat();document.forms.what_form.swlng.value=sw.lng();document.forms.what_form.nelat.value=ne.lat();document.forms.what_form.nelng.value=ne.lng();var parameters=Form.serialize($('what_form'),true);var tabId=searchTabIdFromSearchParameters(parameters);if(!isSearchTabAlreadyOpened(tabId)){gSpinner.show();new Ajax.Request('/search/',{parameters:parameters,onLoading:onAjaxFormLoading.curry('what_form'),onComplete:onAjaxFormComplete.curry('what_form')});}}
function searchForTag(tag_name){var params={};var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();params.swlat=sw.lat();params.swlng=sw.lng();params.nelat=ne.lat();params.nelng=ne.lng();params.search_type=((tag_name=='event')?'Event':'Place');params.name_or_tag=((tag_name=='event')?'':tag_name);if(!isSearchTabAlreadyOpened(searchTabIdFromSearchParameters(params))){showGlobalSpinner();new Ajax.Request('/search/',{method:'get',parameters:params});}}
function savePosition(){lat=map.getCenter().lat();lng=map.getCenter().lng();zoomlevel=map.getZoom();new Ajax.Request('welcome/save_position?lat='+lat+'&lng='+lng+'&zoomlevel='+zoomlevel);}
function sidebar_toggleHelp(element){var visible=element.visible();$$('.sideBar_help_item').each(function(e){if(e.visible()){Effect.BlindUp(e);}});if(!visible){new Effect.BlindDown(element,{queue:'end'});}}
function toggle_search_acc(acc_option_id){if(acc_status[acc_option_id]){acc_status[acc_option_id]=false;}
else{acc_status[acc_option_id]=true;}
Effect.toggle('acc_content_'+acc_option_id,'blind');}
function close_other_acc_options(acc_option_id){acc_status.each(function(accordion_option,idx){if(acc_option_id!=idx){$('acc_content_'+idx).hide();acc_status[idx]=false;}});}
function displayIfRendezvousElements(){if(party&&(party.editable_place||party.isOwner)){$$('.if_rendezvous').invoke('show');}else{$$('.if_rendezvous').invoke('hide');}}
function changeAdvancedSearchType(){if($('search_type_place').checked){$('place_search_form').show();$('event_search_form').hide();}else{$('place_search_form').hide();$('event_search_form').show();}}
function changeAdvancedSearchLocation(){if($('location_type_current').checked){$('location_radius').disable();$('location_origin').disable();}else{$('location_radius').enable();$('location_origin').enable();$('location_origin').activate();}}
function updateAdvancedSearchBounds(){var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();document.forms.advanced_search_form.swlat.value=sw.lat();document.forms.advanced_search_form.swlng.value=sw.lng();document.forms.advanced_search_form.nelat.value=ne.lat();document.forms.advanced_search_form.nelng.value=ne.lng();}
function initAdvancedSearchDiscountSlider(){var band=$$('#advanced_search_form .discount_slider_band')[0];var handles=$$('#advanced_search_form .discount_slider_handle');var control=new Control.Slider(handles,band,{range:$R(0,100),onChange:advancedSearchDiscountSliderChanged,onSlide:advancedSearchDiscountSliderChanged});advancedSearchDiscountSliderChanged(control.value);}
function advancedSearchDiscountSliderChanged(value){value=Math.round(value);$$('#advanced_search_form .discount_slider_value').each(function(e){e.update(value);});document.forms.advanced_search_form.discount.value=value;}
function initializeMapDirections(){gdir=new GDirections(map,document.getElementById("map_directions"));GEvent.addListener(gdir,"error",handleMapDirectionsErrors);}
function setDirections(toAddress,locale){fromAddress=$F('from_field');gdir.loadFromWaypoints([fromAddress,toAddress],{"locale":locale});$('map_directions_closeable').show();}
function closeDirectionsDiv(){gdir.clear();$('map_directions_closeable').hide();}
function handleMapDirectionsErrors(){if(gdir.getStatus().code==G_GEO_UNKNOWN_ADDRESS)
alert(I18n.t('map_directions.unknown_address'));else if(gdir.getStatus().code==G_GEO_SERVER_ERROR)
alert(I18n.t('map_directions.server_error'));else if(gdir.getStatus().code==G_GEO_MISSING_QUERY)
alert(I18n.t('map_directions.missing_query'));else if(gdir.getStatus().code==G_GEO_BAD_KEY)
alert(I18n.t('map_directions.bad_key'));else if(gdir.getStatus().code==G_GEO_BAD_REQUEST)
alert(I18n.t('map_directions.bad_request'));else alert(I18n.t('map_directions.unknown_error'));}
function onImageExpand(a){if(numGalleryPages==undefined||numGalleryPages<=5)return;var imageId=a.id.replace(/hs_anchor_(\d+)/,"$1");var imageElements=$('imagebox_thumbnails').childElements().grep(new Selector('a'));var imageNumber=0;for(var i=0;i<imageElements.length;++i){var el=imageElements[i];if(el.id=='hs_anchor_'+imageId){el.addClassName('active_thumbnail');imageNumber=i;}else{el.removeClassName('active_thumbnail');}}
navigateGallery(imageNumber-currentGalleryPage);}
function navigateGallery(increment){if(numGalleryPages==undefined||numGalleryPages<=5)return;if(currentGalleryPage+increment<0){increment=-currentGalleryPage;}else if(currentGalleryPage+increment>=numGalleryPages-5){increment=numGalleryPages-currentGalleryPage-5;}
currentGalleryPage+=increment;if(increment){new Effect.Move("imagebox_thumbnails",{duration:0.2*Math.abs(increment),mode:'relative',x:increment*-64,y:0});}
if(currentGalleryPage>0){$('gallery_button_up').show();$('gallery_button_up_disabled').hide();}else{$('gallery_button_up').hide();$('gallery_button_up_disabled').show();}
if(currentGalleryPage<numGalleryPages-5){$('gallery_button_down').show();$('gallery_button_down_disabled').hide();}else{$('gallery_button_down').hide();$('gallery_button_down_disabled').show();}}
var noticeTimeout=null;function displayNotice(notice){var READING_SPEED_IN_MSPC=66;var MIN_DISPLAY_TIME=3000;$('notice').show().setOpacity(1.0).update(notice);var displayTime=Math.max(MIN_DISPLAY_TIME,notice.length*READING_SPEED_IN_MSPC);if(noticeTimeout){clearTimeout(noticeTimeout);noticeTimeout=null;}
noticeTimeout=setTimeout("new Effect.Fade('notice', { duration: 3.0 });",displayTime);}
function applyLoggedIn(logged,lat,lng,user_id,user_name){if(logged){$('header').addClassName('logged_in');$('header').removeClassName('not_logged_in');if(lat&&lng&&!isSideBarExtended){moveMap(lat,lng);}}
$$('.dynamic_filter_ranking').each(function(e){e.show();});if(!isSideBarLeftExtended){if(logged&&redboxOpenedWindowUrl==null){displayMyspace();}else if(redboxOpenedWindowUrl!=null){new Ajax.Request(redboxOpenedWindowUrl,{method:'get',asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()}});}
refresh=true;applyRefresh();}else{refresh=true;applyRefresh(user_name,user_id);}
$('menu_login_form').setStyle({display:'none'});isUserLogged=logged;}
function loginShowClassic(){$('openid_url').value="";$('login_open_id').hide();$('login_forgot_pwd').hide();$('login_classic').show();$('login_classic_link').hide();}
function loginShowOpenid(){$('login_classic').hide();$('login_forgot_pwd').hide();$('login_open_id').show();$('login_classic_link').show();}
function loginShowForgotPwd(){$('login_open_id').hide();$('login_classic').hide();$('login_forgot_pwd').show();$('login_classic_link').show();}
function applyRefresh(user_name,user_id){if(refresh){delete refresh;pm.emptyCache();pm.mapMoved();if(party){if(party.newRecord){new Ajax.Request('/rdv',{onComplete:function(){setTimeout("party.addPerson('"+user_name+"', 'RegisteredUser', '"+user_id+"')",500)}});}else{var key=$F('rendezvous_key');new Ajax.Request('/rendezvous/display_rdv/'+key);}}}}
function addPlaceToRdv(object_id,object_name,object_type,background,book_link){introDestroy();RedBox.close();if(party&&(party.editable_place||party.isOwner)){party.addNewPlace(object_id,object_name,object_type,background,book_link)}else{new Ajax.Request('/rdv',{method:'get',onComplete:function(){setTimeout("party.addNewPlace("+object_id+",'"+object_name+"','"+object_type+"','"+background+"','"+book_link+"');",500);}});}}
function addPersonToRdv(name,type,user_id){introDestroy();RedBox.close();if(party&&(party.editable_place||party.isOwner)){party.addPerson(name,type,user_id);}else{new Ajax.Request('/rdv',{method:'get',onComplete:function(){setTimeout("party.addPerson('"+name+"', '"+type+"', "+user_id+")",500);}});}}
function startEditingMe(input,label){input=$(input);label=$(label);input.show();input.focus()
input.select();label.hide();}
function stopEditingMe(input,label){input=$(input);label=$(label);input.hide();var value=input.getValue();if(!value.blank()){if(label.hasClassName('withSimpleFormat')){var paragraphs=value.strip().split(/\n{2,}/);paragraphs=paragraphs.map(function(p){return'<p>'+p.replace(new RegExp('\n','g'),'<br />')+'</p>';})
value=paragraphs.join('\n\n');}
label.innerHTML=value}
label.show();}
function showReport(){$('showcase_header').className='showcase_tall_header';$('place_report_link').hide();$('report_place_container').addClassName('open');$('report_place').appear();}
function hideReport(message){$('report_place_container').removeClassName('open');$('report_done').innerHTML=message;$('showcase_header').className='showcase_header';}
function updateAttribute(id,attribute,value){$(id).setAttribute(attribute,value);}
function editTagList(place_id,tag_list,controller){tag_list_array=tag_list.split(',');var html_tag_editor='<div id="info_tag_list">'
+'<form onsubmit="new Ajax.Updater(\'info_tag_list\', \'/'+controller+'/update_tag_list/'+place_id+'\', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" '
+'method="post" action="/session">';tag_list_array.each(function(tag){html_tag_editor+='<input type="text" name="tag[]" value="'+tag.strip()+'" class="tag_list_field" />';});html_tag_editor+='<p id="placeholder_for_extra_fields" style="display:none"></p>';if(tag_list_array.size()<5){html_tag_editor+='<a onclick="addTagListField();return false;" id="add_tag_button" href="#">'
+'<span class="icon icon_add"></span>'
+'</a>';}
html_tag_editor+='<input type="submit" value="save"/>'
+'</form>'
+'</div>';$('info_tag_list').replace(html_tag_editor);}
function addTagListField(){if($('add_tag_button').siblings().size()>5){$('add_tag_button').hide();}
Insertion.Before('placeholder_for_extra_fields','<input type="text" name="tag[]" class="tag_list_field">');}
function killPopup(){Control.Window.windows.invoke('close');Control.Window.windows.invoke('destroy');}
function locateFriends(){var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();if(!isSearchTabAlreadyOpened(searchTabIdFromSearchParameters({search_type:'friends'}))){new Ajax.Request('/search/friends/',{parameters:{swlat:sw.lat(),swlng:sw.lng(),nelat:ne.lat(),nelng:ne.lng()}});}}
function displayIntro(){page_navigate('intro');}
function requestIntro(){introDestroy();RedBox.close();new Ajax.Request('/welcome/intro',{method:'get',asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()}});}
function displaySignup(){page_navigate('signup');}
function requestSignup(){introDestroy();RedBox.close();new Ajax.Request('/signup',{method:'get',asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()}});}
function displayMap(){if(YAHOO.util.History.getCurrentState("page")=='map'){introDestroy();RedBox.close();}
page_navigate('map');if(inIntro){if(I18n.locale=='es'){searchForTag('must see')}else{searchForTag('bar')}}
inIntro=false;}
function toggleMapViewMode(){if(map.getCurrentMapType()==G_HYBRID_MAP){map.setMapType(G_NORMAL_MAP);}else{map.setMapType(G_HYBRID_MAP);}}
function idFromDomId(domId){exp=/^(\w+)_(\d+)$/;tokens=exp.exec(domId);return parseInt(tokens[2]);}
function classFromDomId(domId,prefix){if(Object.isUndefined(prefix)){prefix="";}else{prefix=prefix+'_';}
exp=new RegExp("^"+prefix+"(\\w+)_(\\d+)$");tokens=exp.exec(domId);return tokens[1].dasherize().capitalize().camelize();}
function domIdFromIdAndClass(id,className,prefix){if(Object.isUndefined(prefix)){prefix='';}else{prefix=prefix+'_';}
return(prefix+className+'_'+id).underscore();}
var openRegistration=function(type,force_email){if(typeof force_email=='undefined'){force_email=false;}
var info=$('info_div');var mil=$('mil_registration_form');var fb=$('fb_registration_form');var openId=$('open_id_registration_form');info.hide();mil.hide();fb.hide();openId.hide();switch(type){case'info':info.show();$('user_redbox_h1').innerHTML=I18n.t('users.new.title');break;case'mil':mil.show();$('user_redbox_h1').innerHTML=I18n.t('register.mil_title');break;case'fb':fb.show();displayEmailField=true;FB.Connect.showPermissionDialog('email,user_birthday',function(perms){if(perms&&!force_email){displayEmailField=false
$('new_mil_with_fb').hide();}});$('user_redbox_h1').innerHTML=I18n.t('register.fb_title');break;case'open_id':openId.show();$('user_redbox_h1').innerHTML=I18n.t('register.open_id_title');break;default:info.show();buttons_info.show();bottom_info();}}
function fb_connect_invite_friends(options){if(typeof options!='object'){options={}}
if(options.title==undefined){options.title="Invite your friends"}
if(options.type==undefined){options.type=window.location.hostname}
if(options.all_friends_invited==undefined){options.all_friends_invited="<div style='padding: 10px; font-size: 1.2em;'>You've already invited all of your friends and they've accepted.</div>"}
if(options.invitation_copy==undefined){options.invitation_copy=""}
if(options.invitation_choice_url==undefined){options.invitation_choice_url=window.location.protocol+'//'+window.location.host+'/'}
if(options.invitation_choice_label==undefined){options.invitation_choice_label='Accept'}
if(options.request_action_url==undefined){options.request_action_url=window.location.href}
if(options.request_action_text==undefined){options.request_action_text=options.title}
if(options.friend_selector_rows==undefined){options.friend_selector_rows=3}
if(options.friend_selector_email_invite==undefined){options.friend_selector_email_invite='true'}
if(options.friend_selector_bypass==undefined){options.friend_selector_bypass='cancel'}
if(isNaN(options.width)){options.width=760}
if(isNaN(options.height)){options.height=544}
var api=FB.Facebook.apiClient
var sequencer=new FB.BatchSequencer()
var friends=api.friends_get(null,sequencer)
var friends_app_users=api.friends_getAppUsers(sequencer)
sequencer.execute(function(){var friend_ids=''
try{friend_ids=friends.result.sort().join(',')}catch(e){;}
var exclude_ids=''
try{exclude_ids=friends_app_users.result.sort().join(',')}catch(e){;}
var dialog=new FB.UI.FBMLPopupDialog(options.title,'')
if(friend_ids.length>0&&exclude_ids.length>0&&friend_ids==exclude_ids){var fbml=''
fbml+='<fb:fbml>'
fbml+=options.all_friends_invited
fbml+='</fb:fbml>'
dialog.setFBMLContent(fbml)
dialog.setContentWidth(300)
dialog.setContentHeight(70)}else{var content=''
content+=options.invitation_copy
content+="<fb:req-choice url='"+options.invitation_choice_url+"' label='"+options.invitation_choice_label+"' />"
var fbml=''
fbml+='<fb:fbml>'
fbml+='<fb:request-form type="'+options.type+'" content="'+content+'" invite="true" action="'+options.request_action_url+'" method="post">'
fbml+='<fb:multi-friend-selector'
fbml+=' actiontext="'+options.request_action_text+'" '
fbml+=' showborder="true" '
fbml+=' rows="'+options.friend_selector_rows+'" '
fbml+=' exclude_ids="'+exclude_ids+'" '
fbml+=' bypass="'+options.friend_selector_bypass+'" '
fbml+=' email_invite="'+options.friend_selector_email_invite+'" '
fbml+='/>'
fbml+='</fb:request-form>'
fbml+='</fb:fbml>'
dialog.setFBMLContent(fbml)
dialog.setContentWidth(options.width)
dialog.setContentHeight(options.height)}
dialog.show()})}
function emailBookingDecisionChanged(){['accept','decline'].each(function(verb,index){if($F('decision_'+verb)){$$('.if_'+verb+'_is_selected').invoke('show');$('email_booking_merchant_message').linkedSelectsChanged[index]();}else{$$('.if_'+verb+'_is_selected').invoke('hide');}});}
function linkSelectWithTextArea(selectId,textAreaId){var select=$(selectId);var textArea=$(textAreaId);var observer=function(){if(select.getValue()!=="null"){textArea.value=select.value;textArea.enable();}else{textArea.value="";textArea.disable();}};if(!textArea.linkedSelects){textArea.linkedSelects=[];textArea.linkedSelectsChanged=[];}
textArea.linkedSelects.push(select);textArea.linkedSelectsChanged.push(observer);select.observe('change',observer);}
function update_user_pictures(id,filenames){var pictures;for(var size in filenames){pictures=$$('.user_'+id+'_picture.'+size);pictures.each(function(picture){picture.src=filenames[size];});}}
var newPlace=null;var NewPlace=Class.create({initialize:function(){this.name;this.street;this.city;this.country;this.phone;this.lat;this.lng;}});function clickOnMap(overlay,point){if(point!=null){if(crossHairActive){crossHairActive=false;map.getDragObject().setDraggableCursor('-moz-grab');displayDraggableMarker(point.lat(),point.lng());$('new_place_step_2_pointer').hide();$('new_place_step_3').show();}}}
function goAddPlaceButton(field){new Ajax.Request('/welcome/goto_location',{parameters:{location:$F(field)},onSuccess:function(){setTimeout("GEvent.trigger(simpleMarker,'click');",100);}});$('create_place_with_address_field').clear();}
function createPlace(){if(crossHairActive){noticeText=I18n.t('positioning_pointer_inactive');crossHairActive=false;map.getDragObject().setDraggableCursor('-moz-grab');}
else{noticeText=I18n.t('positioning_pointer_active');crossHairActive=true;map.getDragObject().setDraggableCursor('crosshair');}
displayNotice(noticeText);}
function displayAddPlaceTab(){newPlace=new NewPlace();newPlace.name=$F('create_place_with_name_field');new Ajax.Request('/places/new_in_sidebar',{method:'get',asynchronous:true,evalScripts:true,parameters:{name:$F('create_place_with_name_field')},onLoading:function(){gSpinner.show()}});}
var draggableMarker=null;function displayDraggableMarker(lat,lng,callback){if(typeof lat!='undefined'&&typeof lng!='undefined'){point=new GLatLng(lat,lng);}else{point=map.getCenter();}
draggableMarker=new GMarker(point,{draggable:true});map.addOverlay(draggableMarker);}
function addPlaceTriggerTransition(from,to){var trans=from+'-'+to;switch(trans){case'1-2a':$('new_place_step_1').hide();$('new_place_step_2_address').show();break;case'2a-1':$('new_place_step_2_address').hide();$('new_place_step_1').show();break;case'1-2b':$('new_place_step_1').hide();$('new_place_step_2_pointer').show();createPlace();break;case'2b-1':$('new_place_step_2_pointer').hide();$('new_place_step_1').show();createPlace();if(draggableMarker!=null){map.removeOverlay(draggableMarker);draggableMarker=null;}
break;case'2a-3':newPlace.street=$F('new_place_street');newPlace.city=$F('new_place_city');newPlace.country=$F('new_place_country');newPlace.phone=$F('new_place_phone');var address=$F('new_place_street')+', '+
$F('new_place_city')+', '+
$F('new_place_country');var geocoder=new GClientGeocoder();geocoder.getLatLng(address,function(point){if(!point){$('new_place_address_not_found').show();setTimeout(function(){$('new_place_address_not_found').fade();},3500);}else{newPlace.lat=point.lat();newPlace.lng=point.lng();$('new_place_step_2_address').hide();$('new_place_step_3').show();moveMap(point.lat(),point.lng());displayDraggableMarker(point.lat(),point.lng());}});break;case'3-1':if(draggableMarker!=null){$('new_place_step_3').hide();$('new_place_step_1').show();map.removeOverlay(draggableMarker);draggableMarker=null;}
break;case'3-4':if(draggableMarker!=null){var lat=draggableMarker.getLatLng().lat();var lng=draggableMarker.getLatLng().lng();map.removeOverlay(draggableMarker);draggableMarker=null;removeSearchTabFromSideBar("new_place");new Ajax.Request('/places/new',{method:'get',asynchronous:true,evalScripts:true,parameters:{name:newPlace.name,lat:lat,lng:lng,st:newPlace.street,ci:newPlace.city,co:newPlace.country,ph:newPlace.phone},onLoading:function(){gSpinner.show()}});}
break;}}
(function(){function g(o){console.log("$f.fireEvent",[].slice.call(o))}function k(q){if(!q||typeof q!="object"){return q}var o=new q.constructor();for(var p in q){if(q.hasOwnProperty(p)){o[p]=k(q[p])}}return o}function m(t,q){if(!t){return}var o,p=0,r=t.length;if(r===undefined){for(o in t){if(q.call(t[o],o,t[o])===false){break}}}else{for(var s=t[0];p<r&&q.call(s,p,s)!==false;s=t[++p]){}}return t}function c(o){return document.getElementById(o)}function i(q,p,o){if(typeof p!="object"){return q}if(q&&p){m(p,function(r,s){if(!o||typeof s!="function"){q[r]=s}})}return q}function n(s){var q=s.indexOf(".");if(q!=-1){var p=s.substring(0,q)||"*";var o=s.substring(q+1,s.length);var r=[];m(document.getElementsByTagName(p),function(){if(this.className&&this.className.indexOf(o)!=-1){r.push(this)}});return r}}function f(o){o=o||window.event;if(o.preventDefault){o.stopPropagation();o.preventDefault()}else{o.returnValue=false;o.cancelBubble=true}return false}function j(q,o,p){q[o]=q[o]||[];q[o].push(p)}function e(){return"_"+(""+Math.random()).substring(2,10)}var h=function(t,r,s){var q=this;var p={};var u={};q.index=r;if(typeof t=="string"){t={url:t}}i(this,t,true);m(("Begin*,Start,Pause*,Resume*,Seek*,Stop*,Finish*,LastSecond,Update,BufferFull,BufferEmpty,BufferStop").split(","),function(){var v="on"+this;if(v.indexOf("*")!=-1){v=v.substring(0,v.length-1);var w="onBefore"+v.substring(2);q[w]=function(x){j(u,w,x);return q}}q[v]=function(x){j(u,v,x);return q};if(r==-1){if(q[w]){s[w]=q[w]}if(q[v]){s[v]=q[v]}}});i(this,{onCuepoint:function(x,w){if(arguments.length==1){p.embedded=[null,x];return q}if(typeof x=="number"){x=[x]}var v=e();p[v]=[x,w];if(s.isLoaded()){s._api().fp_addCuepoints(x,r,v)}return q},update:function(w){i(q,w);if(s.isLoaded()){s._api().fp_updateClip(w,r)}var v=s.getConfig();var x=(r==-1)?v.clip:v.playlist[r];i(x,w,true)},_fireEvent:function(v,y,w,A){if(v=="onLoad"){m(p,function(B,C){if(C[0]){s._api().fp_addCuepoints(C[0],r,B)}});return false}A=A||q;if(v=="onCuepoint"){var z=p[y];if(z){return z[1].call(s,A,w)}}if(y&&"onBeforeBegin,onMetaData,onStart,onUpdate,onResume".indexOf(v)!=-1){i(A,y);if(y.metaData){if(!A.duration){A.duration=y.metaData.duration}else{A.fullDuration=y.metaData.duration}}}var x=true;m(u[v],function(){x=this.call(s,A,y,w)});return x}});if(t.onCuepoint){var o=t.onCuepoint;q.onCuepoint.apply(q,typeof o=="function"?[o]:o);delete t.onCuepoint}m(t,function(v,w){if(typeof w=="function"){j(u,v,w);delete t[v]}});if(r==-1){s.onCuepoint=this.onCuepoint}};var l=function(p,r,q,t){var s={};var o=this;var u=false;if(t){i(s,t)}m(r,function(v,w){if(typeof w=="function"){s[v]=w;delete r[v]}});i(this,{animate:function(y,z,x){if(!y){return o}if(typeof z=="function"){x=z;z=500}if(typeof y=="string"){var w=y;y={};y[w]=z;z=500}if(x){var v=e();s[v]=x}if(z===undefined){z=500}r=q._api().fp_animate(p,y,z,v);return o},css:function(w,x){if(x!==undefined){var v={};v[w]=x;w=v}r=q._api().fp_css(p,w);i(o,r);return o},show:function(){this.display="block";q._api().fp_showPlugin(p);return o},hide:function(){this.display="none";q._api().fp_hidePlugin(p);return o},toggle:function(){this.display=q._api().fp_togglePlugin(p);return o},fadeTo:function(y,x,w){if(typeof x=="function"){w=x;x=500}if(w){var v=e();s[v]=w}this.display=q._api().fp_fadeTo(p,y,x,v);this.opacity=y;return o},fadeIn:function(w,v){return o.fadeTo(1,w,v)},fadeOut:function(w,v){return o.fadeTo(0,w,v)},getName:function(){return p},getPlayer:function(){return q},_fireEvent:function(w,v,x){if(w=="onUpdate"){var y=q._api().fp_getPlugin(p);if(!y){return}i(o,y);delete o.methods;if(!u){m(y.methods,function(){var A=""+this;o[A]=function(){var B=[].slice.call(arguments);var C=q._api().fp_invoke(p,A,B);return C==="undefined"||C===undefined?o:C}});u=true}}var z=s[w];if(z){z.apply(o,v);if(w.substring(0,1)=="_"){delete s[w]}}}})};function b(o,t,z){var E=this,y=null,x,u,p=[],s={},B={},r,v,w,D,A,q;i(E,{id:function(){return r},isLoaded:function(){return(y!==null)},getParent:function(){return o},hide:function(F){if(F){o.style.height="0px"}if(y){y.style.height="0px"}return E},show:function(){o.style.height=q+"px";if(y){y.style.height=A+"px"}return E},isHidden:function(){return y&&parseInt(y.style.height,10)===0},load:function(F){if(!y&&E._fireEvent("onBeforeLoad")!==false){m(a,function(){this.unload()});x=o.innerHTML;if(x&&!flashembed.isSupported(t.version)){o.innerHTML=""}flashembed(o,t,{config:z});if(F){F.cached=true;j(B,"onLoad",F)}}return E},unload:function(){if(x.replace(/\s/g,"")!==""){if(E._fireEvent("onBeforeUnload")===false){return E}try{if(y){y.fp_close();E._fireEvent("onUnload")}}catch(F){}y=null;o.innerHTML=x}return E},getClip:function(F){if(F===undefined){F=D}return p[F]},getCommonClip:function(){return u},getPlaylist:function(){return p},getPlugin:function(F){var H=s[F];if(!H&&E.isLoaded()){var G=E._api().fp_getPlugin(F);if(G){H=new l(F,G,E);s[F]=H}}return H},getScreen:function(){return E.getPlugin("screen")},getControls:function(){return E.getPlugin("controls")},getConfig:function(F){return F?k(z):z},getFlashParams:function(){return t},loadPlugin:function(I,H,K,J){if(typeof K=="function"){J=K;K={}}var G=J?e():"_";E._api().fp_loadPlugin(I,H,K,G);var F={};F[G]=J;var L=new l(I,null,E,F);s[I]=L;return L},getState:function(){return y?y.fp_getState():-1},play:function(G,F){function H(){if(G!==undefined){E._api().fp_play(G,F)}else{E._api().fp_play()}}if(y){H()}else{E.load(function(){H()})}return E},getVersion:function(){var G="flowplayer.js 3.1.4";if(y){var F=y.fp_getVersion();F.push(G);return F}return G},_api:function(){if(!y){throw"Flowplayer "+E.id()+" not loaded when calling an API method"}return y},setClip:function(F){E.setPlaylist([F]);return E},getIndex:function(){return w}});m(("Click*,Load*,Unload*,Keypress*,Volume*,Mute*,Unmute*,PlaylistReplace,ClipAdd,Fullscreen*,FullscreenExit,Error,MouseOver,MouseOut").split(","),function(){var F="on"+this;if(F.indexOf("*")!=-1){F=F.substring(0,F.length-1);var G="onBefore"+F.substring(2);E[G]=function(H){j(B,G,H);return E}}E[F]=function(H){j(B,F,H);return E}});m(("pause,resume,mute,unmute,stop,toggle,seek,getStatus,getVolume,setVolume,getTime,isPaused,isPlaying,startBuffering,stopBuffering,isFullscreen,toggleFullscreen,reset,close,setPlaylist,addClip,playFeed").split(","),function(){var F=this;E[F]=function(H,G){if(!y){return E}var I=null;if(H!==undefined&&G!==undefined){I=y["fp_"+F](H,G)}else{I=(H===undefined)?y["fp_"+F]():y["fp_"+F](H)}return I==="undefined"||I===undefined?E:I}});E._fireEvent=function(O){if(typeof O=="string"){O=[O]}var P=O[0],M=O[1],K=O[2],J=O[3],I=0;if(z.debug){g(O)}if(!y&&P=="onLoad"&&M=="player"){y=y||c(v);A=y.clientHeight;m(p,function(){this._fireEvent("onLoad")});m(s,function(Q,R){R._fireEvent("onUpdate")});u._fireEvent("onLoad")}if(P=="onLoad"&&M!="player"){return}if(P=="onError"){if(typeof M=="string"||(typeof M=="number"&&typeof K=="number")){M=K;K=J}}if(P=="onContextMenu"){m(z.contextMenu[M],function(Q,R){R.call(E)});return}if(P=="onPluginEvent"){var F=M.name||M;var G=s[F];if(G){G._fireEvent("onUpdate",M);G._fireEvent(K,O.slice(3))}return}if(P=="onPlaylistReplace"){p=[];var L=0;m(M,function(){p.push(new h(this,L++,E))})}if(P=="onClipAdd"){if(M.isInStream){return}M=new h(M,K,E);p.splice(K,0,M);for(I=K+1;I<p.length;I++){p[I].index++}}var N=true;if(typeof M=="number"&&M<p.length){D=M;var H=p[M];if(H){N=H._fireEvent(P,K,J)}if(!H||N!==false){N=u._fireEvent(P,K,J,H)}}m(B[P],function(){N=this.call(E,M,K);if(this.cached){B[P].splice(I,1)}if(N===false){return false}I++});return N};function C(){if($f(o)){$f(o).getParent().innerHTML="";w=$f(o).getIndex();a[w]=E}else{a.push(E);w=a.length-1}q=parseInt(o.style.height,10)||o.clientHeight;if(typeof t=="string"){t={src:t}}r=o.id||"fp"+e();v=t.id||r+"_api";t.id=v;z.playerId=r;if(typeof z=="string"){z={clip:{url:z}}}if(typeof z.clip=="string"){z.clip={url:z.clip}}z.clip=z.clip||{};if(o.getAttribute("href",2)&&!z.clip.url){z.clip.url=o.getAttribute("href",2)}u=new h(z.clip,-1,E);z.playlist=z.playlist||[z.clip];var F=0;m(z.playlist,function(){var H=this;if(typeof H=="object"&&H.length){H={url:""+H}}m(z.clip,function(I,J){if(J!==undefined&&H[I]===undefined&&typeof J!="function"){H[I]=J}});z.playlist[F]=H;H=new h(H,F,E);p.push(H);F++});m(z,function(H,I){if(typeof I=="function"){if(u[H]){u[H](I)}else{j(B,H,I)}delete z[H]}});m(z.plugins,function(H,I){if(I){s[H]=new l(H,I,E)}});if(!z.plugins||z.plugins.controls===undefined){s.controls=new l("controls",null,E)}s.canvas=new l("canvas",null,E);t.bgcolor=t.bgcolor||"#000000";t.version=t.version||[9,0];t.expressInstall="http://www.flowplayer.org/swf/expressinstall.swf";function G(H){if(!E.isLoaded()&&E._fireEvent("onBeforeClick")!==false){E.load()}return f(H)}x=o.innerHTML;if(x.replace(/\s/g,"")!==""){if(o.addEventListener){o.addEventListener("click",G,false)}else{if(o.attachEvent){o.attachEvent("onclick",G)}}}else{if(o.addEventListener){o.addEventListener("click",f,false)}E.load()}}if(typeof o=="string"){flashembed.domReady(function(){var F=c(o);if(!F){throw"Flowplayer cannot access element: "+o}else{o=F;C()}})}else{C()}}var a=[];function d(o){this.length=o.length;this.each=function(p){m(o,p)};this.size=function(){return o.length}}window.flowplayer=window.$f=function(){var p=null;var o=arguments[0];if(!arguments.length){m(a,function(){if(this.isLoaded()){p=this;return false}});return p||a[0]}if(arguments.length==1){if(typeof o=="number"){return a[o]}else{if(o=="*"){return new d(a)}m(a,function(){if(this.id()==o.id||this.id()==o||this.getParent()==o){p=this;return false}});return p}}if(arguments.length>1){var r=arguments[1];var q=(arguments.length==3)?arguments[2]:{};if(typeof o=="string"){if(o.indexOf(".")!=-1){var t=[];m(n(o),function(){t.push(new b(this,k(r),k(q)))});return new d(t)}else{var s=c(o);return new b(s!==null?s:o,r,q)}}else{if(o){return new b(o,r,q)}}}return null};i(window.$f,{fireEvent:function(){var o=[].slice.call(arguments);var q=$f(o[0]);return q?q._fireEvent(o.slice(1)):null},addPlugin:function(o,p){b.prototype[o]=p;return $f},each:m,extend:i});if(typeof jQuery=="function"){jQuery.prototype.flowplayer=function(q,p){if(!arguments.length||typeof arguments[0]=="number"){var o=[];this.each(function(){var r=$f(this);if(r){o.push(r)}});return arguments.length?o[arguments[0]]:new d(o)}return this.each(function(){$f(this,k(q),p?k(p):{})})}}})();(function(){var e=typeof jQuery=="function";var i={width:"100%",height:"100%",allowfullscreen:true,allowscriptaccess:"always",quality:"high",version:null,onFail:null,expressInstall:null,w3c:false,cachebusting:false};if(e){jQuery.tools=jQuery.tools||{};jQuery.tools.flashembed={version:"1.0.4",conf:i}}function j(){if(c.done){return false}var l=document;if(l&&l.getElementsByTagName&&l.getElementById&&l.body){clearInterval(c.timer);c.timer=null;for(var k=0;k<c.ready.length;k++){c.ready[k].call()}c.ready=null;c.done=true}}var c=e?jQuery:function(k){if(c.done){return k()}if(c.timer){c.ready.push(k)}else{c.ready=[k];c.timer=setInterval(j,13)}};function f(l,k){if(k){for(key in k){if(k.hasOwnProperty(key)){l[key]=k[key]}}}return l}function g(k){switch(h(k)){case"string":k=k.replace(new RegExp('(["\\\\])',"g"),"\\$1");k=k.replace(/^\s?(\d+)%/,"$1pct");return'"'+k+'"';case"array":return"["+b(k,function(n){return g(n)}).join(",")+"]";case"function":return'"function()"';case"object":var l=[];for(var m in k){if(k.hasOwnProperty(m)){l.push('"'+m+'":'+g(k[m]))}}return"{"+l.join(",")+"}"}return String(k).replace(/\s/g," ").replace(/\'/g,'"')}function h(l){if(l===null||l===undefined){return false}var k=typeof l;return(k=="object"&&l.push)?"array":k}if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}})}function b(k,n){var m=[];for(var l in k){if(k.hasOwnProperty(l)){m[l]=n(k[l])}}return m}function a(r,t){var q=f({},r);var s=document.all;var n='<object width="'+q.width+'" height="'+q.height+'"';if(s&&!q.id){q.id="_"+(""+Math.random()).substring(9)}if(q.id){n+=' id="'+q.id+'"'}if(q.cachebusting){q.src+=((q.src.indexOf("?")!=-1?"&":"?")+Math.random())}if(q.w3c||!s){n+=' data="'+q.src+'" type="application/x-shockwave-flash"'}else{n+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'}n+=">";if(q.w3c||s){n+='<param name="movie" value="'+q.src+'" />'}q.width=q.height=q.id=q.w3c=q.src=null;for(var l in q){if(q[l]!==null){n+='<param name="'+l+'" value="'+q[l]+'" />'}}var o="";if(t){for(var m in t){if(t[m]!==null){o+=m+"="+(typeof t[m]=="object"?g(t[m]):t[m])+"&"}}o=o.substring(0,o.length-1);n+='<param name="flashvars" value=\''+o+"' />"}n+="</object>";return n}function d(m,p,l){var k=flashembed.getVersion();f(this,{getContainer:function(){return m},getConf:function(){return p},getVersion:function(){return k},getFlashvars:function(){return l},getApi:function(){return m.firstChild},getHTML:function(){return a(p,l)}});var q=p.version;var r=p.expressInstall;var o=!q||flashembed.isSupported(q);if(o){p.onFail=p.version=p.expressInstall=null;m.innerHTML=a(p,l)}else{if(q&&r&&flashembed.isSupported([6,65])){f(p,{src:r});l={MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title};m.innerHTML=a(p,l)}else{if(m.innerHTML.replace(/\s/g,"")!==""){}else{m.innerHTML="<h2>Flash version "+q+" or greater is required</h2><h3>"+(k[0]>0?"Your version is "+k:"You have no flash plugin installed")+"</h3>"+(m.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='http://www.adobe.com/go/getflashplayer'>here</a></p>");if(m.tagName=="A"){m.onclick=function(){location.href="http://www.adobe.com/go/getflashplayer"}}}}}if(!o&&p.onFail){var n=p.onFail.call(this);if(typeof n=="string"){m.innerHTML=n}}if(document.all){window[p.id]=document.getElementById(p.id)}}window.flashembed=function(l,m,k){if(typeof l=="string"){var n=document.getElementById(l);if(n){l=n}else{c(function(){flashembed(l,m,k)});return}}if(!l){return}if(typeof m=="string"){m={src:m}}var o=f({},i);f(o,m);return new d(l,o,k)};f(window.flashembed,{getVersion:function(){var m=[0,0];if(navigator.plugins&&typeof navigator.plugins["Shockwave Flash"]=="object"){var l=navigator.plugins["Shockwave Flash"].description;if(typeof l!="undefined"){l=l.replace(/^.*\s+(\S+\s+\S+$)/,"$1");var n=parseInt(l.replace(/^(.*)\..*$/,"$1"),10);var r=/r/.test(l)?parseInt(l.replace(/^.*r(.*)$/,"$1"),10):0;m=[n,r]}}else{if(window.ActiveXObject){try{var p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")}catch(q){try{p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");m=[6,0];p.AllowScriptAccess="always"}catch(k){if(m[0]==6){return m}}try{p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(o){}}if(typeof p=="object"){l=p.GetVariable("$version");if(typeof l!="undefined"){l=l.replace(/^\S+\s+(.*)$/,"$1").split(",");m=[parseInt(l[0],10),parseInt(l[2],10)]}}}}return m},isSupported:function(k){var m=flashembed.getVersion();var l=(m[0]>k[0])||(m[0]==k[0]&&m[1]>=k[1]);return l},domReady:c,asString:g,getHTML:a});if(e){jQuery.fn.flashembed=function(l,k){var m=null;this.each(function(){m=flashembed(this,l,k)});return l.api===false?this:m}}})();function introInit(noLocation){inIntro=true;if(noLocation){$('ranking_title_no_location').show();$('ranking_no_location').show();}else{introSwitchTab('events');$('mayors').innerHTML='';introLoadMayors();}
flowplayer("general_video","/flowplayer/flowplayer/flowplayer-3.1.5.swf",{plugins:{controls:null},clip:{autoPlay:false,onFinish:function(){introHideVideo('general');}},canvas:{background:'transparent url(/images/intro/bg_video_'+I18n.locale+'.png)'}});flowplayer("iphone_video","/flowplayer/flowplayer/flowplayer-3.1.5.swf",{plugins:{controls:null},clip:{autoPlay:false,onFinish:function(){introHideVideo('iphone');}}});gSpinner.hide();}
function introRefresh(){introSwitchTab(introActiveTab);$('mayors').innerHTML=''
introLoadMayors();}
function introHide(){new Effect.Parallel([new Effect.Fade('box',{sync:true}),new Effect.Fade('bottom_links',{sync:true}),new Effect.Fade('overlay',{sync:true}),new Effect.BlindUp('top',{sync:true})]);new Effect.Fade('intro',{queue:'end',duration:0.1});}
function introDestroy(){$('intro').innerHTML='';}
function introShow(){$('box').appear();$('bottom_links').appear();$('top').blindDown();$('overlay').appear({to:0.8});}
function introSwitchTab(tab){introActiveTab=tab;var tabs=$('tabs');var ranking_title_events=$('ranking_title_events');var ranking_title_bars=$('ranking_title_bars');var ranking_title_restaurants=$('ranking_title_restaurants');var ranking_title_restaurants=$('ranking_title_restaurants');var ranking_title_no_location=$('ranking_title_no_location');var ranking_title_contest=$('ranking_title_contest')
var ranking_loading=$('ranking_loading');var ranking_list=$('ranking_list');var ranking_no_location=$('ranking_no_location');var ranking_contest=$('ranking_contest');ranking_title_no_location.hide();ranking_title_events.hide();ranking_title_bars.hide();ranking_title_restaurants.hide();ranking_title_contest.hide();ranking_list.hide();ranking_no_location.hide();ranking_contest.hide();switch(tab){case'contest':tabs.removeClassName('bars');tabs.removeClassName('events');tabs.removeClassName('restaurants');tabs.addClassName('contest');ranking_title_contest.show();ranking_contest.show();break;case'events':tabs.removeClassName('bars');tabs.removeClassName('restaurants');tabs.removeClassName('contest');tabs.addClassName('events');ranking_title_events.show();ranking_loading.show();introLoadEvents(function(){ranking_loading.hide();ranking_list.show();});break;case'bars':tabs.removeClassName('restaurants');tabs.removeClassName('events');tabs.removeClassName('contest');tabs.addClassName('bars');ranking_title_bars.show();ranking_loading.show();introLoadPlaces('bar',function(){ranking_loading.hide();ranking_list.show();});break;case'restaurants':tabs.removeClassName('bars');tabs.removeClassName('events');tabs.removeClassName('contest');tabs.addClassName('restaurants');ranking_title_restaurants.show();ranking_loading.show();introLoadPlaces('restaurant',function(){ranking_loading.hide();ranking_list.show();});break;}}
function introLoadEvents(onCompleteCallback){var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();var parameters={swlat:sw.lat(),swlng:sw.lng(),nelat:ne.lat(),nelng:ne.lng()};new Ajax.Updater('ranking_list','/events/intro_calendar',{method:'get',parameters:parameters,onComplete:function(){onCompleteCallback();}});}
function introLoadPlaces(tag,onCompleteCallback){var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();var parameters={name_or_tag:tag,swlat:sw.lat(),swlng:sw.lng(),nelat:ne.lat(),nelng:ne.lng()};new Ajax.Updater('ranking_list','/places/ranking_intro',{method:'get',parameters:parameters,onComplete:function(){onCompleteCallback();}});}
function introLoadMayors(){var sw=map.getBounds().getSouthWest();var ne=map.getBounds().getNorthEast();var parameters={swlat:sw.lat(),swlng:sw.lng(),nelat:ne.lat(),nelng:ne.lng()};new Ajax.Updater('mayors','/places/recent_mayors',{method:'get',parameters:parameters});}
function introFeedbackOver(){$('feedback').addClassName('over');}
function introFeedbackOut(){$('feedback').removeClassName('over');}
function introShowVideo(title){new Effect.Fade('box');new Effect.Appear(title+'_video_container',{queue:'end',afterFinish:function(){flowplayer(title+'_video').play();}});}
function introHideVideo(title){new Effect.Fade(title+'_video_container',{beforeStart:function(){flowplayer(title+'_video').stop();}});new Effect.Appear('box',{queue:'end'});}
function page_navigate(state){if(window.location.pathname!=''&&window.location.pathname!='/'&&window.location.pathname.substring(0,5)!='/rdv/'){window.location.href=window.location.protocol+'//'+window.location.host+'/#page='+state;}else{YAHOO.util.History.navigate('page',state);}}
function page_stateChangeHandler(state){var index=state.indexOf('-',0);var page;var parameters;if(index<0){page=state;parameters="";}else{page=state.substr(0,state.indexOf('-',0));parameters=state.substring(state.indexOf('-',0)+1);}
switch(page){case'place':requestPlace(parameters);break;case'event':requestEvent(parameters);break;case'calendar':requestCalendar(parameters);break;case'intro':requestIntro();break;case'myspace':requestMyspace();case'map':introDestroy();RedBox.close();break;case'signup':requestSignup();break;case'gangmap':requestGangmap();break;case'place_smallinfo':requestPlaceSmallinfo(parameters);break;case'user':requestUser(parameters);default:}}
YAHOO.util.History.register("page",(YAHOO.util.History.getBookmarkedState("page")||""),page_stateChangeHandler);YAHOO.util.History.onReady(function(){var pageState=YAHOO.util.History.getCurrentState("page")
page_stateChangeHandler(pageState);});function displayPlace(id){page_navigate('place-'+id);}
function displayPlaceSmallinfo(id,lat,lng){page_navigate('place_smallinfo-'+id+'/'+lat+'/'+lng);}
function requestPlace(id){introDestroy();RedBox.close();new Ajax.Request('/places/info/'+id,{asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()},onSuccess:function(){if(typeof pageTracker!='undefined'){pageTracker._trackPageview("/places/info/<%= @place.to_param %>");}}});}
function requestPlaceSmallinfo(parameters){introDestroy();RedBox.close();parameters=parameters.split('/');showSimpleMarker(parameters[0],'Place',null,parameters[1],parameters[2]);}
var newplace_proposedTags=new Array();function newplace_updateProposedTags(event){var e=Event.element(event);if(typeof newplace_proposedTags[e.id]!='undefined'){$$('#edit_place_form select.tag_for_'+newplace_proposedTags[e.id]).each(function(element){element.value="";});$$('#edit_place_form li.tag_for_'+newplace_proposedTags[e.id]).invoke('hide');}
newplace_proposedTags[e.id]=e.value.gsub(/[^a-z0-9_]/,'_');$$('#edit_place_form li.tag_for_'+newplace_proposedTags[e.id]).invoke('show');}
function place_claimBenefit(benefit_id){new Ajax.Request('/places/claim_benefit',{asynchronous:true,evalScripts:true,parameters:{benefit_id:benefit_id}});}
function place_checkSimilarity(){$('similar_place_links').hide();$('similar_place_spinner').show();new Ajax.Updater('similar_place_links','/places/find_similar',{asynchronous:true,evalScripts:true,parameters:{lat:$F('place_lat'),lng:$F('place_lng'),name:$F('place_name')},onComplete:function(){$('similar_place_spinner').hide();$('similar_place_links').show();}});}
function contentSwap(el1,el2){var tmp=el1.innerHTML;el1.innerHTML=el2.innerHTML;el2.innerHTML=tmp;}
function translateReview(review_id,srcLang,destLang){if(destLang==undefined)
destLang=I18n.locale;var srcEl=$('review_content_'+review_id);var destEl=$('translated_review_content_'+review_id);if(destEl.innerHTML.blank()){var text=srcEl.innerHTML;google.language.translate(text,srcLang,destLang,function(result){if(result.translation){destEl.innerHTML=result.translation;contentSwap(srcEl,destEl);}});}else{contentSwap(srcEl,destEl);}
$('review_translate_'+review_id).hide();$('review_untranslate_'+review_id).show();}
function untranslateReview(review_id){contentSwap($('translated_review_content_'+review_id),$('review_content_'+review_id));$('review_untranslate_'+review_id).hide();$('review_translate_'+review_id).show();}
function displayEvent(id){page_navigate('event-'+id);}
function requestEvent(id){introDestroy();RedBox.close();new Ajax.Request('/events/info/'+id,{asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()},onSuccess:function(){if(typeof pageTracker!='undefined'){pageTracker._trackPageview("/events/info/"+id);}}});}
function displayGangmap(){page_navigate('gangmap');new Ajax.Request()}
function requestGangmap(){introDestroy();RedBox.close();var center=map.getCenter();var parameters={lat:center.lat(),lng:center.lng(),zoom:map.getZoom()};new Ajax.Request('/gangmap',{parameters:parameters,asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()}});}
var gangmap=null;var Gangmap=Class.create({initialize:function(lat,lng,zoom){this.map=null;this.circles=new Array();this.parameters={mode:'2',correction:'2',coeff:1,n:50,debug:false,precision:10,auto_coeff:true}
this.colors={};this.places=null;this.map=new GMap2($('gangmap_map'));this.map.setCenter(new GLatLng(lat,lng),zoom);GEvent.bind(this.map,"moveend",this,this.updateStatistics);this.updateStatistics();},updateStatistics:function(){var sw=this.map.getBounds().getSouthWest();var ne=this.map.getBounds().getNorthEast();var parameters={swlat:sw.lat(),swlng:sw.lng(),nelat:ne.lat(),nelng:ne.lng()};new Ajax.Updater('gangmap_statistics','/gangmap/statistics',{parameters:parameters,asynchronous:true,evalScripts:true,onLoading:function(){gSpinner.show()}});},resetCircles:function(){this.circles.each(function(circle){GEvent.removeListener(circle.listeners.mouseover);GEvent.removeListener(circle.listeners.mouseout);this.map.removeOverlay(circle.polygon);});this.circles=new Array();},updateCircles:function(){if(this.places!=null){this.resetCircles();this.drawCircles();}},drawCircles:function(places){this.resetCircles();if(typeof places!='undefined'){this.places=places.sortBy(function(p){return-p.p_points;});}
if(this.parameters.n>0){var places=this.places.slice(0,this.parameters.n);}else{var places=this.places;}
if(this.parameters.auto_coeff){this.parameters.coeff=places.length/50;$('gm_coeff').value=this.parameters.coeff;}
$('n_places').innerHTML=places.length;var me=this;places.each(function(p){var radius=me.computeRadius(p,places);me.drawCircle(p,radius);});},computeRadius:function(place,places){var total_points=places.inject(0,function(sum,p){return sum+p.p_points;});var radius;switch(this.parameters.mode){case'0':radius=1;break;case'1':radius=1/places.length;break;case'2':radius=place.p_points/total_points;break;case'3':radius=place.o_points/place.p_points
break;}
var sw=this.map.getBounds().getSouthWest();var ne=this.map.getBounds().getNorthEast();var nw=new GLatLng(ne.lat(),sw.lng());var se=new GLatLng(sw.lat(),ne.lng());var deltaX=nw.distanceFrom(ne)/1000;var deltaY=nw.distanceFrom(sw)/1000;switch(this.parameters.correction){case'0':break;case'1':var area=deltaX*deltaY;radius*=area;break;case'2':var diagonal=Math.sqrt(deltaX*deltaX+deltaY*deltaY);radius*=diagonal;break;}
return radius*this.parameters.coeff;},setColor:function(id,color){this.colors[id]=color;this.updateCircles();},getColor:function(id){if(typeof this.colors[id]=='undefined'){return null;}
return this.colors[id];},setParameter:function(name,value){this.parameters[name]=value;this.updateCircles();},drawCircle:function(place,radius){if(this.parameters.debug){console.log('final_radius='+radius+' km');console.log('--');}
var color=this.getColor(place.o_id);if(color==null){return;}
var circlePoints=Array();with(Math){var d=radius/6378.8;var lat1=(PI/180)*place.lat;var lng1=(PI/180)*place.lng;for(var a=0;a<361;a+=this.parameters.precision){var tc=(PI/180)*a;var y=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));var dlng=atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));var x=((lng1-dlng+PI)%(2*PI))-PI;var point=new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));circlePoints.push(point);}
if(d<1.5678565720686044){var polygon=new GPolygon(circlePoints,color,1,1,color,0.25)}else{var polygon=new GPolygon(circlePoints,color,1,1);}
var circle={polygon:polygon,listeners:{mouseover:null,mouseout:null}};var me=this;circle.listeners.mouseout=GEvent.addListener(circle.polygon,'mouseout',function(){$('gangmap_place_'+place.p_id).hide();});circle.listeners.mouseover=GEvent.addListener(circle.polygon,'mouseover',function(){var bubble=$('gangmap_place_'+place.p_id);var pos=me.map.fromLatLngToContainerPixel(new GLatLng(place.lat,place.lng));var d=bubble.getDimensions();var dx=d.width/2;var dy=d.height/2;bubble.setStyle({top:(20+pos.y-dy)+'px',left:(20+pos.x-dx)+'px'});bubble.show();});this.map.addOverlay(circle.polygon);this.circles.push(circle);}}});function toggleHelpElement(event){var el=Event.element(event);el.toggleClassName('unfolded');Effect.toggle(el.next('div'),'blind');return false;}
function installVideos(){switch(I18n.locale){case'fr':var ids=["help_video_signup","help_video_fconnect","help_video_rdv","help_video_create_place","help_video_search_places","help_video_events","help_video_move_map","help_video_im_here"];break;case'en':case'de':var ids=["help_video_rdv","help_video_create_place","help_video_search_places","help_video_events"];break;case'es':var ids=["help_video_rdv","help_video_create_place","help_video_search_places"];break;default:return false;}
ids.each(function(e){flowplayer(e,"/flowplayer/flowplayer/flowplayer-3.1.5.swf",{plugins:{controls:null},clip:{autoPlay:false},canvas:{background:'transparent url(/images/help_video_bg_big.png)'}});});return false;}
YAHOO.namespace('whardy.widget');YAHOO.whardy.widget.iCalendarGroup=function(ctr,cfg){this._iState=0;if(YAHOO.lang.isUndefined(cfg)){var cfg={};}
cfg.multi_select=true;YAHOO.whardy.widget.iCalendarGroup.superclass.constructor.call(this,ctr,cfg);this.beforeSelectEvent.subscribe(this._iOnBeforeSelect,this,true);this.selectEvent.subscribe(this._iOnSelect,this,true);this.beforeDeselectEvent.subscribe(this._iOnBeforeDeselect,this,true);this.deselectEvent.subscribe(this._iOnDeselect,this,true);};YAHOO.lang.extend(YAHOO.whardy.widget.iCalendarGroup,YAHOO.widget.CalendarGroup);YAHOO.whardy.widget.iCalendarGroup._DEFAULT_CONFIG=YAHOO.widget.CalendarGroup._DEFAULT_CONFIG;YAHOO.whardy.widget.iCalendarGroup.prototype._dateString=function(d){var a=new Array();a[this.cfg.getProperty(YAHOO.whardy.widget.iCalendarGroup._DEFAULT_CONFIG.MDY_MONTH_POSITION.key)-1]=(d.getMonth()+1);a[this.cfg.getProperty(YAHOO.whardy.widget.iCalendarGroup._DEFAULT_CONFIG.MDY_DAY_POSITION.key)-1]=d.getDate();a[this.cfg.getProperty(YAHOO.whardy.widget.iCalendarGroup._DEFAULT_CONFIG.MDY_YEAR_POSITION.key)-1]=d.getFullYear();var s=this.cfg.getProperty(YAHOO.whardy.widget.iCalendarGroup._DEFAULT_CONFIG.DATE_FIELD_DELIMITER.key);return a.join(s);};YAHOO.whardy.widget.iCalendarGroup.prototype._dateIntervalString=function(l,u){var s=this.cfg.getProperty(YAHOO.whardy.widget.iCalendarGroup._DEFAULT_CONFIG.DATE_RANGE_DELIMITER.key);return(this._dateString(l)
+s+this._dateString(u));};YAHOO.whardy.widget.iCalendarGroup.prototype.getInterval=function(){var dates=this.getSelectedDates();if(dates.length>0){var l=dates[0];var u=dates[dates.length-1];return[l,u];}
else{return[];}}
YAHOO.whardy.widget.iCalendarGroup.prototype.setInterval=function(d1,d2){var b=(d1<=d2);var l=b?d1:d2;var u=b?d2:d1;this.cfg.setProperty('selected',this._dateIntervalString(l,u),false);this._iState=2;}
YAHOO.whardy.widget.iCalendarGroup.prototype.resetInterval=function(){this.cfg.setProperty('selected',[],false);this._iState=0;}
YAHOO.whardy.widget.iCalendarGroup.prototype._iOnBeforeSelect=function(t,a,o){this._iState=(this._iState+1)%3;if(this._iState==0){this.deselectAll();this._iState++;}}
YAHOO.whardy.widget.iCalendarGroup.prototype._iOnSelect=function(t,a,o){var dates=this.getSelectedDates();if(dates.length>1){var l=dates[0];var u=dates[dates.length-1];this.cfg.setProperty('selected',this._dateIntervalString(l,u),false);}
if(this._iState!=1){this._disableReservedDays();this._disableForbiddenStartDays();}else{this.removeRenderers();this._disableEarlyEndDays();}
this.render();}
YAHOO.whardy.widget.iCalendarGroup.prototype._iOnBeforeDeselect=function(t,a,o){if(this._iState!=0){return false;}}
YAHOO.whardy.widget.iCalendarGroup.prototype._iOnDeselect=function(t,a,o){if(this._iState!=0){this._iState=0;this.deselectAll();var d=a[0];var date=YAHOO.widget.DateMath.getDate(d[0],d[1]-1,d[2]);var page=this.getCalendarPage(date);if(page){page.beforeSelectEvent.fire();this.cfg.setProperty('selected',this._dateString(date),false);page.selectEvent.fire([d]);}
return false;}}
YAHOO.whardy.widget.iCalendarGroup.prototype._disableForbiddenStartDays=function(days){}
YAHOO.whardy.widget.iCalendarGroup.prototype._disableReservedDays=function(){}
YAHOO.whardy.widget.iCalendarGroup.prototype._disableEarlyEndDays=function(duration){}
YAHOO.namespace('mil');YAHOO.mil.intervalCalendar=function(ctr,cfg,icfg){if(YAHOO.lang.isUndefined(cfg)){var cfg={};}
YAHOO.mil.intervalCalendar.superclass.constructor.call(this,ctr,cfg);this.cfg.setProperty("MONTHS_LONG",I18n.t('calendar_date_select.date.months'));var wd=I18n.t('calendar_date_select.date.weekdays');this.cfg.setProperty("WEEKDAYS_SHORT",[wd[6],wd[0],wd[1],wd[2],wd[3],wd[4],wd[5]]);this._minDate=this.cfg.getProperty("mindate");this._maxDate=this.cfg.getProperty("maxdate");this.futureBookings=icfg.futureBookings.collect(function(period){return[new Date(period[0]),new Date(period[1])];});this.forbiddenStartDays=icfg.forbiddenStartDays;this.minimumDuration=icfg.minimumDuration||1;this._disableReservedDays();this._disableForbiddenStartDays();if(this.forbiddenStartDays.length>0){var tooltipDiv=new Element('div');tooltipDiv.update($('booking_can_start').innerHTML.strip());$$('body')[0].appendChild(tooltipDiv);this.tooltip=new Control.Window(tooltipDiv,{className:'tooltip'});}
this.selectEvent.subscribe(this._mOnSelect,this,true);YAHOO.util.Event.addListener(document.getElementById("booking_clear_button"),"click",this.clearSelection,this,true);};YAHOO.lang.extend(YAHOO.mil.intervalCalendar,YAHOO.whardy.widget.iCalendarGroup);YAHOO.mil.intervalCalendar.prototype.clearSelection=function(){$('prereserved_booking').update('')
$('booking_start_date_display').update('');$('booking_end_date_display').update('');$('booking_price').update('-');$('booking_submit_button').disable();this.resetInterval();this.removeRenderers();this._disableReservedDays();this._disableForbiddenStartDays();this.render();return false;}
YAHOO.mil.intervalCalendar.prototype._mOnSelect=function(t,a,o){var interval=this.getInterval();var inTxt=$('booking_start_date_display');var outTxt=$('booking_end_date_display');if(interval.length==2){inDate=interval[0];$('booking_start_date').value=inDate;inTxt.update(inDate.getDate()+"/"+(inDate.getMonth()+1)+"/"+inDate.getFullYear());outDate=interval[1];if(outDate.getDate()-inDate.getDate()<this.minimumDuration){outDate.setDate(inDate.getDate()+this.minimumDuration-1);}
$('booking_end_date').value=outDate;outTxt.update(outDate.getDate()+"/"+(outDate.getMonth()+1)+"/"+outDate.getFullYear());new Ajax.Request('/bookings/precalc_price',{parameters:Form.serialize($('booking_form'),true),onLoading:function(){$('booking_price').next('span.spinner').show()},onComplete:function(){$('booking_price').next('span.spinner').hide()}})}
if(this._iState!=0){$('booking_submit_button').enable();}else{$('booking_submit_button').disable();}}
YAHOO.mil.intervalCalendar.prototype._mOnRender=function(t,a,o){$$('div.tooltip').invoke('remove');$$('td.calcell.forbidden').each(function(element){new Control.ToolTip($(element),$('booking_can_start').innerHTML.strip(),{className:'tooltip'});});}
YAHOO.mil.intervalCalendar.prototype.setTooltipPosition=function(element){var element=$(element);var x=element.cumulativeOffset().left-element.cumulativeScrollOffset().left+30;var y=element.cumulativeOffset().top-element.cumulativeScrollOffset().top+10;this.tooltip.options.position=[x,y];}
YAHOO.mil.intervalCalendar.prototype.renderCellForbidden=function(workingDate,cell){cell.innerHTML='<a href="#" onclick="return false" onmouseover="intervalCal.setTooltipPosition(this);intervalCal.tooltip.open()" onmouseout="intervalCal.tooltip.close()">'
+this.buildDayLabel(workingDate)+"</a>";YAHOO.util.Dom.addClass(cell,'forbidden');return YAHOO.widget.Calendar.STOP_RENDER;}
YAHOO.mil.intervalCalendar.prototype.renderCellSelectedUnselectable=function(workingDate,cell){cell.innerHTML=workingDate.getDate();YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT1);return YAHOO.widget.Calendar.STOP_RENDER;}
YAHOO.mil.intervalCalendar.prototype._disableReservedDays=function(days){var days=days||this.futureBookings;days.each(function(period){var p=period[0].format("M/d/y")+'-'+period[1].format("M/d/y");this.addRenderer(p,this.renderBodyCellRestricted);},this);}
YAHOO.mil.intervalCalendar.prototype._disableForbiddenStartDays=function(){this.cfg.setProperty("mindate",this._minDate);this.cfg.setProperty("maxdate",this._maxDate);var minDate=new Date(this.cfg.getProperty("mindate")),maxDate=new Date(this.cfg.getProperty("maxdate"));minDate.setDay(0);maxDate.setDay(7);var numWeeks=Math.ceil((maxDate-minDate)/(1000*60*60*24*7));for(var i=0;i<numWeeks;i++){this.forbiddenStartDays.each(function(wd){var temp=minDate.clone();temp.setDate(minDate.getDate()+7*i+wd);var skip=false;this.futureBookings.each(function(period){var low=new Date(period[0]);var up=new Date(period[1]);up.setDate(up.getDate()+1);if(YAHOO.widget.DateMath.between(temp,low,up)){skip=true;return;}},this);var interval=this.getInterval();if(!skip&&interval.length==2){var low=new Date(interval[0]);var up=new Date(interval[1]);up.setDate(up.getDate()+1);if(YAHOO.widget.DateMath.between(temp,low,up)){skip=true;return;}}
if(!skip){this.addRenderer(temp.format("M/d/y"),this.renderCellForbidden);}},this);}}
YAHOO.mil.intervalCalendar.prototype._disableEarlyEndDays=function(duration){var duration=duration||this.minimumDuration;this._minDate=this.cfg.getProperty("mindate");this._maxDate=this.cfg.getProperty("maxdate");var interval=this.getInterval();var inDate=interval[0];this.cfg.setProperty("mindate",inDate.format("M/d/y"));if(this.futureBookings&&this.futureBookings.length>0){var maxDate;maxDate=this.futureBookings.min(function(period){if(YAHOO.widget.DateMath.after(period[0],inDate))
return period[0];});if(maxDate!=undefined){maxDate.setDate(maxDate.getDate()-1);this.cfg.setProperty("maxdate",maxDate.format("M/d/y"));}}
var minOutDate=inDate.clone();minOutDate.setDate(inDate.getDate()+duration-1);var period=inDate.format("M/d/y")+'-'+minOutDate.format("M/d/y");this.addRenderer(period,this.renderCellSelectedUnselectable);}
var area_loaded={area:new Array(),bar:new Array(),restaurant:new Array()};function area_getContent(id){if(!area_loaded.area.member(id)){area_loaded.area.push(id);$('area_'+id).show();new Ajax.Updater('area_'+id,'/area/content',{method:'get',parameters:{id:id}});}else{$('area_'+id).toggle();}}
function area_find(tag,id){if(!area_loaded[tag].member(id)){area_loaded[tag].push(id);$('area_'+id+'_'+tag).show();new Ajax.Updater('area_'+id+'_'+tag,'/area/search',{method:'get',parameters:{tag:tag,id:id}});}else{$('area_'+id+'_'+tag).toggle();}}
function reviews_expandMiniform(id_prefix){var widget=$(id_prefix+'_edit_review');widget.down('.mini').hide();widget.down('.normal').show();widget.down('.normal textarea').focus();updateStarRating(id_prefix+'_review_mark',$F(id_prefix+'_mini_mark'));}
function reviews_minimizeMiniform(id_prefix){var widget=$(id_prefix+'_edit_review');widget.down('.normal').hide();widget.down('.mini').show();updateStarRating(id_prefix+'_mini_mark',0);}
var Cookies={started:false,values:{},create:function(name,value,days){if(!this.started){this.init();}
if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires=date.toGMTString();}else{var date=new Date();date.setTime(date.getTime()+(365*24*60*60*1000));var expires=date.toGMTString();};this.values[name]=value;document.cookie=name+"="+escape(value)+"; expires="+expires+";path=/";},init:function(){var allCookies=document.cookie.split('; ');for(var i=0;i<allCookies.length;i++){var cookiesPair=allCookies[i].split('=');this.values[cookiesPair[0]]=unescape(cookiesPair[1]);}
this.started=true;},read:function(name){if(!this.started){this.init();}
return this.values[name];},erase:function(name){this.create(name,'',-1);this.values[name]=null;}}
if(window.Widget==undefined){window.Widget={};}
Widget.Textarea=Class.create({initialize:function(textarea,options){this.textarea=$(textarea);this.options=$H({}).update(options);var browser=YAHOO.env.ua;if(browser.gecko>1.9||browser.webkit||browser.opera){this.textarea.setStyle({overflowY:'hidden',resize:'none'});}
this.original_height=parseInt(this.textarea.getStyle('height'));this.previous_scroll_top=0;this._shadow=this.textarea.cloneNode(false).setStyle({lineHeight:this.textarea.getStyle('lineHeight'),fontSize:this.textarea.getStyle('fontSize'),fontFamily:this.textarea.getStyle('fontFamily'),letterSpacing:this.textarea.getStyle('letterSpacing'),width:this.textarea.getStyle('width'),height:this.textarea.getStyle('height'),position:'absolute',top:'-10000px',left:'-10000px'}).writeAttribute({id:null,name:null,disabled:true});this.textarea.insert({after:this._shadow});this.textarea.observe('keyup',this.refresh.bind(this));this.textarea.observe('change',this.refresh.bind(this));this.refresh();},refresh:function(){this._shadow.update($F(this.textarea).replace(/</g,'&lt;').replace(/&/g,'&amp;')).scrollTop=10000;if(this._shadow.scrollTop==this.previous_scroll_top){return;}
this.textarea.setStyle({height:(this._shadow.scrollTop+this.original_height)+'px'});this.previous_scroll_top=this._shadow.scrollTop;}});function displayGratification(innerHTML){$('gratification').innerHTML=innerHTML;$('gratification').show();}
function hideGratification(){$('gratification').fade();}