// source/mootools-1.2-more.js
// source/dropMenu.js
// source/milkbox.js
// source/popupbox.js

//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

Fx.Slide=new Class({Extends:Fx,options:{mode:"vertical"},initialize:function(B,A){this.addEvent("complete",function(){this.open=(this.wrapper["offset"+this.layout.capitalize()]!=0);
if(this.open&&Browser.Engine.webkit419){this.element.dispose().inject(this.wrapper);}},true);this.element=this.subject=$(B);this.parent(A);var C=this.element.retrieve("wrapper");
this.wrapper=C||new Element("div",{styles:$extend(this.element.getStyles("margin","position"),{overflow:"hidden"})}).wraps(this.element);this.element.store("wrapper",this.wrapper).setStyle("margin",0);
this.now=[];this.open=true;},vertical:function(){this.margin="margin-top";this.layout="height";this.offset=this.element.offsetHeight;},horizontal:function(){this.margin="margin-left";
this.layout="width";this.offset=this.element.offsetWidth;},set:function(A){this.element.setStyle(this.margin,A[0]);this.wrapper.setStyle(this.layout,A[1]);
return this;},compute:function(E,D,C){var B=[];var A=2;A.times(function(F){B[F]=Fx.compute(E[F],D[F],C);});return B;},start:function(B,E){if(!this.check(arguments.callee,B,E)){return this;
}this[E||this.options.mode]();var D=this.element.getStyle(this.margin).toInt();var C=this.wrapper.getStyle(this.layout).toInt();var A=[[D,C],[0,this.offset]];
var G=[[D,C],[-this.offset,0]];var F;switch(B){case"in":F=A;break;case"out":F=G;break;case"toggle":F=(this.wrapper["offset"+this.layout.capitalize()]==0)?A:G;
}return this.parent(F[0],F[1]);},slideIn:function(A){return this.start("in",A);},slideOut:function(A){return this.start("out",A);},hide:function(A){this[A||this.options.mode]();
this.open=false;return this.set([-this.offset,0]);},show:function(A){this[A||this.options.mode]();this.open=true;return this.set([0,this.offset]);},toggle:function(A){return this.start("toggle",A);
}});Element.Properties.slide={set:function(B){var A=this.retrieve("slide");if(A){A.cancel();}return this.eliminate("slide").store("slide:options",$extend({link:"cancel"},B));
},get:function(A){if(A||!this.retrieve("slide")){if(A||!this.retrieve("slide:options")){this.set("slide",A);}this.store("slide",new Fx.Slide(this,this.retrieve("slide:options")));
}return this.retrieve("slide");}};Element.implement({slide:function(D,E){D=D||"toggle";var B=this.get("slide"),A;switch(D){case"hide":B.hide(E);break;case"show":B.show(E);
break;case"toggle":var C=this.retrieve("slide:flag",B.open);B[(C)?"slideOut":"slideIn"](E);this.store("slide:flag",!C);A=true;break;default:B.start(D,E);
}if(!A){this.eliminate("slide:flag");}return this;}});Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(B,A){this.element=this.subject=$(B);
this.parent(A);var D=this.cancel.bind(this,false);if($type(this.element)!="element"){this.element=$(this.element.getDocument().body);}var C=this.element;
if(this.options.wheelStops){this.addEvent("start",function(){C.addEvent("mousewheel",D);},true);this.addEvent("complete",function(){C.removeEvent("mousewheel",D);
},true);}},set:function(){var A=Array.flatten(arguments);this.element.scrollTo(A[0],A[1]);},compute:function(E,D,C){var B=[];var A=2;A.times(function(F){B.push(Fx.compute(E[F],D[F],C));
});return B;},start:function(C,H){if(!this.check(arguments.callee,C,H)){return this;}var E=this.element.getSize(),F=this.element.getScrollSize();var B=this.element.getScroll(),D={x:C,y:H};
for(var G in D){var A=F[G]-E[G];if($chk(D[G])){D[G]=($type(D[G])=="number")?D[G].limit(0,A):A;}else{D[G]=B[G];}D[G]+=this.options.offset[G];}return this.parent([B.x,B.y],[D.x,D.y]);
},toTop:function(){return this.start(false,0);},toLeft:function(){return this.start(0,false);},toRight:function(){return this.start("right",false);},toBottom:function(){return this.start(false,"bottom");
},toElement:function(B){var A=$(B).getPosition(this.element);return this.start(A.x,A.y);}});Fx.Elements=new Class({Extends:Fx.CSS,initialize:function(B,A){this.elements=this.subject=$$(B);
this.parent(A);},compute:function(G,H,I){var C={};for(var D in G){var A=G[D],E=H[D],F=C[D]={};for(var B in A){F[B]=this.parent(A[B],E[B],I);}}return C;
},set:function(B){for(var C in B){var A=B[C];for(var D in A){this.render(this.elements[C],D,A[D],this.options.unit);}}return this;},start:function(C){if(!this.check(arguments.callee,C)){return this;
}var H={},I={};for(var D in C){var F=C[D],A=H[D]={},G=I[D]={};for(var B in F){var E=this.prepare(this.elements[D],B,F[B]);A[B]=E.from;G[B]=E.to;}}return this.parent(H,I);
}});var Drag=new Class({Implements:[Events,Options],options:{snap:6,unit:"px",grid:false,style:true,limit:false,handle:false,invert:false,preventDefault:false,modifiers:{x:"left",y:"top"}},initialize:function(){var B=Array.link(arguments,{options:Object.type,element:$defined});
this.element=$(B.element);this.document=this.element.getDocument();this.setOptions(B.options||{});var A=$type(this.options.handle);this.handles=(A=="array"||A=="collection")?$$(this.options.handle):$(this.options.handle)||this.element;
this.mouse={now:{},pos:{}};this.value={start:{},now:{}};this.selection=(Browser.Engine.trident)?"selectstart":"mousedown";this.bound={start:this.start.bind(this),check:this.check.bind(this),drag:this.drag.bind(this),stop:this.stop.bind(this),cancel:this.cancel.bind(this),eventStop:$lambda(false)};
this.attach();},attach:function(){this.handles.addEvent("mousedown",this.bound.start);return this;},detach:function(){this.handles.removeEvent("mousedown",this.bound.start);
return this;},start:function(C){if(this.options.preventDefault){C.preventDefault();}this.fireEvent("beforeStart",this.element);this.mouse.start=C.page;
var A=this.options.limit;this.limit={x:[],y:[]};for(var D in this.options.modifiers){if(!this.options.modifiers[D]){continue;}if(this.options.style){this.value.now[D]=this.element.getStyle(this.options.modifiers[D]).toInt();
}else{this.value.now[D]=this.element[this.options.modifiers[D]];}if(this.options.invert){this.value.now[D]*=-1;}this.mouse.pos[D]=C.page[D]-this.value.now[D];
if(A&&A[D]){for(var B=2;B--;B){if($chk(A[D][B])){this.limit[D][B]=$lambda(A[D][B])();}}}}if($type(this.options.grid)=="number"){this.options.grid={x:this.options.grid,y:this.options.grid};
}this.document.addEvents({mousemove:this.bound.check,mouseup:this.bound.cancel});this.document.addEvent(this.selection,this.bound.eventStop);},check:function(A){if(this.options.preventDefault){A.preventDefault();
}var B=Math.round(Math.sqrt(Math.pow(A.page.x-this.mouse.start.x,2)+Math.pow(A.page.y-this.mouse.start.y,2)));if(B>this.options.snap){this.cancel();this.document.addEvents({mousemove:this.bound.drag,mouseup:this.bound.stop});
this.fireEvent("start",this.element).fireEvent("snap",this.element);}},drag:function(A){if(this.options.preventDefault){A.preventDefault();}this.mouse.now=A.page;
for(var B in this.options.modifiers){if(!this.options.modifiers[B]){continue;}this.value.now[B]=this.mouse.now[B]-this.mouse.pos[B];if(this.options.invert){this.value.now[B]*=-1;
}if(this.options.limit&&this.limit[B]){if($chk(this.limit[B][1])&&(this.value.now[B]>this.limit[B][1])){this.value.now[B]=this.limit[B][1];}else{if($chk(this.limit[B][0])&&(this.value.now[B]<this.limit[B][0])){this.value.now[B]=this.limit[B][0];
}}}if(this.options.grid[B]){this.value.now[B]-=(this.value.now[B]%this.options.grid[B]);}if(this.options.style){this.element.setStyle(this.options.modifiers[B],this.value.now[B]+this.options.unit);
}else{this.element[this.options.modifiers[B]]=this.value.now[B];}}this.fireEvent("drag",this.element);},cancel:function(A){this.document.removeEvent("mousemove",this.bound.check);
this.document.removeEvent("mouseup",this.bound.cancel);if(A){this.document.removeEvent(this.selection,this.bound.eventStop);this.fireEvent("cancel",this.element);
}},stop:function(A){this.document.removeEvent(this.selection,this.bound.eventStop);this.document.removeEvent("mousemove",this.bound.drag);this.document.removeEvent("mouseup",this.bound.stop);
if(A){this.fireEvent("complete",this.element);}}});Element.implement({makeResizable:function(A){return new Drag(this,$merge({modifiers:{x:"width",y:"height"}},A));
}});Drag.Move=new Class({Extends:Drag,options:{droppables:[],container:false},initialize:function(C,B){this.parent(C,B);this.droppables=$$(this.options.droppables);
this.container=$(this.options.container);if(this.container&&$type(this.container)!="element"){this.container=$(this.container.getDocument().body);}C=this.element;
var D=C.getStyle("position");var A=(D!="static")?D:"absolute";if(C.getStyle("left")=="auto"||C.getStyle("top")=="auto"){C.position(C.getPosition(C.offsetParent));
}C.setStyle("position",A);this.addEvent("start",function(){this.checkDroppables();},true);},start:function(B){if(this.container){var D=this.element,J=this.container,E=J.getCoordinates(D.offsetParent),F={},A={};
["top","right","bottom","left"].each(function(K){F[K]=J.getStyle("padding-"+K).toInt();A[K]=D.getStyle("margin-"+K).toInt();},this);var C=D.offsetWidth+A.left+A.right,I=D.offsetHeight+A.top+A.bottom;
var H=[E.left+F.left,E.right-F.right-C];var G=[E.top+F.top,E.bottom-F.bottom-I];this.options.limit={x:H,y:G};}this.parent(B);},checkAgainst:function(B){B=B.getCoordinates();
var A=this.mouse.now;return(A.x>B.left&&A.x<B.right&&A.y<B.bottom&&A.y>B.top);},checkDroppables:function(){var A=this.droppables.filter(this.checkAgainst,this).getLast();
if(this.overed!=A){if(this.overed){this.fireEvent("leave",[this.element,this.overed]);}if(A){this.overed=A;this.fireEvent("enter",[this.element,A]);}else{this.overed=null;
}}},drag:function(A){this.parent(A);if(this.droppables.length){this.checkDroppables();}},stop:function(A){this.checkDroppables();this.fireEvent("drop",[this.element,this.overed]);
this.overed=null;return this.parent(A);}});Element.implement({makeDraggable:function(A){return new Drag.Move(this,A);}});Hash.Cookie=new Class({Extends:Cookie,options:{autoSave:true},initialize:function(B,A){this.parent(B,A);
this.load();},save:function(){var A=JSON.encode(this.hash);if(!A||A.length>4096){return false;}if(A=="{}"){this.dispose();}else{this.write(A);}return true;
},load:function(){this.hash=new Hash(JSON.decode(this.read(),true));return this;}});Hash.Cookie.implement((function(){var A={};Hash.each(Hash.prototype,function(C,B){A[B]=function(){var D=C.apply(this.hash,arguments);
if(this.options.autoSave){this.save();}return D;};});return A;})());var Color=new Native({initialize:function(B,C){if(arguments.length>=3){C="rgb";B=Array.slice(arguments,0,3);
}else{if(typeof B=="string"){if(B.match(/rgb/)){B=B.rgbToHex().hexToRgb(true);}else{if(B.match(/hsb/)){B=B.hsbToRgb();}else{B=B.hexToRgb(true);}}}}C=C||"rgb";
switch(C){case"hsb":var A=B;B=B.hsbToRgb();B.hsb=A;break;case"hex":B=B.hexToRgb(true);break;}B.rgb=B.slice(0,3);B.hsb=B.hsb||B.rgbToHsb();B.hex=B.rgbToHex();
return $extend(B,this);}});Color.implement({mix:function(){var A=Array.slice(arguments);var C=($type(A.getLast())=="number")?A.pop():50;var B=this.slice();
A.each(function(D){D=new Color(D);for(var E=0;E<3;E++){B[E]=Math.round((B[E]/100*(100-C))+(D[E]/100*C));}});return new Color(B,"rgb");},invert:function(){return new Color(this.map(function(A){return 255-A;
}));},setHue:function(A){return new Color([A,this.hsb[1],this.hsb[2]],"hsb");},setSaturation:function(A){return new Color([this.hsb[0],A,this.hsb[2]],"hsb");
},setBrightness:function(A){return new Color([this.hsb[0],this.hsb[1],A],"hsb");}});function $RGB(C,B,A){return new Color([C,B,A],"rgb");}function $HSB(C,B,A){return new Color([C,B,A],"hsb");
}function $HEX(A){return new Color(A,"hex");}Array.implement({rgbToHsb:function(){var B=this[0],C=this[1],J=this[2];var G,F,H;var I=Math.max(B,C,J),E=Math.min(B,C,J);
var K=I-E;H=I/255;F=(I!=0)?K/I:0;if(F==0){G=0;}else{var D=(I-B)/K;var A=(I-C)/K;var L=(I-J)/K;if(B==I){G=L-A;}else{if(C==I){G=2+D-L;}else{G=4+A-D;}}G/=6;
if(G<0){G++;}}return[Math.round(G*360),Math.round(F*100),Math.round(H*100)];},hsbToRgb:function(){var C=Math.round(this[2]/100*255);if(this[1]==0){return[C,C,C];
}else{var A=this[0]%360;var E=A%60;var F=Math.round((this[2]*(100-this[1]))/10000*255);var D=Math.round((this[2]*(6000-this[1]*E))/600000*255);var B=Math.round((this[2]*(6000-this[1]*(60-E)))/600000*255);
switch(Math.floor(A/60)){case 0:return[C,B,F];case 1:return[D,C,F];case 2:return[F,C,B];case 3:return[F,D,C];case 4:return[B,F,C];case 5:return[C,F,D];
}}return false;}});String.implement({rgbToHsb:function(){var A=this.match(/\d{1,3}/g);return(A)?hsb.rgbToHsb():null;},hsbToRgb:function(){var A=this.match(/\d{1,3}/g);
return(A)?A.hsbToRgb():null;}});var Group=new Class({initialize:function(){this.instances=Array.flatten(arguments);this.events={};this.checker={};},addEvent:function(B,A){this.checker[B]=this.checker[B]||{};
this.events[B]=this.events[B]||[];if(this.events[B].contains(A)){return false;}else{this.events[B].push(A);}this.instances.each(function(C,D){C.addEvent(B,this.check.bind(this,[B,C,D]));
},this);return this;},check:function(C,A,B){this.checker[C][B]=true;var D=this.instances.every(function(F,E){return this.checker[C][E]||false;},this);if(!D){return ;
}this.checker[C]={};this.events[C].each(function(E){E.call(this,this.instances,A);},this);}});var Asset=new Hash({javascript:function(F,D){D=$extend({onload:$empty,document:document,check:$lambda(true)},D);
var B=new Element("script",{src:F,type:"text/javascript"});var E=D.onload.bind(B),A=D.check,G=D.document;delete D.onload;delete D.check;delete D.document;
B.addEvents({load:E,readystatechange:function(){if(["loaded","complete"].contains(this.readyState)){E();}}}).setProperties(D);if(Browser.Engine.webkit419){var C=(function(){if(!$try(A)){return ;
}$clear(C);E();}).periodical(50);}return B.inject(G.head);},css:function(B,A){return new Element("link",$merge({rel:"stylesheet",media:"screen",type:"text/css",href:B},A)).inject(document.head);
},image:function(C,B){B=$merge({onload:$empty,onabort:$empty,onerror:$empty},B);var D=new Image();var A=$(D)||new Element("img");["load","abort","error"].each(function(E){var F="on"+E;
var G=B[F];delete B[F];D[F]=function(){if(!D){return ;}if(!A.parentNode){A.width=D.width;A.height=D.height;}D=D.onload=D.onabort=D.onerror=null;G.delay(1,A,A);
A.fireEvent(E,A,1);};});D.src=A.src=C;if(D&&D.complete){D.onload.delay(1);}return A.setProperties(B);},images:function(D,C){C=$merge({onComplete:$empty,onProgress:$empty},C);
if(!D.push){D=[D];}var A=[];var B=0;D.each(function(F){var E=new Asset.image(F,{onload:function(){C.onProgress.call(this,B,D.indexOf(F));B++;if(B==D.length){C.onComplete();
}}});A.push(E);});return new Elements(A);}});var Sortables=new Class({Implements:[Events,Options],options:{snap:4,opacity:1,clone:false,revert:false,handle:false,constrain:false},initialize:function(A,B){this.setOptions(B);
this.elements=[];this.lists=[];this.idle=true;this.addLists($$($(A)||A));if(!this.options.clone){this.options.revert=false;}if(this.options.revert){this.effect=new Fx.Morph(null,$merge({duration:250,link:"cancel"},this.options.revert));
}},attach:function(){this.addLists(this.lists);return this;},detach:function(){this.lists=this.removeLists(this.lists);return this;},addItems:function(){Array.flatten(arguments).each(function(A){this.elements.push(A);
var B=A.retrieve("sortables:start",this.start.bindWithEvent(this,A));(this.options.handle?A.getElement(this.options.handle)||A:A).addEvent("mousedown",B);
},this);return this;},addLists:function(){Array.flatten(arguments).each(function(A){this.lists.push(A);this.addItems(A.getChildren());},this);return this;
},removeItems:function(){var A=[];Array.flatten(arguments).each(function(B){A.push(B);this.elements.erase(B);var C=B.retrieve("sortables:start");(this.options.handle?B.getElement(this.options.handle)||B:B).removeEvent("mousedown",C);
},this);return $$(A);},removeLists:function(){var A=[];Array.flatten(arguments).each(function(B){A.push(B);this.lists.erase(B);this.removeItems(B.getChildren());
},this);return $$(A);},getClone:function(B,A){if(!this.options.clone){return new Element("div").inject(document.body);}if($type(this.options.clone)=="function"){return this.options.clone.call(this,B,A,this.list);
}return A.clone(true).setStyles({margin:"0px",position:"absolute",visibility:"hidden",width:A.getStyle("width")}).inject(this.list).position(A.getPosition(A.getOffsetParent()));
},getDroppables:function(){var A=this.list.getChildren();if(!this.options.constrain){A=this.lists.concat(A).erase(this.list);}return A.erase(this.clone).erase(this.element);
},insert:function(C,B){var A="inside";if(this.lists.contains(B)){this.list=B;this.drag.droppables=this.getDroppables();}else{A=this.element.getAllPrevious().contains(B)?"before":"after";
}this.element.inject(B,A);this.fireEvent("sort",[this.element,this.clone]);},start:function(B,A){if(!this.idle){return ;}this.idle=false;this.element=A;
this.opacity=A.get("opacity");this.list=A.getParent();this.clone=this.getClone(B,A);this.drag=new Drag.Move(this.clone,{snap:this.options.snap,container:this.options.constrain&&this.element.getParent(),droppables:this.getDroppables(),onSnap:function(){B.stop();
this.clone.setStyle("visibility","visible");this.element.set("opacity",this.options.opacity||0);this.fireEvent("start",[this.element,this.clone]);}.bind(this),onEnter:this.insert.bind(this),onCancel:this.reset.bind(this),onComplete:this.end.bind(this)});
this.clone.inject(this.element,"before");this.drag.start(B);},end:function(){this.drag.detach();this.element.set("opacity",this.opacity);if(this.effect){var A=this.element.getStyles("width","height");
var B=this.clone.computePosition(this.element.getPosition(this.clone.offsetParent));this.effect.element=this.clone;this.effect.start({top:B.top,left:B.left,width:A.width,height:A.height,opacity:0.25}).chain(this.reset.bind(this));
}else{this.reset();}},reset:function(){this.idle=true;this.clone.destroy();this.fireEvent("complete",this.element);},serialize:function(){var C=Array.link(arguments,{modifier:Function.type,index:$defined});
var B=this.lists.map(function(D){return D.getChildren().map(C.modifier||function(E){return E.get("id");},this);},this);var A=C.index;if(this.lists.length==1){A=0;
}return $chk(A)&&A>=0&&A<this.lists.length?B[A]:B;}});var Tips=new Class({Implements:[Events,Options],options:{onShow:function(A){A.setStyle("visibility","visible");
},onHide:function(A){A.setStyle("visibility","hidden");},showDelay:100,hideDelay:100,className:null,offsets:{x:16,y:16},fixed:false},initialize:function(){var C=Array.link(arguments,{options:Object.type,elements:$defined});
this.setOptions(C.options||null);this.tip=new Element("div").inject(document.body);if(this.options.className){this.tip.addClass(this.options.className);
}var B=new Element("div",{"class":"tip-top"}).inject(this.tip);this.container=new Element("div",{"class":"tip"}).inject(this.tip);var A=new Element("div",{"class":"tip-bottom"}).inject(this.tip);
this.tip.setStyles({position:"absolute",top:0,left:0,visibility:"hidden"});if(C.elements){this.attach(C.elements);}},attach:function(A){$$(A).each(function(D){var G=D.retrieve("tip:title",D.get("title"));
var F=D.retrieve("tip:text",D.get("rel")||D.get("href"));var E=D.retrieve("tip:enter",this.elementEnter.bindWithEvent(this,D));var C=D.retrieve("tip:leave",this.elementLeave.bindWithEvent(this,D));
D.addEvents({mouseenter:E,mouseleave:C});if(!this.options.fixed){var B=D.retrieve("tip:move",this.elementMove.bindWithEvent(this,D));D.addEvent("mousemove",B);
}D.store("tip:native",D.get("title"));D.erase("title");},this);return this;},detach:function(A){$$(A).each(function(C){C.removeEvent("mouseenter",C.retrieve("tip:enter")||$empty);
C.removeEvent("mouseleave",C.retrieve("tip:leave")||$empty);C.removeEvent("mousemove",C.retrieve("tip:move")||$empty);C.eliminate("tip:enter").eliminate("tip:leave").eliminate("tip:move");
var B=C.retrieve("tip:native");if(B){C.set("title",B);}});return this;},elementEnter:function(B,A){$A(this.container.childNodes).each(Element.dispose);
var D=A.retrieve("tip:title");if(D){this.titleElement=new Element("div",{"class":"tip-title"}).inject(this.container);this.fill(this.titleElement,D);}var C=A.retrieve("tip:text");
if(C){this.textElement=new Element("div",{"class":"tip-text"}).inject(this.container);this.fill(this.textElement,C);}this.timer=$clear(this.timer);this.timer=this.show.delay(this.options.showDelay,this);
this.position((!this.options.fixed)?B:{page:A.getPosition()});},elementLeave:function(A){$clear(this.timer);this.timer=this.hide.delay(this.options.hideDelay,this);
},elementMove:function(A){this.position(A);},position:function(D){var B=window.getSize(),A=window.getScroll();var E={x:this.tip.offsetWidth,y:this.tip.offsetHeight};
var C={x:"left",y:"top"};for(var F in C){var G=D.page[F]+this.options.offsets[F];if((G+E[F]-A[F])>B[F]){G=D.page[F]-this.options.offsets[F]-E[F];}this.tip.setStyle(C[F],G);
}},fill:function(A,B){(typeof B=="string")?A.set("html",B):A.adopt(B);},show:function(){this.fireEvent("show",this.tip);},hide:function(){this.fireEvent("hide",this.tip);
}});var SmoothScroll=new Class({Extends:Fx.Scroll,initialize:function(B,C){C=C||document;var E=C.getDocument(),D=C.getWindow();this.parent(E,B);this.links=(this.options.links)?$$(this.options.links):$$(E.links);
var A=D.location.href.match(/^[^#]*/)[0]+"#";this.links.each(function(G){if(G.href.indexOf(A)!=0){return ;}var F=G.href.substr(A.length);if(F&&$(F)){this.useLink(G,F);
}},this);if(!Browser.Engine.webkit419){this.addEvent("complete",function(){D.location.hash=this.anchor;},true);}},useLink:function(B,A){B.addEvent("click",function(C){this.anchor=A;
this.toElement(A);C.stop();}.bind(this));}});var Slider=new Class({Implements:[Events,Options],options:{onTick:function(A){if(this.options.snap){A=this.toPosition(this.step);
}this.knob.setStyle(this.property,A);},snap:false,offset:0,range:false,wheel:false,steps:100,mode:"horizontal"},initialize:function(E,A,D){this.setOptions(D);
this.element=$(E);this.knob=$(A);this.previousChange=this.previousEnd=this.step=-1;this.element.addEvent("mousedown",this.clickedElement.bind(this));if(this.options.wheel){this.element.addEvent("mousewheel",this.scrolledElement.bindWithEvent(this));
}var F,B={},C={x:false,y:false};switch(this.options.mode){case"vertical":this.axis="y";this.property="top";F="offsetHeight";break;case"horizontal":this.axis="x";
this.property="left";F="offsetWidth";}this.half=this.knob[F]/2;this.full=this.element[F]-this.knob[F]+(this.options.offset*2);this.min=$chk(this.options.range[0])?this.options.range[0]:0;
this.max=$chk(this.options.range[1])?this.options.range[1]:this.options.steps;this.range=this.max-this.min;this.steps=this.options.steps||this.full;this.stepSize=Math.abs(this.range)/this.steps;
this.stepWidth=this.stepSize*this.full/Math.abs(this.range);this.knob.setStyle("position","relative").setStyle(this.property,-this.options.offset);C[this.axis]=this.property;
B[this.axis]=[-this.options.offset,this.full-this.options.offset];this.drag=new Drag(this.knob,{snap:0,limit:B,modifiers:C,onDrag:this.draggedKnob.bind(this),onStart:this.draggedKnob.bind(this),onComplete:function(){this.draggedKnob();
this.end();}.bind(this)});if(this.options.snap){this.drag.options.grid=Math.ceil(this.stepWidth);this.drag.options.limit[this.axis][1]=this.full;}},set:function(A){if(!((this.range>0)^(A<this.min))){A=this.min;
}if(!((this.range>0)^(A>this.max))){A=this.max;}this.step=Math.round(A);this.checkStep();this.end();this.fireEvent("tick",this.toPosition(this.step));return this;
},clickedElement:function(C){var B=this.range<0?-1:1;var A=C.page[this.axis]-this.element.getPosition()[this.axis]-this.half;A=A.limit(-this.options.offset,this.full-this.options.offset);
this.step=Math.round(this.min+B*this.toStep(A));this.checkStep();this.end();this.fireEvent("tick",A);},scrolledElement:function(A){var B=(this.options.mode=="horizontal")?(A.wheel<0):(A.wheel>0);
this.set(B?this.step-this.stepSize:this.step+this.stepSize);A.stop();},draggedKnob:function(){var B=this.range<0?-1:1;var A=this.drag.value.now[this.axis];
A=A.limit(-this.options.offset,this.full-this.options.offset);this.step=Math.round(this.min+B*this.toStep(A));this.checkStep();},checkStep:function(){if(this.previousChange!=this.step){this.previousChange=this.step;
this.fireEvent("change",this.step);}},end:function(){if(this.previousEnd!==this.step){this.previousEnd=this.step;this.fireEvent("complete",this.step+"");
}},toStep:function(A){var B=(A+this.options.offset)*this.stepSize/this.full*this.steps;return this.options.steps?Math.round(B-=B%this.stepSize):B;},toPosition:function(A){return(this.full*Math.abs(this.min-A))/(this.steps*this.stepSize)-this.options.offset;
}});var Scroller=new Class({Implements:[Events,Options],options:{area:20,velocity:1,onChange:function(A,B){this.element.scrollTo(A,B);}},initialize:function(B,A){this.setOptions(A);
this.element=$(B);this.listener=($type(this.element)!="element")?$(this.element.getDocument().body):this.element;this.timer=null;this.coord=this.getCoords.bind(this);
},start:function(){this.listener.addEvent("mousemove",this.coord);},stop:function(){this.listener.removeEvent("mousemove",this.coord);this.timer=$clear(this.timer);
},getCoords:function(A){this.page=(this.listener.get("tag")=="body")?A.client:A.page;if(!this.timer){this.timer=this.scroll.periodical(50,this);}},scroll:function(){var B=this.element.getSize(),A=this.element.getScroll(),E=this.element.getPosition(),D={x:0,y:0};
for(var C in this.page){if(this.page[C]<(this.options.area+E[C])&&A[C]!=0){D[C]=(this.page[C]-this.options.area-E[C])*this.options.velocity;}else{if(this.page[C]+this.options.area>(B[C]+E[C])&&B[C]+B[C]!=A[C]){D[C]=(this.page[C]-B[C]+this.options.area-E[C])*this.options.velocity;
}}}if(D.y||D.x){this.fireEvent("change",[A.x+D.x,A.y+D.y]);}}});var Accordion=new Class({Extends:Fx.Elements,options:{display:0,show:false,height:true,width:false,opacity:true,fixedHeight:false,fixedWidth:false,wait:false,alwaysHide:false},initialize:function(){var C=Array.link(arguments,{container:Element.type,options:Object.type,togglers:$defined,elements:$defined});
this.parent(C.elements,C.options);this.togglers=$$(C.togglers);this.container=$(C.container);this.previous=-1;if(this.options.alwaysHide){this.options.wait=true;
}if($chk(this.options.show)){this.options.display=false;this.previous=this.options.show;}if(this.options.start){this.options.display=false;this.options.show=false;
}this.effects={};if(this.options.opacity){this.effects.opacity="fullOpacity";}if(this.options.width){this.effects.width=this.options.fixedWidth?"fullWidth":"offsetWidth";
}if(this.options.height){this.effects.height=this.options.fixedHeight?"fullHeight":"scrollHeight";}for(var B=0,A=this.togglers.length;B<A;B++){this.addSection(this.togglers[B],this.elements[B]);
}this.elements.each(function(E,D){if(this.options.show===D){this.fireEvent("active",[this.togglers[D],E]);}else{for(var F in this.effects){E.setStyle(F,0);
}}},this);if($chk(this.options.display)){this.display(this.options.display);}},addSection:function(E,C,G){E=$(E);C=$(C);var F=this.togglers.contains(E);
var B=this.togglers.length;this.togglers.include(E);this.elements.include(C);if(B&&(!F||G)){G=$pick(G,B-1);E.inject(this.togglers[G],"before");C.inject(E,"after");
}else{if(this.container&&!F){E.inject(this.container);C.inject(this.container);}}var A=this.togglers.indexOf(E);E.addEvent("click",this.display.bind(this,A));
if(this.options.height){C.setStyles({"padding-top":0,"border-top":"none","padding-bottom":0,"border-bottom":"none"});}if(this.options.width){C.setStyles({"padding-left":0,"border-left":"none","padding-right":0,"border-right":"none"});
}C.fullOpacity=1;if(this.options.fixedWidth){C.fullWidth=this.options.fixedWidth;}if(this.options.fixedHeight){C.fullHeight=this.options.fixedHeight;}C.setStyle("overflow","hidden");
if(!F){for(var D in this.effects){C.setStyle(D,0);}}return this;},display:function(A){A=($type(A)=="element")?this.elements.indexOf(A):A;if((this.timer&&this.options.wait)||(A===this.previous&&!this.options.alwaysHide)){return this;
}this.previous=A;var B={};this.elements.each(function(E,D){B[D]={};var C=(D!=A)||(this.options.alwaysHide&&(E.offsetHeight>0));this.fireEvent(C?"background":"active",[this.togglers[D],E]);
for(var F in this.effects){B[D][F]=C?0:E[this.effects[F]];}},this);return this.start(B);}});
	
	


/*
Script: dropMenu.js
	Drop menu going Nth levels

License:
	MIT-style license.

Author:
	Copyright (c) 2008 Chris Esler, <http://www.chrisesler.com/mootools>

*/
// Also known as IE fix
var TridentFix = new Class({
	tridentFix: function(item){
		item.addEvents({
			'mouseover':function(){
				this.addClass('iehover');
			},
			'mouseout':function(){
				this.removeClass('iehover');
			}
		});
	}
});


var DropMenu = new Class({
	Implements: [Options,TridentFix],
	/* 
		don't know about options yet
		but set it up anyways just in case 
	*/
	options: {
		mode: 'horizontal'
	},
	menu: null,
	initialize: function(menu,options){
		if(options) this.setOptions(options);
	
		this.menu = $(menu);
		
		// grab all of the menus children - LI's in this case
		var children = this.menu.getChildren();
		
		// loop through children
		children.each(function(item,index){
			// declare some variables 
			var fChild, list;
			
			/* 
				fChild = first child - which should be an A tag
				list = submenu UL
			*/
			fChild = item.getFirst();
			list = fChild.getNext('ul');
			
			// check if IE, if so apply fix
			if(Browser.Engine.trident) this.tridentFix(item);
			
			// if there is a sub menu UL
			if(list){
				item.mel = list; // pel = parent element
				list.pel = item; // mel = menu element
				new SubMenu(list); // hook up the subMenu
			}
		},this); // binding loop to this object for trident fix

	}	
});



var SubMenu = new Class({
	Implements: [Options,TridentFix],
	/* 
		don't know about options yet
		but set it up anyways just in case 
	*/
	options: {
		mode: 'vertical'
	},
	menu: null, // storage for menu object
	depth: 0, // storage for current menu depth
	initialize: function(el,depth,options){
		if(options) this.setOptions(options); // set options
		if(depth) this.depth = depth;// set depth
		
		this.menu = el; //attach menu to object
		
		if(this.depth == 0)	this.menu.addClass('submenu'); // class for first level
		if(this.depth >= 1)	this.menu.addClass('sub_submenu'); // class for deeper levels - in case :P
		
		this.menu.fade('hide'); // set menu to hid

		/*
			hook up menu's parent with event
			to trigger menu
		*/
		this.menu.pel.addEvents(this.parentEvents); 
		
		// get menu's child elements
		var children = this.menu.getChildren();
			
		// loop through children
		children.each(function(item,index){
			// declare some variables 
			var fChild, list;
			
			/* 
				fChild = first child - which should be an A tag
				list = submenu UL
			*/
			fChild = item.getFirst();
			list = fChild.getNext('ul');
			
			// check if IE, if so apply fix
			if(Browser.Engine.trident) this.tridentFix(item);
			
			// if the menu item has a sub_submenu
			if(list){
				/*
					create marker for menu item
					that has a sub_submenu
					this is to show persistence and 
					where you are in the menu tree
				*/
				var count = new Element('span').set('html','\&raquo;').addClass('counter');
				
				item.adopt(count); // stuff it inside li
				count.fade('hide'); // hide it

				item.mel = list; // mel = menu element
				item.count = count; // attach count accessor to menu item
				list.pel = item; // pel = parent element
				
				// create new subMenu with depth incremented
				new SubMenu(list,this.depth+1);
			}
		},this); //bound to this for trident fix
	},
	// menu parent mouse events
	parentEvents: {
		'mouseover': function(){
			/*
				if it has a count accesor
				then fade it in 
			*/
			if(this.count) this.count.fade('in');
			
			// fade in menu
			this.mel.fade('in');		
		},
		'mouseout': function(){
			/*
				if it has a count accesor
				then fade it out 
			*/
			if(this.count) this.count.fade('out');
			
			// fade out menu
			this.mel.fade('out');
		}
	}
});



/*
	Milkbox v2.2 - required: mootools.js v1.2.1 core + more: Assets
		
	by Luca Reghellin (http://www.reghellin.com) January 2009, MIT-style license.
	Inspiration Lokesh Dhakar (http://www.lokeshdhakar.com/projects/lightbox2/)
	AND OF COURSE, SPECIAL THANKS TO THE MOOTOOLS DEVELOPERS
*/

var Milkbox = new Class({

	Implements:[Options,Events],
	
	options:{//set all the options here
		overlayOpacity:0.7,
		topPosition:50,
		initialWidth:250,
		initialHeight:250,
		canvasBorderWidth:'0px',
		canvasBorderColor:'#000000',
		canvasPadding:'0px',
		resizeDuration:500,
		resizeTransition:'sine:in:out',/*function (ex. Transitions.Sine.easeIn) or string (ex. 'bounce:out')*/
		autoPlay:false,
		autoPlayDelay:7,
		removeTitle:false,
		onXmlGalleries:$empty,
		onClosed:$empty,
		onFileReady:$empty
	},
	
	initialize: function(options){
		
		this.setOptions(options);
		this.autoPlayBkup = { autoPlayDelay:this.options.autoPlayDelay, autoPlay:this.options.autoPlay };
		this.fullOptionsBkup = {};
		this.galleries = [];
		this.families = [];
		this.xmlFiles = [];
		this.loadedImages = [];//to check the preloaded images
		this.currentFile = null;
		this.currentIndex = null;
		this.currentGallery = null;
		this.currentRequest = null;
		this.currentResponse = null;
		
		this.mode = null;//'singleFile','fileGallery'
		this.closed = true;
		this.busy = true;//to control keyboard and autoplay events
		this.paused = true;
		this.fileReady = false;//to prevent overlapping loadFile calls via next_prev_aux()
		this.eventsok = false;
		this.first = true;//true if it's the first file since it opened 
		
		this.intObj = null;
		
		this.formtags = null;
		this.prepareGalleries();
		//if no galleries, stop here and prevent extra memory usage.
		//so you can keep milkbox in every page of a site.
		if(this.galleries.length == 0){ return; };
				
		this.initMilkbox();
		this.saveOptions();//then use restoreOptions()
	},//end init
	
	initMilkbox:function(){

		this.prepareHTML();
		this.prepareEffects();
		this.prepareEvents();
		
		this.formtags = $$('select','textarea');
		this.activated = true;
	},
	
	/* ****** SHOW/HIDE ****** */
	
	//runs only 1 time per gallery
	openMilkbox:function(gallery,index){

		this.closed = false;
		
		if(this.formtags.length != 0){ this.formtags.setStyle('display','none') };

		this.overlay.setStyles({ 'top': -$(window).getScroll().y,'height':$(window).getScrollSize().y+$(window).getScroll().y });
		this.center.setStyle('top',$(window).getScroll().y+this.options.topPosition);

		this.currentGallery = gallery;
		this.currentIndex = index;
		this.overlay.tween('opacity',this.options.overlayOpacity);//onComplete: center.tween opacity
		
		if(gallery.length == 1){
			this.mode = 'singleFile';
			this.loadFile(gallery[index],index);
		} else {
			this.mode = 'fileGallery';
			var playpauseWidth = 0;
			//interface
			$$(this.prev, this.next, this.count).setStyle('display','block');
			if(this.options.autoPlay){ 
				this.playpause.setStyle('display','block');
				var playpauseWidth = this.playpause.getSize().x;
			}
			var border = this.center.getStyle('border-right-width').toInt();//border-right is just ok for design purposes..
			var navWidth = this.prev.getSize().x+this.next.getSize().x+this.close.getSize().x+playpauseWidth+border;
			this.navigation.setStyle('width',navWidth);
			this.description.setStyle('margin-right',navWidth);
			//files
			var next = (index != gallery.length-1) ? gallery[index+1] : gallery[0];
			var prev = (index != 0) ? gallery[index-1] : gallery[gallery.length-1];
			var preloads = (prev == next) ? [prev] : [prev,next]; //if gallery.length == 2, then prev == next
						
			this.loadFile(gallery[index],preloads);
		}//end else
	},
	
	loadFile:function(fileObj,preloads){
		this.fileReady = false;
		var swf = this.checkFileType(fileObj,'swf');
		if(!swf){ 
			if(!this.loadedImages.contains(fileObj.retrieve('href'))){ this.center.addClass('mbLoading'); } 
			this.loadImage(fileObj.retrieve('href'));
		} else {
			this.loadSwf(fileObj);
		}
		
		if(preloads){ this.preloadFiles(preloads); }
	},
	
	preloadFiles:function(preloads){
		preloads.each(function(fileObj,index){
			var swf = this.checkFileType(fileObj.retrieve('href'),"swf");
			if(!swf){ this.preloadImage(fileObj.retrieve('href')); }
		},this);
	},
	
	loadImage:function(file){
		var imageAsset = new Asset.image(file, { onload:function(img){
			if(!this.loadedImages.contains(file)){ this.loadedImages.push(file); };//see next/prev events
			this.currentFile = img;
			this.loadAux(this.currentFile);
		}.bindWithEvent(this)});
	},
	
	preloadImage:function(file){
		if(!this.loadedImages.contains(file)){
			var imageAsset = new Asset.image(file, { onload:function(img){
					this.loadedImages.push(file);
			}.bindWithEvent(this)});
		}
	},
	

	loadSwf:function(swf){

		var swfObj = new Swiff(swf.retrieve('href'),{
			width:swf.retrieve('width').toInt(),
			height:swf.retrieve('height').toInt(),
			params:{ wMode:'opaque', swLiveConnect:'false', allowfullscreen:true }
		});
		
		this.currentFile = swfObj;
		this.loadAux(swf);
	},
	
	loadAux:function(file){
		this.fileReady = true; //the file is loaded and ready to be showed (see next_prev_aux())
		this.fireEvent('fileReady');
		$$(this.description,this.navigation).setStyle('visibility','hidden');
		this.navigation.setStyle('height','');//reset the height setted in center.morph.onComplete
		$$(this.next,this.prev,this.close).setStyle('backgroundPosition','0 0');
		this.showFile(file);
	},
	
	
	showFile:function(file){
 		
 		if(this.closed){ return; };//if you close the Milkbox and an onload event is still running
 		
 		var fileSize = new Hash();
 		var targetSize = {};
 		var b = null;
 		var p = null;
 		if(this.options.canvasBorderWidth.toInt() != 0 && this.canvas.getStyle('borderWidth').toInt() == 0){
 			b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
 			this.canvas.setStyle('border',b);
 		}
 		
 		if(this.options.canvasPadding.toInt() != 0 && this.canvas.getStyle('padding').toInt() == 0){
 			p = this.options.canvasPadding;
 			this.canvas.setStyle('padding',p);
 		}
 		
 		var canvasSize = this.canvas.getSize();
 		var canvasAddSize = this.canvas.getStyle('borderWidth').toInt()*2 + this.canvas.getStyle('padding').toInt()*2;
 		this.canvas.setStyles({'opacity':0, 'width':'', 'height':''});
 		
 		if(!file.retrieve('width')){//is an image file
 			fileSize = fileSize.extend(file.getProperties('width','height')).map(function(item, index){ return item.toInt(); });
 		} else {//is an swf file
 			fileSize.extend({ 'height':file.retrieve('height').toInt(), 'width':file.retrieve('width').toInt() });
 		}

 		var centerSize = new Hash(this.center.getStyles('width','height')).map(function(item, index){ return item.toInt(); });

 		if(fileSize.width != centerSize.width){ 
 			targetSize.width = fileSize.width + canvasAddSize;
 			targetSize.marginLeft = -(targetSize.width/2).round();
 		}
 		 		
 		var gap = (canvasSize.y-canvasAddSize > 0) ? centerSize.height - canvasSize.y : 0; 

 	   targetSize.height = fileSize.height + canvasAddSize + gap;
 	   
		//so nav doesn't move when you click next/prev
		this.canvas.setStyles({'width':fileSize.width, 'height':fileSize.height});

 		this.center.removeClass('mbLoading');
 		
 		var d = 0;
 		if(this.first){ d = 500; this.first = false; }
 		(function(){ this.center.morph(targetSize); }).delay(d,this)//onComplete: show all items
	},

	
	//{ gallery:'gall1', index:2, autoplay:true, delay:7 }
	showGallery:function(opt){
		if(!opt || !opt.gallery){ return; }
		var fileIndex = ($chk(opt.index)) ? opt.index : 0;
		var g = this.getGallery(opt.gallery);
		var auto = false;
		var d;
		if(opt.autoplay || (g['options'] && g['options'].autoplay)){ auto = true; }
		if(g != -1 && !this.opened){
			if(auto){
				d = (opt && opt.delay) ? opt.delay : (g['options'] && g['options'].delay) ? g['options'].delay : this.autoPlayDelay;
				this.startAutoPlay({ gallery:g, index:fileIndex, delay:d });
			} else {
				this.openMilkbox(g,fileIndex);
			}
		}
	},
	
	/* ******* XML/AJAX ******* */

	addGalleries:function(xmlfile){
		this.currentRequest = new Request({
			method:'get',
			autoCancel:true,
			url:xmlfile,
			onRequest:function(){
				//placeholder
			}.bindWithEvent(this),
			onSuccess:function(text,xml){
				var t = text.replace(/(<a.+)\/>/gi,"$1></a>");
				this.setGalleries(new Element('div',{ html:t }),xmlfile);
			}.bindWithEvent(this),
			onFailure:function(transport){ alert('Milkbox :: addGalleries: XML file path error or local test'); }
		});
		
		this.currentRequest.send();
	},
	
	setGalleries:function(container,xmlfile){
		//controllare che non ci sia già
		if(!this.xmlFiles.contains(xmlfile)){ this.xmlFiles.push(xmlfile); }
		var c = container;
		var galleries = c.getElements('.gallery');
		var links = [];
		var aplist = [];
		galleries.each(function(gallery,i){
						
			var obj = { 
				gallery:gallery.getProperty('name'), 
				autoplay:Boolean(gallery.getProperty('autoplay')),
				delay:Number(gallery.getProperty('delay'))
			}
			
			var l = gallery.getChildren('a');
			var lx = l.map(function(link){ return link.setProperty('rel','milkbox['+obj.gallery+']'); });
			links.push(lx);
			if(obj.autoplay){ aplist.push(obj); }
		});
		
		this.prepareGalleries(links.flatten());
		this.setAutoPlay(aplist);
		
		if(!this.activated){ this.initMilkbox(); }
		
		this.fireEvent('xmlGalleries');
	},
	
	
	
	/* ****** UTILS ****** */
	
	checkFileType:function(file,type){
		var href = null;
		if($type(file) != 'string'){ href = file.retrieve('href'); } 
		else{ href = file; }
		var regexp = new RegExp("\.("+type+")$","i");
		return href.split('?')[0].test(regexp);
	},
	
	getGallery:function(gallery){
		var f = null;
		if(gallery.test(/^milkbox/i)){
			f = this.families;
		} else {
			f = this.families.map(function(item){
				var cleaned = item.trim();
				return cleaned.slice(0,cleaned.length-1).substr(8);
			});
		}
		var i = f.indexOf(gallery);
		var g = (i != -1) ? this.galleries[i] : i;
		return g;
	},
	
	setFileProps:function(fileObj,propString){
		var s = propString.split(',');
		s.each(function(p,i){
			var clean = p.trim().split(':');
			fileObj.store(clean[0].trim(),clean[1].trim())
		},this);
	},
	
	changeOptions:function(obj){
		if(!obj){ return; }
		this.setOptions(obj);
 		this.center.get('morph').setOptions({ transition:this.options.resizeTransition,  duration:this.options.resizeDuration });
	},
	
	saveOptions:function(obj){
		if($chk(obj)){
			this.fullOptionsBkup = obj;
		} else {
			this.fullOptionsBkup = this.options;
		}
	},
	
	restoreOptions:function(){
		this.setOptions(this.fullOptionsBkup);
 		b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
 		this.canvas.setStyles({ 'border':b, 'padding':this.options.canvasPadding});
 		this.center.get('morph').setOptions({ transition:this.options.resizeTransition,  duration:this.options.resizeDuration });
	},
	
	reloadGalleries:function(){
		this.galleries = [];
		this.families = [];
		//re-check for tags
		this.formtags = $$('select','textarea');
		
		//reload standard galleries
		this.prepareGalleries();		
		this.setGalleriesEvents();
		
		if(this.xmlFiles.length == 0){ return; }
		//reload xmlGalleries
		this.xmlFiles.each(function(xmlfile,index){
			this.addGalleries(xmlfile);
		}.bind(this));
	},
	
	/* ****** AUTOPLAY ****** */
	
	//list:Array of objects or an object > [ { gallery:'gall1', autoplay:true, delay:6 } ]
	//to permanently define autoplay options for any gallery 
	setAutoPlay:function(list){
		var l = ($type(list) == 'object') ? [list] : list;
		l.each(function(item){
			var g = this.getGallery(item.gallery);
			if(g == -1){ return; }
			var a = (item.autoplay == true) ? item.autoplay : false;
			var d = ($chk(item.delay) && a) ? item.delay : this.options.autoPlayDelay;
			g['options'] = { autoplay:a, delay:d }
		},this);
	},
	
	startAutoPlay:function(opt){//opt: gallery, index, delay (in seconds)
		
		var g = -1;
		var i,d;
		if(opt && opt.gallery){
			if($type(opt.gallery) == 'array'){ g = opt.gallery }
			else if($type(opt.gallery) == 'string'){ 
				g = this.getGallery(opt.gallery);
			}
		}
		
		if(g == -1){ g = this.galleries[0]; }
		
		d = (opt && opt.delay && ($type(opt.delay) == 'number')) ? opt.delay*1000 : (g['options'] && g['options'].delay) ? g['options'].delay*1000 : this.options.autoPlayDelay*1000;
		i = (opt && opt.index && ($type(opt.index) == 'number')) ? opt.index : 0;
		if(d < this.options.resizeDuration*2){ d = this.options.resizeDuration*2 };
		this.options.autoPlayDelay = d/1000;//save autoPlayDelay because now it is customized
		
		if(!this.options.autoPlay){ this.setOptions({ autoPlay:true, autoPlayDelay:this.options.autoPlayDelay }); }
		
		if(this.closed){ 
			this.openMilkbox(g,i); 
			if(this.mode != 'fileGallery'){ return; }
			this.addEvent('fileReady',function(){
				//wait until the first file is loaded
				this.intObj = this.next_prev_aux.periodical(d,this,[null,'next']);
				this.removeEvents('fileReady');
			}.bindWithEvent(this));
		} else {
			if(!this.closed){ this.next_prev_aux(null,'next'); }
			this.intObj = this.next_prev_aux.periodical(d,this,[null,'next']);
		}

		this.paused = false;
	},
	
	stopAutoPlay:function(){
		if(this.intObj){ $clear(this.intObj); this.intObj = null; }
		this.playpause.setStyle('backgroundPosition','0 -44px');
		this.paused = true;
	},
	
	
	/* ****** INIT/CLOSE ****** */
	
	setGalleriesEvents:function(){
		this.galleries.each(function(gallery){
		
			$$(gallery).addEvent('click',function(e){
				var button=($(e.target).match('a')) ? $(e.target) : $(e.target).getParent('a');
				e.preventDefault();
				
				var g = this.getGallery(button.rel);
				if(g.options && g.options.autoplay){
					this.setOptions({ autoPlay:g.options.autoplay, autoPlayDelay:g.options.delay });
				}

				if(this.options.autoPlay){
					this.startAutoPlay({ gallery:gallery, index:gallery.indexOf(button) });
				} else { 
					this.openMilkbox(gallery, gallery.indexOf(button)); 
				}
				
			}.bindWithEvent(this));
		},this);
	},
	
	//all the main events
	prepareEvents:function(xml){
	
		//galleries
		this.setGalleriesEvents();
		
		//next, prev, see next_prev_aux()
		this.next.addEvent('click',this.next_prev_aux.bindWithEvent(this,'next'));
		this.prev.addEvent('click',this.next_prev_aux.bindWithEvent(this,'prev'));
		
		
		//css hover doesn't work in ie6, so I must do it via js...
		$$(this.next,this.prev,this.close).addEvents({
			'mouseover':function(){ this.setStyle('backgroundPosition','0 -22px'); },
			'mouseout':function(){ this.setStyle('backgroundPosition','0 0'); }
		});

		//keyboard next/prev/close
		$(window.document).addEvent('keydown',function(e){
			if(this.mode != 'fileGallery' || this.busy == true){ return; }
			if(e.key == 'right' || e.key == 'space'){ this.next_prev_aux(e,'next'); }
			else if(e.key == 'left'){ this.next_prev_aux(e,'prev'); }
			else if(e.key == 'esc'){ this.closeMilkbox(); }
		}.bindWithEvent(this));
		
		//playpause for autoPlay
		this.playpause.addEvents({
				'mouseover':function(e){ 
					if(this.paused == false){ this.playpause.setStyle('backgroundPosition','0 -22px'); } 
					else { this.playpause.setStyle('backgroundPosition','0 -66px'); }
				}.bindWithEvent(this),
				'mouseout':function(){ 
					if(this.paused == false){ this.playpause.setStyle('backgroundPosition','0 0'); } 
					else { this.playpause.setStyle('backgroundPosition','0 -44px'); }
				}.bindWithEvent(this),
				'click':function(){
					if(this.paused == false){ 
						this.stopAutoPlay();
						this.paused = true;
						this.playpause.setStyle('backgroundPosition','0 -66px');
					} else {
						var d = (this.currentGallery.options && this.currentGallery.options.delay) ? this.currentGallery.options.delay : this.options.autoPlayDelay;
						this.startAutoPlay({gallery:this.currentGallery, index:this.currentIndex+1, delay:d });
						this.paused = false;
						this.playpause.setStyle('backgroundPosition','0 0');
					}
				}.bindWithEvent(this)
		});
		
		//overlay
		this.overlay.get('tween').addEvent('onComplete',function(){
			if(this.overlay.getStyle('opacity') == this.options.overlayOpacity){ 
				this.center.tween('opacity',1);
			} else if(this.overlay.getStyle('opacity') == 0) {
				this.overlay.setStyles({'height':0,'top':''});
			};
		}.bindWithEvent(this));
		
		//center
		this.center.get('morph').addEvent('onComplete',function(){
			
			 if($type(this.currentFile) == "element"){//is image file
				this.canvas.grab(this.currentFile);
			 } else {//object: is swf file
			 	(function(){ this.canvas.grab(this.currentFile); }).delay(500,this);
			 }
 			 
			 this.canvas.tween('opacity',1);
			 			 
			 var d = (!(this.mode == 'showThisImage')) ? this.currentGallery[this.currentIndex].retrieve('title') : this.specialDescription;
			 if($chk(d)){ this.description.innerHTML = d; };
			 
			 if(this.mode == 'fileGallery'){ 
			 	this.count.appendText((this.currentIndex+1)+' of '+this.currentGallery.length); 
			 }
			 
			 var currentCenterHeight = this.center.getStyle('height').toInt();
			 
			 this.navigation.setStyle('height',this.bottom.getStyle('height').toInt());//to have the right-border height == total bottom height
			 var bottomSize = this.bottom.getSize().y;
			 
			 //after the 1st time, currentCenterHeight is always > this.canvas.getSize().y
			 var targetOffset = (currentCenterHeight > this.canvas.getSize().y) ? (this.bottom.getSize().y+this.canvas.getSize().y)-currentCenterHeight : bottomSize;
				
			 this.bottom.setStyle('display','none');//to avoid rendering problems during setFinalHeight

			 this.center.retrieve('setFinalHeight').start(currentCenterHeight,currentCenterHeight+targetOffset);
			/**/
		}.bindWithEvent(this));
		
		this.center.retrieve('setFinalHeight').addEvent('onComplete',function(){
			this.bottom.setStyles({'visibility':'visible','display':'block'});
			$$(this.description,this.navigation).setStyle('visibility','visible');
			//reset overlay height based on position and height
			var scrollSize = $(window).getScrollSize().y;
			var scrollTop = $(window).getScroll().y;
			
			this.overlay.setStyles({'height':scrollSize+scrollTop, 'top':-scrollTop });
			this.busy = false;
		}.bindWithEvent(this));
		
		//reset overlay height and position onResize
		window.addEvent('resize',function(){
			if(this.overlay.getStyle('opacity') == 0){ return; };//resize only if visible
			var scrollSize = $(window).getScrollSize().y;
			var scrollTop = $(window).getScroll().y;
			this.overlay.setStyles({ 'height':scrollSize+scrollTop,'top':-scrollTop });
		}.bindWithEvent(this));

		//close
		$$(this.overlay,this.close).addEvent('click',function(){ this.closeMilkbox(); }.bindWithEvent(this));
		
		//check
		this.eventsok = true;
	},
	
	next_prev_aux:function(e,direction){
		
		if(e){ 
			e.preventDefault();
			this.stopAutoPlay();
		} else { 
			//if there's no event obj, than this is called by autoPlay()
			if(this.busy || !this.fileReady){ return; }//stop autoplay()
		}

		this.busy = true; //for keyboard and autoplay
		
		var backupIndex = this.currentIndex;
		
		if(direction == "next"){
			var i= (this.currentIndex != this.currentGallery.length-1) ? this.currentIndex += 1 : this.currentIndex = 0;
			var _i= (this.currentIndex != this.currentGallery.length-1) ? this.currentIndex + 1 : 0;
		} else {
			var i= (this.currentIndex != 0) ? this.currentIndex -= 1 : this.currentIndex = this.currentGallery.length-1;
			var _i= (this.currentIndex != 0) ? this.currentIndex - 1 : this.currentGallery.length-1;		
		};
		
		this.canvas.empty();
		this.description.empty();
		this.count.empty();

		this.loadFile(this.currentGallery[i],[this.currentGallery[_i]]);
	},
	
	prepareEffects:function(){
		this.overlay.set('tween',{ duration:'short',link:'cancel' });
		this.center.set('tween',{ duration:'short',link:'chain' });
		this.center.set('morph',{ duration:this.options.resizeDuration,link:'chain',transition:this.options.resizeTransition });
		this.center.store('setFinalHeight',new Fx.Tween(this.center,{property:'height',duration:'short'}));
		this.canvas.set('tween',{ link:'chain' });
	},
	
	prepareGalleries:function(responseElements){
		var milkbox_a = [];
		var gIndex;
		var a_tags = (responseElements) ? responseElements : $$('a');
				
		a_tags.each(function(a){
			//test 'milkbox' and link extension, and collect all milkbox links
			if(a.rel && a.rel.test(/^milkbox/i) && a.href.split('?')[0].test(/\.(gif|jpg|png|swf)$/i)){
				if(a.rel.length>7 && !this.families.contains(a.rel)){ this.families.push(a.rel); };
				milkbox_a.push(a);
			}
		},this);

		//create an array of arrays with all galleries
		milkbox_a.each(function(a){
			$(a).store('href',a.href);
			$(a).store('rel',a.rel);
			$(a).store('title',a.title);
			if(this.checkFileType(a.href,"swf")){ this.setFileProps($(a),a.rev); }

			if(this.options.removeTitle){ $(a).removeProperty('title'); }
			if(a.rel.length > 7){
				this.families.each(function(f,i){
					if(a.rel == f){
						var gMounted = false;
						var index;
						this.galleries.each(function(g,k){
							if(g[0].rel == f){ 
								gMounted = true;
								index = k;
								return;
							}
						});
						
						if(gMounted == true){ this.galleries[index].push($(a)); } 
						else { this.galleries.push([$(a)]); }
					};
				},this);
			} else { this.galleries.push([$(a)]); };
		},this);
		
		//console.log(this.galleries);
	},
		
	prepareHTML:function(){		
		
		this.overlay = new Element('div', { 'id':'mbOverlay','styles':{ 'opacity':0,'visibility':'visible','height':0,'overflow':'hidden' }}).inject($(document.body));
		
		this.center = new Element('div', {'id':'mbCenter', 'styles':{'width':this.options.initialWidth,'height':this.options.initialHeight,'marginLeft':-(this.options.initialWidth/2),'opacity':0 }}).inject($(document.body));
		this.canvas = new Element('div', {'id':'mbCanvas'}).inject(this.center);
		
		this.bottom = new Element('div',{'id':'mbBottom'}).inject(this.center).setStyle('visibility','hidden');
		this.navigation = new Element('div',{'id':'mbNavigation'}).setStyle('visibility','hidden');
		this.description = new Element('div',{'id':'mbDescription'}).setStyle('visibility','hidden');

		this.bottom.adopt(this.navigation, this.description, new Element('div',{'class':'clear'}));
		
		this.close = new Element('a',{'id':'mbCloseLink'});
		this.next = new Element('a',{'id':'mbNextLink'});
		this.prev = new Element('a',{'id':'mbPrevLink'});
		this.playpause = new Element('a',{'id':'mbPlayPause'});
		this.count = new Element('span',{'id':'mbCount'});
		
		$$(this.next, this.prev, this.count, this.playpause).setStyle('display','none');
		
		this.navigation.adopt(this.close, this.next, this.prev, this.playpause, new Element('div',{'class':'clear'}), this.count);
	},
	
	closeMilkbox:function(){
		this.cancelAllEffects();
		this.stopAutoPlay();
		this.setOptions(this.autoPlayBkup);

		this.currentFile = null;
		this.currentIndex = null;
		this.currentGallery = null;
		this.currentRequest = null;
		this.currentResponse = null;
 		
		$$(this.prev, this.next, this.playpause, this.count).setStyle('display','none');
		this.playpause.setStyle('backgroundPosition','0 0');
		var border = this.center.getStyle('border-right-width').toInt();
		var navWidth = this.close.getSize().x+border;
		this.navigation.setStyles({'width':navWidth,'height':'','visibility':'hidden'});
		this.description.setStyle('margin-right',navWidth);
		this.description.empty();
		this.bottom.setStyles({'visibility':'hidden','display':''});
		
   	this.canvas.setStyles({'opacity':0, 'width':'', 'height':''});
 		this.canvas.empty();
 		
 		this.count.empty();
		
		this.center.setStyles({'opacity':0,'width':this.options.initialWidth,'height':this.options.initialHeight,'marginLeft':-(this.options.initialWidth/2)});
		this.overlay.tween('opacity',0);//see onComplete in prepareEvents() 
		
		if(this.formtags.length != 0){ this.formtags.setStyle('display','') };
		
		this.mode = null;
		this.closed = true;
		this.first = true;
		this.fileReady = false;
		this.fireEvent('closed');
	},
	
	cancelAllEffects:function(){
		this.overlay.get('tween').cancel();
		this.center.get('morph').cancel();
		this.center.get('tween').cancel();
		this.center.retrieve('setFinalHeight').cancel();
		this.canvas.get('tween').cancel();
	}
	
});//END MILKBOX;




/*
	PopupBox.open(<id>, <options>);
	
	Example: PopupBox.open( "message", {width: 400} );
*/

var PopupBox = new Class(
{

	Implements:Options,
	
	options:	{//set all the options here
		overlayOpacity:0.5,
		popupWidth: 800,
		popupMinWidth: 200,
		popupMinHeight: 100,
		popupMaxWidth: 900,
		popupMaxHeight: 600,
		initialWidth:250,
		initialHeight:250
	},

	initialize: function(options)
	{
		this.prepareHTML();
		this.prepareEvents();
	},

	open:function( obj_id, options )
	{
		var obj = $(obj_id);
		if (!options) options = [];
		obj.options = this.options;

		this.overlay.setStyles({height: window.getScrollHeight()});
		this.overlay.setStyles({opacity: this.options.overlayOpacity});
		this.popup_content.set ('html', obj.innerHTML);
		this.popup_box.setStyles({display: "", width: this.options.popupWidth});
		if (options.width) this.popup_box.setStyles({width: options.width});
		if (options.height) this.popup_box.setStyles({height: options.height});

		var size = this.popup_box.getSize();

		if (size.x > obj.options.popupMaxWidth) this.popup_box.setStyles({width: obj.options.popupMaxWidth});
		if (size.x < obj.options.popupMinWidth) this.popup_box.setStyles({width: obj.options.popupMinWidth});

		if (size.y > obj.options.popupMaxHeight) this.popup_box.setStyles({height: obj.options.popupMaxHeight});
		if (size.y < obj.options.popupMinHeight) this.popup_box.setStyles({height: obj.options.popupMinHeight});

		size = this.popup_box.getSize();

		this.popup_box.setStyles({
			left: (window.getWidth() - size.x)/2,
			top: window.getScrollHeight() - window.getHeight() + (window.getHeight() - size.y)/2
		});
	},

	close:function()
	{
		this.overlay.setStyles({opacity: 0});
		this.overlay.setStyles({height:'', top:''});
		this.popup_box.setStyles({display: "none"});
	},

	prepareHTML:function()
	{
		this.overlay = new Element('div', { 'id':'overlay','styles':{ 'opacity':'0','visibility':'visible' }}).inject($(document.body));
		this.popup_box = new Element('div', { 'id':'popup_box', 'styles':{ 'display':'none' }}).inject($(document.body));
		this.popup_titlebar = new Element('div', { 'id':'popup_titlebar' }).inject(this.popup_box);
		this.popup_caption = new Element('div', { 'id':'popup_caption' }).inject(this.popup_titlebar);
		this.popup_close = new Element('a', { 'id':'popup_close' }).inject(this.popup_titlebar);
		this.popup_close.set ('html', 'Close' );
		this.popup_content = new Element('div', { 'id':'popup_content' }).inject(this.popup_box);
	},

	prepareEvents:function()
	{
		//reset overlay height and position onResize
		window.addEvent('resize',function()
		{
			if(this.overlay.getStyle('opacity') == 0){ return; };//resize only if visible
			this.overlay.setStyles({height: window.getScrollHeight()});
		}.bindWithEvent(this));
		
		//close
		$$(this.overlay, this.popup_close).addEvent('click',function(){ this.close(); return false; }.bindWithEvent(this));
	}

});//END PopupBox;


/*
	mediaboxAdvanced v0.9.9d - The ultimate extension of Mediabox into an all-media script
	updated 2009.03.28
	(c) 2007-2009 John Einselen <http://iaian7.com>
		based on
	Slimbox v1.64 - The ultimate lightweight Lightbox clone
	(c) 2007-2008 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/

var Mediabox;

(function() {

	// Global variables, accessible to Mediabox only
	var state = 0, options, images, activeImage, prevImage, nextImage, top, fx, preload, preloadPrev = new Image(), preloadNext = new Image(),	// State values: 0 (closed or closing), 1 (open and ready), 2+ (open and busy with animation)
	// DOM elements
	overlay, center, image, bottomContainer, bottom, captionSplit, title, caption, prevLink, number, nextLink,
	// Mediabox specific vars
	URL, WH, WHL, elrel, mediaWidth, mediaHeight, mediaType = "none", mediaSplit, mediaId = "mediaBox", mediaFmt;

	/*
		Initialization
	*/

	window.addEvent("domready", function() {
		// Create and append the Mediabox HTML code at the bottom of the document
		$(document.body).adopt(
			$$([
				overlay = new Element("div", {id: "mbOverlay"}).addEvent("click", close),
				center = new Element("div", {id: "mbCenter"}),
				bottomContainer = new Element("div", {id: "mbBottomContainer"})
			]).setStyle("display", "none")
		);

		image = new Element("div", {id: "mbImage"}).injectInside(center);
		bottom = new Element("div", {id: "mbBottom"}).injectInside(bottomContainer).adopt(
			new Element("a", {id: "mbCloseLink", href: "#"}).addEvent("click", close),
			nextLink = new Element("a", {id: "mbNextLink", href: "#"}).addEvent("click", next),
			prevLink = new Element("a", {id: "mbPrevLink", href: "#"}).addEvent("click", previous),
			title = new Element("div", {id: "mbTitle"}),
			number = new Element("div", {id: "mbNumber"}),
			caption = new Element("div", {id: "mbCaption"}),
			new Element("div", {styles: {clear: "both"}})
		);

		fx = {
			overlay: new Fx.Tween(overlay, {property: "opacity", duration: 360}).set(0),
			image: new Fx.Tween(image, {property: "opacity", duration: 360, onComplete: nextEffect}),
			bottom: new Fx.Tween(bottom, {property: "margin-top", duration: 240})
		};
	});

	/*
		API
	*/

	Mediabox = {
		close: function(){ 
			close();	// Thanks to Yosha on the google group for fixing the close function API!
		}, 

		open: function(_images, startImage, _options) {
			options = $extend({
				loop: false,					// Allows to navigate between first and last images
				stopKey: true,					// Prevents default keyboard action (such as up/down arrows), in lieu of the shortcuts
													// Does not apply to iFrame content
													// Does not affect mouse scrolling
				overlayOpacity: 0.7,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
													// Remember that Firefox 2 and Camino 1.6 on the Mac require a background .png set in the CSS
				resizeDuration: 240,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// Default transition in mootools
				initialWidth: 360,				// Initial width of the box (in pixels)
				initialHeight: 240,				// Initial height of the box (in pixels)
				showCaption: true,				// Display the title and caption, true / false
				animateCaption: true,			// Animate the caption, true / false
				showCounter: true,				// If true, a counter will only be shown if there is more than 1 image to display
				counterText: '  ({x} of {y})',	// Translate or change as you wish
//			Global media options
				scriptaccess: 'true',		// Allow script access to flash files
				fullscreen: 'true',			// Use fullscreen
				fullscreenNum: '1',			// 1 = true
				autoplay: 'true',			// Plays the video as soon as it's opened
				autoplayNum: '1',			// 1 = true
				autoplayYes: 'yes',			// yes = true
				bgcolor: '#000000',			// Background color, used for both flash and QT media
//			JW Media Player settings and options
				playerpath: '../js/player.swf',	// Path to the mediaplayer.swf or flvplayer.swf file
				backcolor:  '000000',		// Base color for the controller, color name / hex value (0x000000)
				frontcolor: '999999',		// Text and button color for the controller, color name / hex value (0x000000)
				lightcolor: '000000',		// Rollover color for the controller, color name / hex value (0x000000)
				screencolor: '000000',		// Rollover color for the controller, color name / hex value (0x000000)
				controlbar: 'over',			// bottom, over, none (this setting is ignored when playing audio files)
//			NonverBlaster
				useNB: true,				// use NonverBlaster in place of the JW Media Player for .flv and .mp4 files
				NBpath: '../js/NonverBlaster.swf',	// Path to NonverBlaster.swf
				NBloop: 'true',				// Loop video playback, true / false
				controllerColor: '0x777777',	// set the controlbar colour
				showTimecode: 'false',		// turn timecode display off or on
//			Quicktime options
				controller: 'true',			// Show controller, true / false
//			Flickr options
				flInfo: 'true',				// Show title and info at video start
//			Revver options
				revverID: '187866',			// Revver affiliate ID, required for ad revinue sharing
				revverFullscreen: 'true',	// Fullscreen option
				revverBack: '000000',		// Background colour
				revverFront: 'ffffff',		// Foreground colour
				revverGrad: '000000',		// Gradation colour
//			Youtube options
				ytColor1: '000000',			// Outline colour
				ytColor2: '333333',			// Base interface colour (highlight colours stay consistent)
				ytQuality: '&ap=%2526fmt%3D18',	// Empty for standard quality, use '&ap=%2526fmt%3D18' for high quality, and '&ap=%2526fmt%3D22' for HD (note that not all videos are availible in high quality, and very few in HD)
//			Vimeo options
				vdPlayer: 'false',			// Use simple (smaller) player (22px less)
//			Vimeo options
				vmTitle: '1',				// Show video title
				vmByline: '1',				// Show byline
				vmPortrait: '1',			// Show author portrait
				vmColor: 'ffffff'			// Custom controller colours, hex value minus the # sign, defult is 5ca0b5
			}, _options || {});

			if (typeof _images == "string") {	// The function is called for a single image, with URL and Title as first two arguments
				_images = [[_images,startImage,_options]];
				startImage = 0;
			}

// Fixes Firefox 2 and Camino 1.6 incompatibility with opacity + flash
if ((Browser.Engine.gecko) && (Browser.Engine.version<19)) {
	options.overlayOpacity = 1;
	overlay.className = 'mbOverlayFF';
}

			images = _images;
			options.loop = options.loop && (images.length > 1);
			position();
			setup(true);
			top = window.getScrollTop() + (window.getHeight() / 15);
			fx.resize = new Fx.Morph(center, $extend({duration: options.resizeDuration, onComplete: nextEffect}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			center.setStyles({top: top, width: options.initialWidth, height: options.initialHeight, marginLeft: -(options.initialWidth/2), display: ""});
			fx.overlay.start(options.overlayOpacity);
			state = 1;
			return changeImage(startImage);
		}
	};

	Element.implement({
		mediabox: function(_options, linkMapper) {
			$$(this).mediabox(_options, linkMapper);	// The processing of a single element is similar to the processing of a collection with a single element

			return this;
		}
	});

	Elements.implement({
		/*
			options:	Optional options object, see Mediabox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 3 elements:
					the image URL and the image caption (may contain HTML)
			linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
					the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
					This function must always return true when the DOM element argument is "this".
		*/
		mediabox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				elrel = el.rel.split(/[\[\]]/);
				elrel = elrel[1];
				return [el.href, el.title, elrel];
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;

			links.removeEvents("click").addEvent("click", function() {
				// Build the list of images that will be displayed
				var filteredArray = links.filter(linksFilter, this);
				var filteredLinks = [];
				var filteredHrefs = [];

				filteredArray.each(function(item, index){
					if(filteredHrefs.indexOf(item.toString()) < 0) {
						filteredLinks.include(filteredArray[index]);
						filteredHrefs.include(filteredArray[index].toString());
					};
				});

				return Mediabox.open(filteredLinks.map(linkMapper), filteredHrefs.indexOf(this.toString()), _options);
			});

			return links;
		}
	});

	/*
		Internal functions
	*/

	function position() {
		overlay.setStyles({top: window.getScrollTop(), height: window.getHeight()});
	}

	function setup(open) {
		// Hides on-page objects and embeds while the overlay is open to counteract Firefox stupidity
		["object", window.ie ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._mediabox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._mediabox;
			});
		});

		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		window[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		switch(event.code) {
			case 27:	// Esc
			case 88:	// 'x'
			case 67:	// 'c'
				close();
				break;
			case 37:	// Left arrow
			case 80:	// 'p'
				previous();
				break;	
			case 39:	// Right arrow
			case 78:	// 'n'
				next();
		}
		if (options.stopKey) { return false; };
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if ((state == 1) && (imageIndex >= 0)) {
			state = 2;
			image.set('html', '');
			activeImage = imageIndex;
			prevImage = ((activeImage || !options.loop) ? activeImage : images.length) - 1;
			nextImage = activeImage + 1;
			if (nextImage == images.length) nextImage = options.loop ? 0 : -1;

			$$(prevLink, nextLink, image, bottomContainer).setStyle("display", "none");
			fx.bottom.cancel().set(0);
			fx.image.set(0);
			center.className = "mbLoading";

// MEDIABOX FORMATING
			WH = images[imageIndex][2].split(' ');
			WHL = WH.length;
			if (WHL>1) {
				mediaWidth = (WH[WHL-2].match("%")) ? (window.getWidth()*("0."+(WH[WHL-2].replace("%", ""))))+"px" : WH[WHL-2]+"px";
				mediaHeight = (WH[WHL-1].match("%")) ? (window.getHeight()*("0."+(WH[WHL-1].replace("%", ""))))+"px" : WH[WHL-1]+"px";
			} else {
				mediaWidth = "";
				mediaHeight = "";
			}
			URL = images[imageIndex][0];
			captionSplit = images[activeImage][1].split('::');
// Quietube support
			if (URL.match(/quietube\.com/i)) {
				mediaSplit = URL.split('v.php/');
				URL = mediaSplit[1];
			}
// MEDIA TYPES
// IMAGES
			if (URL.match(/\.gif|\.jpg|\.png/i)) {
				mediaType = 'img';
				preload = new Image();
				preload.onload = nextEffect;
				preload.src = images[imageIndex][0];
// FLV, MP4
			} else if (URL.match(/\.flv|\.mp4/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || options.initialWidth;
				mediaHeight = mediaHeight || options.initialHeight;
				if (options.useNB) {
				preload = new Swiff(''+options.NBpath+'?videoURL='+URL+'&allowSmoothing=true&autoPlay='+options.autoplay+'&buffer=6&showTimecode='+options.showTimecode+'&loop='+options.NBloop+'&controlColour='+options.controllerColor+'&scaleIfFullScreen=true&showScalingButton=false', {
					id: 'MediaboxSWF',
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				} else {
				preload = new Swiff(''+options.playerpath+'?file='+URL+'&backcolor='+options.backcolor+'&frontcolor='+options.frontcolor+'&lightcolor='+options.lightcolor+'&screencolor='+options.screencolor+'&autostart='+options.autoplay+'&controlbar='+options.controlbar, {
					id: 'MediaboxSWF',
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				}
				nextEffect();
// MP3, AAC
			} else if (URL.match(/\.mp3|\.aac/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || options.initialWidth;
				mediaHeight = mediaHeight || options.initialHeight;
				preload = new Swiff(''+options.playerpath+'?file='+URL+'&backcolor='+options.backcolor+'&frontcolor='+options.frontcolor+'&lightcolor='+options.lightcolor+'&screencolor='+options.screencolor+'&autostart='+options.autoplay, {
					id: 'MediaboxSWF',
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// SWF
			} else if (URL.match(/\.swf/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || options.initialWidth;
				mediaHeight = mediaHeight || options.initialHeight;
				preload = new Swiff(URL, {
					id: 'MediaboxSWF',
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// SOCIAL SITES
// Blip.tv
			} else if (URL.match(/blip\.tv/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "640px";
				mediaHeight = mediaHeight || "390px";
				preload = new Swiff(URL, {
					src: URL,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// DailyMotion
			} else if (URL.match(/dailymotion\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "480px";
				mediaHeight = mediaHeight || "381px";
				preload = new Swiff(URL, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Flickr
			} else if (URL.match(/flickr\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "500px";
				mediaHeight = mediaHeight || "375px";
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[5];
				preload = new Swiff('http://www.flickr.com/apps/video/stewart.swf', {
					id: mediaId,
					classid: 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
					width: mediaWidth,
					height: mediaHeight,
					params: {flashvars: 'photo_id='+mediaId+'&amp;show_info_box='+options.flInfo, wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Google Video
			} else if (URL.match(/google\.com\/videoplay/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "400px";
				mediaHeight = mediaHeight || "326px";
				mediaSplit = URL.split('=');
				mediaId = mediaSplit[1];
				preload = new Swiff('http://video.google.com/googleplayer.swf?docId='+mediaId+'&autoplay='+options.autoplayNum, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Megavideo - Thanks to Robert Jandreu for suggesting this code!
			} else if (URL.match(/megavideo\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "640px";
				mediaHeight = mediaHeight || "360px";
				mediaSplit = URL.split('=');
				mediaId = mediaSplit[1];
				preload = new Swiff('http://wwwstatic.megavideo.com/mv_player.swf?v='+mediaId, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Metacafe
			} else if (URL.match(/metacafe\.com\/watch/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "400px";
				mediaHeight = mediaHeight || "345px";
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[4];
				preload = new Swiff('http://www.metacafe.com/fplayer/'+mediaId+'/.swf?playerVars=autoPlay='+options.autoplayYes, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// MyspaceTV
			} else if (URL.match(/myspacetv\.com|vids\.myspace\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "425px";
				mediaHeight = mediaHeight || "360px";
				mediaSplit = URL.split('=');
				mediaId = mediaSplit[2];
				preload = new Swiff('http://lads.myspace.com/videos/vplayer.swf?m='+mediaId+'&v=2&a='+options.autoplayNum+'&type=video', {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Revver
			} else if (URL.match(/revver\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "480px";
				mediaHeight = mediaHeight || "392px";
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[4];
				preload = new Swiff('http://flash.revver.com/player/1.0/player.swf?mediaId='+mediaId+'&affiliateId='+options.revverID+'&allowFullScreen='+options.revverFullscreen+'&autoStart='+options.autoplay+'&backColor=#'+options.revverBack+'&frontColor=#'+options.revverFront+'&gradColor=#'+options.revverGrad+'&shareUrl=revver', {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Rutube
			} else if (URL.match(/rutube\.ru/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "470px";
				mediaHeight = mediaHeight || "353px";
				mediaSplit = URL.split('=');
				mediaId = mediaSplit[1];
				preload = new Swiff('http://video.rutube.ru/'+mediaId, {
					movie: 'http://video.rutube.ru/'+mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Seesmic
			} else if (URL.match(/seesmic\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "435px";
				mediaHeight = mediaHeight || "355px";
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[5];
				preload = new Swiff('http://seesmic.com/Standalone.swf?video='+mediaId, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Tudou
			} else if (URL.match(/tudou\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "400px";
				mediaHeight = mediaHeight || "340px";
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[5];
				preload = new Swiff('http://www.tudou.com/v/'+mediaId, {
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// YouKu
			} else if (URL.match(/youku\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "480px";
				mediaHeight = mediaHeight || "400px";
				mediaSplit = URL.split('id_');
				mediaId = mediaSplit[1];
				preload = new Swiff('http://player.youku.com/player.php/sid/'+mediaId+'=/v.swf', {
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// YouTube
			} else if (URL.match(/youtube\.com\/watch/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('v=');
				mediaId = mediaSplit[1];
				if (mediaId.match(/fmt=18/i)) {
					mediaFmt = '&ap=%2526fmt%3D18';
					mediaWidth = mediaWidth || "560px";
					mediaHeight = mediaHeight || "345px";
				} else if (mediaId.match(/fmt=22/i)) {
					mediaFmt = '&ap=%2526fmt%3D22';
					mediaWidth = mediaWidth || "640px";
					mediaHeight = mediaHeight || "385px";
				} else {
					mediaFmt = options.ytQuality;
					mediaWidth = mediaWidth || "480px";
					mediaHeight = mediaHeight || "295px";
				}
				preload = new Swiff('http://www.youtube.com/v/'+mediaId+'&autoplay='+options.autoplayNum+'&fs='+options.fullscreenNum+mediaFmt+'&color1=0x'+options.ytColor1+'&color2=0x'+options.ytColor2, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// YouTube
			} else if (URL.match(/youtube\.com\/view/i)) {
				mediaType = 'obj';
				mediaSplit = URL.split('p=');
				mediaId = mediaSplit[1];
				mediaWidth = mediaWidth || "480px";
				mediaHeight = mediaHeight || "385px";
				preload = new Swiff('http://www.youtube.com/p/'+mediaId+'&autoplay='+options.autoplayNum+'&fs='+options.fullscreenNum+mediaFmt+'&color1=0x'+options.ytColor1+'&color2=0x'+options.ytColor2, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Veoh
			} else if (URL.match(/veoh\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "410px";
				mediaHeight = mediaHeight || "341px";
				mediaSplit = URL.split('videos/');
				mediaId = mediaSplit[1];
				preload = new Swiff('http://www.veoh.com/videodetails2.swf?permalinkId='+mediaId+'&player=videodetailsembedded&videoAutoPlay='+options.AutoplayNum, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// Viddler
			} else if (URL.match(/viddler\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "437px";
				mediaHeight = mediaHeight || "370px";
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[4];
				preload = new Swiff(URL, {
					id: 'viddler_'+mediaId,
					movie: URL,
					classid: 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen, id: 'viddler_'+mediaId, movie: URL}
					});
				nextEffect();
// Vimeo
			} else if (URL.match(/vimeo\.com/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "400px";
				mediaHeight = mediaHeight || "225px";
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[3];
				preload = new Swiff('http://www.vimeo.com/moogaloop.swf?clip_id='+mediaId+'&amp;server=www.vimeo.com&amp;fullscreen='+options.fullscreenNum+'&amp;autoplay='+options.autoplayNum+'&amp;show_title='+options.vmTitle+'&amp;show_byline='+options.vmByline+'&amp;show_portrait='+options.vmPortrait+'&amp;color='+options.vmColor, {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// 12seconds
			} else if (URL.match(/12seconds\.tv/i)) {
				mediaType = 'obj';
				mediaWidth = mediaWidth || "430px";
				mediaHeight = mediaHeight || "360px";
				mediaSplit = URL.split('/');
				mediaId = mediaSplit[5];
				preload = new Swiff('http://embed.12seconds.tv/players/remotePlayer.swf', {
					id: mediaId,
					width: mediaWidth,
					height: mediaHeight,
					params: {flashvars: 'vid='+mediaId+'', wmode: 'opaque', bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
					});
				nextEffect();
// CONTENT TYPES
// INLINE
			} else if (URL.match(/\#mb_/i)) {
				mediaType = 'inline';
				mediaWidth = mediaWidth || options.initialWidth;
				mediaHeight = mediaHeight || options.initialHeight;
				URLsplit = URL.split('#');
				preload = $(URLsplit[1]).get('html');
				nextEffect();
// HTML
			} else {
				mediaType = 'url';
				mediaWidth = mediaWidth || options.initialWidth;
				mediaHeight = mediaHeight || options.initialHeight;
				mediaId = "mediaId_"+new Date().getTime();	// Safari will not update iframe content with a static id.
				preload = new Element('iframe', {
//					'href': URL,
					'src': URL,
					'id': mediaId,
					'width': mediaWidth,
					'height': mediaHeight,
					'frameborder': 0
					});
				nextEffect();
			}
		}
		return false;
	}

	function nextEffect() {
		switch (state++) {
			case 2:
				if (mediaType == "img"){
					mediaWidth = preload.width;
					mediaHeight = preload.height;
					image.setStyles({backgroundImage: "url("+URL+")", display: ""});
				} else if (mediaType == "obj") {
					if (Browser.Plugins.Flash.version<8) {
						image.setStyles({backgroundImage: "none", display: ""});
						image.set('html', '<div id="mbError"><b>Error</b><br/>Adobe Flash is either not installed or not up to date,<br/>please visit <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" title="Get Flash" target="_new">Adobe.com</a> to download the free player.</div>');
					} else {
						image.setStyles({backgroundImage: "none", display: ""});
						preload.inject(image);
					}
				} else if (mediaType == "inline") {
					image.setStyles({backgroundImage: "none", display: ""});
					image.set('html', preload);
				} else if (mediaType == "url") {
					image.setStyles({backgroundImage: "none", display: ""});
					preload.inject(image);
				} else {
					alert('this file type is not supported\n'+URL+'\nplease visit iaian7.com/webcode/Mediabox for more information');
				}
				$$(image, bottom).setStyle("width", mediaWidth);
				image.setStyle("height", mediaHeight);

				title.set('html', (options.showCaption) ? captionSplit[0] : "");
				caption.set('html', (options.showCaption && (captionSplit.length > 1)) ? captionSplit[1] : "");
				number.set('html', (options.showCounter && (images.length > 1)) ? options.counterText.replace(/{x}/, activeImage + 1).replace(/{y}/, images.length) : "");

				if ((prevImage >= 0) && (images[prevImage][0].match(/\.gif|\.jpg|\.png/i))) preloadPrev.src = images[prevImage][0];
				if ((nextImage >= 0) && (images[nextImage][0].match(/\.gif|\.jpg|\.png/i))) preloadNext.src = images[nextImage][0];

				state++;
			case 3:
				center.className = "";
				fx.resize.start({height: image.offsetHeight, width: image.offsetWidth, marginLeft: -image.offsetWidth/2});
				break;
				state++;
			case 4:
				bottomContainer.setStyles({top: top + center.clientHeight, marginLeft: center.style.marginLeft, visibility: "hidden", display: ""});
				fx.image.start(1);
				break;
			case 5:
				if (prevImage >= 0) prevLink.style.display = "";
				if (nextImage >= 0) nextLink.style.display = "";
				if (options.animateCaption) {
					fx.bottom.set(-bottom.offsetHeight).start(0);
				}
				bottomContainer.style.visibility = "";
				state = 1;
		}
	}

	function close() {
		if (state) {
			state = 0;
			preload.onload = $empty;
			image.set('html', '');
			for (var f in fx) fx[f].cancel();
			$$(center, bottomContainer).setStyle("display", "none");
			fx.overlay.chain(setup).start(0);
		}
		return false;
	}
})();

// AUTOLOAD CODE BLOCK
Mediabox.scanPage = function() {
	var links = $$("a").filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	});
	$$(links).mediabox({/* Put custom options here */}, null, function(el) {
		var rel0 = this.rel.replace(/[[]|]/gi," ");
		var relsize = rel0.split(" ");
		return (this == el) || ((this.rel.length > 8) && el.rel.match(relsize[1]));
	});
};
window.addEvent("domready", Mediabox.scanPage);


/*
	RS Fader
*/
var rs_fader = new Class(
{
	Implements:Options,
	
	obj: null,
	
	options:	{//set all the options here
		speed: 5
	},

	initialize: function(obj, options)
	{
		this.obj = obj;
		this.setOptions(options);

		this.obj.setStyle('overflow', 'hidden');
		this.obj.getElements('.element').setStyle('opacity', 0);
		this.obj.getElements('.element').setStyle('position', 'absolute');
		this.obj.getElement('.element').setStyle('opacity', 1);
		this.obj.getElement('.element').addClass('current');

		this.fader();
	},

	fader: function() {
		_old = this.obj.getElement('.current');
		if (_old.getNext('.element'))
			_new = _old.getNext('.element');
		else
			_new = this.obj.getElement('.element');

		_old.removeClass('current');
		_new.addClass('current');

		_old
			.get('tween', {property: 'opacity', duration: this.options.speed * 1000})
			.start(0);

		_new.get('tween', {property: 'opacity', duration: this.options.speed * 1000})
			.start(1)
			.chain(function() {
				this.fader();
			}.bind(this));

	}
});