/*
* FancyForm 0.95
* By Vacuous Virtuoso, lipidity.com
* ---
* Checkbox and radio input replacement script.
* Toggles defined class when input is selected.
*/

var FancyForm = {
	start: function(elements, options){
		if(FancyForm.initing != undefined) return;
		if($type(elements)!='array') elements = $$('input.fancyInput');
		if(!options) options = [];
		FancyForm.onclasses = ($type(options['onClasses']) == 'object') ? options['onClasses'] : {
			checkbox: 'checked',
			radio: 'selected'
		}
		FancyForm.offclasses = ($type(options['offClasses']) == 'object') ? options['offClasses'] : {
			checkbox: 'unchecked',
			radio: 'unselected'
		}
		if($type(options['extraClasses']) == 'object'){
			FancyForm.extra = options['extraClasses'];
		} else if(options['extraClasses']){
			FancyForm.extra = {
				checkbox: 'f_checkbox',
				radio: 'f_radio',
				on: 'f_on',
				off: 'f_off',
				all: 'fancy'
			};
		} else {
			FancyForm.extra = {};
		}
		FancyForm.onSelect = $pick(options['onSelect'], function(el){});
		FancyForm.onDeselect = $pick(options['onDeselect'], function(el){});
		FancyForm.chks = [];
		FancyForm.add(elements);
		$each($$('form'), function(x) {
			x.addEvent('reset', function(a) {
				window.setTimeout(function(){FancyForm.chks.each(function(x){FancyForm.update(x);x.inputElement.blur()})}, 200);
			});
		});
	},
	add: function(elements){
		if($type(elements) == 'element')
			elements = [elements];
		FancyForm.initing = 1;
		var keeps = [];
		var newChks = elements.filter(function(chk){
			if($type(chk) != 'element' || chk.inputElement || (chk.get('tag') == 'input' && chk.getParent().inputElement))
				return false;
			if(chk.get('tag') == 'input' && (FancyForm.onclasses[chk.getProperty('type')])){
				var el = chk.getParent();
				if(el.getElement('input')==chk){
					el.type = chk.getProperty('type');
					el.inputElement = chk;
					this.push(el);
				} else {
					chk.addEvent('click',function(f){
						if(f.event.stopPropagation) f.event.stopPropagation();
					});
				}
			} else if((chk.inputElement = chk.getElement('input')) && (FancyForm.onclasses[(chk.type = chk.inputElement.getProperty('type'))])){
				return true;
			}
			return false;
		}.bind(keeps));
		newChks = newChks.combine(keeps);
		newChks.each(function(chk){
			var c = chk.inputElement;
			c.setStyle('position', 'absolute');
			c.setStyle('left', '-9999px');
			chk.addEvent('selectStart', function(f){f.stop()});
			chk.name = c.getProperty('name');
			FancyForm.update(chk);
		});
		newChks.each(function(chk){
			var c = chk.inputElement;
			chk.addEvent('click', function(f){
				f.stop(); f.type = 'prop';
				c.fireEvent('click', f, 1);
			});
			chk.addEvent('mousedown', function(f){
				if($type(c.onmousedown) == 'function')
					c.onmousedown();
				f.preventDefault();
			});
			chk.addEvent('mouseup', function(f){
				if($type(c.onmouseup) == 'function')
					c.onmouseup();
			});
			c.addEvent('focus', function(f){
				if(FancyForm.focus)
					chk.setStyle('outline', '1px dotted');
			});
			c.addEvent('blur', function(f){
				chk.setStyle('outline', 0);
			});
			c.addEvent('click', function(f){
				if(f.event.stopPropagation) f.event.stopPropagation();
				if(c.getProperty('disabled')) // c.getStyle('position') != 'absolute'
					return;
				if (!chk.hasClass(FancyForm.onclasses[chk.type]))
					c.setProperty('checked', 'checked');
				else if(chk.type != 'radio')
					c.setProperty('checked', false);
				if(f.type == 'prop')
					FancyForm.focus = 0;
				FancyForm.update(chk);
				FancyForm.focus = 1;
				if(f.type == 'prop' && !FancyForm.initing && $type(c.onclick) == 'function')
					 c.onclick();
			});
			c.addEvent('mouseup', function(f){
				if(f.event.stopPropagation) f.event.stopPropagation();
			});
			c.addEvent('mousedown', function(f){
				if(f.event.stopPropagation) f.event.stopPropagation();
			});
			if(extraclass = FancyForm.extra[chk.type])
				chk.addClass(extraclass);
			if(extraclass = FancyForm.extra['all'])
				chk.addClass(extraclass);
		});
		FancyForm.chks.combine(newChks);
		FancyForm.initing = 0;
	},
	update: function(chk){
		if(chk.inputElement.getProperty('checked')) {
			chk.removeClass(FancyForm.offclasses[chk.type]);
			chk.addClass(FancyForm.onclasses[chk.type]);
			if (chk.type == 'radio'){
				FancyForm.chks.each(function(other){
					if (other.name == chk.name && other != chk) {
						other.inputElement.setProperty('checked', false);
						FancyForm.update(other);
					}
				});
			}
			if(extraclass = FancyForm.extra['on'])
				chk.addClass(extraclass);
			if(extraclass = FancyForm.extra['off'])
				chk.removeClass(extraclass);
			if(!FancyForm.initing)
				FancyForm.onSelect(chk);
		} else {
			chk.removeClass(FancyForm.onclasses[chk.type]);
			chk.addClass(FancyForm.offclasses[chk.type]);
			if(extraclass = FancyForm.extra['off'])
				chk.addClass(extraclass);
			if(extraclass = FancyForm.extra['on'])
				chk.removeClass(extraclass);
			if(!FancyForm.initing)
				FancyForm.onDeselect(chk);
		}
		if(!FancyForm.initing)
			chk.inputElement.focus();
	},
	all: function(){
		FancyForm.chks.each(function(chk){
			chk.inputElement.setProperty('checked', 'checked');
			FancyForm.update(chk);
		});
	},
	none: function(){
		FancyForm.chks.each(function(chk){
			chk.inputElement.setProperty('checked', false);
			FancyForm.update(chk);
		});
	}
};

window.addEvent('domready', function(){
	FancyForm.start();
});





/**
 * Mootools Accordion
 * Trigger accordion by external link to show/hide certain content
 * Example: <div class="nextBtn" onclick="myAcc.display(3);return false;">Volgende stap</div>
 * 
 * @url => Options see: http://mootools.net/docs/more/Fx/Fx.Accordion
 */

var myAcc = '';

window.addEvent('domready', function() {
	myAcc = new Accordion($('accordionContent'), 'h3.toggler', 'div.accordionElement', {
		opacity: false,
		alwaysHide: false, 
		display: -1,
		show: 0,
		initialDisplayFx: false,
		onActive: function(toggler, element){
			toggler.setStyle('background-image', 'url(/template/images/list-image-down.gif)');
			toggler.setStyle('text-decoration', 'underline');
		},
		onBackground: function(toggler, element){
			toggler.setStyle('background-image', 'url(/template/images/list-image-active.gif)');
			toggler.setStyle('text-decoration', 'none');
		}
	});
});

/**
 * Sexy Alert Box - for mootools 1.2 - jQUery 1.3
 * @name sexyalertbox.v1.2.js
 * @author Eduardo D. Sada - http://www.coders.me/web-js-html/javascript/sexy-alert-box
 * @version 1.2.2
 * @date 25-May-2009
 * @copyright (c) 2009 Eduardo D. Sada (www.coders.me)
 * @license MIT - http://es.wikipedia.org/wiki/Licencia_MIT
 * @example http://www.coders.me/ejemplos/sexy-alert-box/
 * @based in <PBBAcpBox> (Pokemon_JOJO, <http://www.mibhouse.org/pokemon_jojo>)
 * @thanks to Pokemon_JOJO!
 * @features:
 * * Chain Implemented (Cola de mensajes)
 * * More styles (info, error, alert, prompt, confirm)
 * * ESC would close the window
 * * Focus on a default button
*/
var AlertBox=new Class({Implements:[Options, Chain],getOptions:function(){return{name:'AlertBox',zIndex:65555,onReturn:false,onReturnFunction:$empty,BoxStyles:{'width':500},OverlayStyles:{'background-color':'#000','opacity':0.7},showDuration:200,showEffect:Fx.Transitions.linear,closeDuration:100,closeEffect:Fx.Transitions.linear,moveDuration:500,moveEffect:Fx.Transitions.Back.easeOut,onShowStart:$empty,onShowComplete:$empty,onCloseStart:$empty,onCloseComplete:function(a){this.options.onReturnFunction(this.options.onReturn)}.bind(this)}},initialize:function(b){this.i=0;this.setOptions(this.getOptions(),b);this.Overlay=new Element('div',{'id':'BoxOverlay','styles':{'display':'none','position':'absolute','top':'0','left':'0','opacity':0,'z-index':this.options.zIndex,'background-color':this.options.OverlayStyles['background-color'],'height':window.getScrollHeight()+'px','width':window.getScrollWidth()+'px'}});this.Content=new Element('div',{'id':this.options.name+'-BoxContenedor'});this.Contenedor=new Element('div',{'id':this.options.name+'-BoxContent'}).adopt(this.Content);this.InBox=new Element('div',{'id':this.options.name+'-InBox'}).adopt(this.Contenedor);this.Box=new Element('div',{'id':this.options.name+'-Box','styles':{'display':'none','z-index':this.options.zIndex+2,'position':'absolute','top':'0','left':'0','width':this.options.BoxStyles['width']+'px'}}).adopt(this.InBox);this.Overlay.injectInside(document.body);this.Box.injectInside(document.body);/*this.preloadImages();*/window.addEvent('resize',function(){if(this.options.display==1){this.Overlay.setStyles({'height':window.getScrollHeight()+'px','width':window.getScrollWidth()+'px'});this.replaceBox()}}.bind(this));this.Box.addEvent('keydown',function(a){if(a.key=='esc'){this.options.onReturn=false;this.display(0)}}.bind(this));window.addEvent('scroll',this.replaceBox.bind(this))},preloadImages:function(){var a=new Array(2);a[0]=new Image();a[1]=new Image();a[2]=new Image();a[0].src=this.Box.getStyle('background-image').replace(new RegExp("url\\('?([^']*)'?\\)",'gi'),"$1");a[1].src=this.InBox.getStyle('background-image').replace(new RegExp("url\\('?([^']*)'?\\)",'gi'),"$1");a[2].src=this.Contenedor.getStyle('background-image').replace(new RegExp("url\\('?([^']*)'?\\)",'gi'),"$1")},togFlashObjects:function(a){var b=new Array("embed","iframe","object");for(y=0;y<b.length;y++){var c=document.getElementsByTagName(b[y]);for(i=0;i<c.length;i++){c[i].style.visibility=a}}},display:function(a){if(this.Transition)this.Transition.cancel();if(this.options.display==0&&a!=0||a==1){if(Browser.Engine.trident4)$$('select','object','embed').each(function(node){node.style.visibility='hidden'});this.togFlashObjects('hidden');this.Overlay.setStyle('display','block');this.options.display=1;this.fireEvent('onShowStart',[this.Overlay]);this.Transition=new Fx.Tween(this.Overlay,{property:'opacity',duration:this.options.showDuration,transition:this.options.showEffect,onComplete:function(){sizes=window.getSize();scrollito=window.getScroll();this.Box.setStyles({'display':'block','left':(scrollito.x+(sizes.x-this.options.BoxStyles['width'])/2).toInt()});this.replaceBox();this.fireEvent('onShowComplete',[this.Overlay])}.bind(this)}).start(this.options.OverlayStyles['opacity'])}else{if(Browser.Engine.trident4)$$('select','object','embed').each(function(node){node.style.visibility='visible'});this.togFlashObjects('visible');this.queue.delay(500,this);this.Box.setStyles({'display':'none','top':0});this.Content.empty();this.options.display=0;this.fireEvent('onCloseStart',[this.Overlay]);if(this.i==1){this.Transition=new Fx.Tween(this.Overlay,{property:'opacity',duration:this.options.closeDuration,transition:this.options.closeEffect,onComplete:function(){this.fireEvent('onCloseComplete',[this.Overlay])}.bind(this)}).start(0)}}},replaceBox:function(){if(this.options.display==1){sizes=window.getSize();scrollito=window.getScroll();if(this.MoveBox)this.MoveBox.cancel();this.MoveBox=new Fx.Morph(this.Box,{duration:this.options.moveDuration,transition:this.options.moveEffect}).start({'left':(scrollito.x+(sizes.x-this.options.BoxStyles['width'])/2).toInt(),'top':(scrollito.y+(sizes.y-this.Box.offsetHeight)/2).toInt()});this.focusin.delay(this.options.moveDuration,this)}},focusin:function(){if($chk($('BoxAlertBtnOk'))){$('BoxAlertBtnOk').focus()}else if($chk($('BoxPromptInput'))){$('BoxPromptInput').focus()}else if($chk($('BoxConfirmBtnOk'))){$('BoxConfirmBtnOk').focus()}},queue:function(){this.i--;this.callChain()},messageBox:function(a,b,c,d){this.chain(function(){c=$extend({'textBoxBtnOk':'Ok','textBoxBtnCancel':'Annuleren','textBoxInputPrompt':null,'password':false,'onComplete':$empty},c||{});this.options.onReturnFunction=c.onComplete;this.ContenedorBotones=new Element('div',{'id':this.options.name+'-Buttons'});if(a=='alert'||a=='info'||a=='error'){this.AlertBtnOk=new Element('input',{'id':'BoxAlertBtnOk','type':'submit','value':c.textBoxBtnOk,'styles':{'width':'70px'}});this.AlertBtnOk.addEvent('click',function(){this.options.onReturn=true;this.display(0)}.bind(this));if(a=='alert')this.clase='BoxAlert';else if(a=='error')this.clase='BoxError';else if(a=='info')this.clase='BoxInfo';this.Content.setProperty('class',this.clase).set('html',b);this.AlertBtnOk.injectInside(this.ContenedorBotones);this.ContenedorBotones.injectInside(this.Content);this.display(1)}else if(a=='confirm'){this.ConfirmBtnOk=new Element('input',{'id':'BoxConfirmBtnOk','type':'submit','value':c.textBoxBtnOk,'styles':{'width':'70px'}});this.ConfirmBtnCancel=new Element('input',{'id':'BoxConfirmBtnCancel','type':'submit','value':c.textBoxBtnCancel,'styles':{'width':'70px'}});this.ConfirmBtnOk.addEvent('click',function(){this.options.onReturn=true;this.display(0)}.bind(this));this.ConfirmBtnCancel.addEvent('click',function(){this.options.onReturn=false;this.display(0)}.bind(this));this.Content.setProperty('class','BoxConfirm').set('html',b);this.ConfirmBtnOk.injectInside(this.ContenedorBotones);this.ConfirmBtnCancel.injectInside(this.ContenedorBotones);this.ContenedorBotones.injectInside(this.Content);this.display(1)}else if(a=='prompt'){this.PromptBtnOk=new Element('input',{'id':'BoxPromptBtnOk','type':'submit','value':c.textBoxBtnOk,'styles':{'width':'70px'}});this.PromptBtnCancel=new Element('input',{'id':'BoxPromptBtnCancel','type':'submit','value':c.textBoxBtnCancel,'styles':{'width':'70px'}});a=c.password?'password':'text';this.PromptInput=new Element('input',{'id':'BoxPromptInput','type':a,'value':d,'styles':{'width':'250px'}});this.PromptBtnOk.addEvent('click',function(){this.options.onReturn=this.PromptInput.value;this.display(0)}.bind(this));this.PromptBtnCancel.addEvent('click',function(){this.options.onReturn=false;this.display(0)}.bind(this));this.Content.setProperty('class','BoxPrompt').set('html',b+'<br />');this.PromptInput.injectInside(this.Content);new Element('br').injectInside(this.Content);this.PromptBtnOk.injectInside(this.ContenedorBotones);this.PromptBtnCancel.injectInside(this.ContenedorBotones);this.ContenedorBotones.injectInside(this.Content);this.display(1)}else{this.options.onReturn=false;this.display(0)}});this.i++;if(this.i==1)this.callChain()},alert:function(a,b){this.messageBox('alert',a,b)},info:function(a,b){this.messageBox('info',a,b)},error:function(a,b){this.messageBox('error',a,b)},confirm:function(a,b){this.messageBox('confirm',a,b)},prompt:function(a,b,c){this.messageBox('prompt',a,c,b)}});AlertBox.implement(new Events,new Options);window.addEvent('domready',function(){AlertBox=new AlertBox()});

/**
 * Input toggle
*/
window.addEvent('domready', function() {
	$$('input.defs').each(function(input) {
	
		input.addEvent('click', function() {
			if(this.getAttribute('rel') == '' || this.getAttribute('rel') == this.value){
				this.setAttribute('rel',this.value);
				this.value = '';
			}
	   });
		
		input.addEvent('blur', function() {
	       if(this.value == '') {
	    	   this.value = this.getAttribute('rel');	
	       }
	   });
	});
});

/*
Mootools banners
 */
var SL_Slider = new Class({

	//implements
	Implements: [Options],	
	
	//variables setup
	numNav: new Array(),		    //will store number nav elements (if used)
	timer: null,					//periodical function variable holder
	isSliding: 0,					//flag for animation/click prevention
	direction: 1,					//flag for direction (forward/reverse)
	
	//options
	options: {
	slideTimer: 8000,  			    //Time between slides (1 second = 1000), a.k.a. the interval duration
	orientation: 'horizontal',      //vertical, horizontal, or none: None will create a fading in/out transition.
	fade: false,                    //if true will fade the outgoing slide - only used if orientation is != None
	isPaused: false,				//flag for paused state
	transitionTime: 1100, 		    //Transition time (1 second = 1000)
	transitionType: 'cubic:out',	//Transition type
	container: null,				//container element
	items:  null, 					//Array of elements for sliding
	itemNum: 0,						//Current item number
	numNavActive: false,			//Whether or not the number navigation will be used
	numNavHolder: null,			    //Element that holds the number navigation
	playBtn: null,					//Play (and pause) button element
	prevBtn: null,					//Previous button element
	nextBtn: null					//Next button element
	},

	//initialization
	initialize: function(options) {
		var self = this;
		
		//set options
		this.setOptions(options);
		
		//remove any scrollbar(s) on the container
		self.options.container.setStyle('overflow', "hidden");  
		
		//if there is a play/pause button, set up functionality for it
		if(self.options.playBtn != null) {
			//self.pauseIt();  
			self.options.playBtn.set('text', 'pause');
			
			self.options.playBtn.addEvents({
				'click': function() {
					self.pauseIt();
				},				
				'mouseenter' : function() {
					this.setStyle('cursor', 'pointer');
				},
				'mouseleave' : function() {
					
				}
			});
		}
		
		//if there is a prev & next button, set up functionality for them
		if(self.options.prevBtn && self.options.nextBtn){
			
			self.options.prevBtn.addEvents({ 
				'click' : function() {
					if(self.isSliding == 0){
						if(self.options.isPaused == false){
							$clear(self.timer);
							self.timer = self.slideIt.periodical(self.options.slideTimer, self, null);
						}
						self.direction = 0;
						self.slideIt();
					}
				},
				'mouseenter' : function() {
					this.setStyle('cursor', 'pointer');
				},
				'mouseleave' : function() {
				
				}
			});	
			
			this.options.nextBtn.addEvents({ 
				'click' : function() {
					if(self.isSliding == 0){
						if(self.options.isPaused == false){
							$clear(self.timer);
							self.timer = self.slideIt.periodical(self.options.slideTimer, self, null);
						}
						self.direction = 1;
						self.slideIt();
					}
				},
				'mouseenter' : function() {
					this.setStyle('cursor', 'pointer');
				},
				'mouseleave' : function() {
					
				}
			});	
		}
		
		//setup items (a.k.a. slides) from list
		self.options.items.each(function(el, i){
			  
			//f.y.i.  el = the element, i = the index
			el.setStyle('position', "absolute");
			var itemH = el.getSize().y;
			var itemW = el.getSize().x;
			if(self.options.orientation == 'vertical'){ 
                el.setStyle('top', (-1 * itemH));
                el.setStyle('left', 0);
            }else if(self.options.orientation == 'none') {
                el.setStyle('left', 0);
                el.setStyle('top', 0);
                el.set('opacity', 0);
			}else{
                el.setStyle('left', (-1 * itemW));
            }
			// -- Number nav setup
			if(self.options.numNavActive == true){
				//create numbered navigation boxes, and insert into the 'num_nav' ul)
				var numItem = new Element('li', {id: 'num'+i});
				var numLink = new Element('a', {
					'class': 'numbtn',
					'html': (i+1)
				});
				numItem.adopt(numLink);
				self.options.numNavHolder.adopt(numItem);
				self.numNav.push(numLink);
				numLink.set('morph', {duration: 100, transition: Fx.Transitions.linear, link: 'ignore'});
				
				numLink.addEvents({
					'click' : function(){
						self.numPress(i);
					},
					'mouseenter' : function() {
						this.setStyle('cursor', 'pointer');
					}
				});
				
				//set initial number to active state
				if(i == self.options.itemNum){
					var initNum = self.numNav[i];
					initNum.addClass('active');
				}
			}
			//end if num nav 'active'
		
		 });
	
	},

	//startup method
	start: function() {
		
		var self = this;
		
		self.slideIt(self.options.itemNum);  //initialize first slide
		
		if(self.options.isPaused == false){
			self.timer = self.slideIt.periodical(self.options.slideTimer, self, null);
			if(self.options.playBtn) self.options.playBtn.set('text', 'pause');
		}
		else{
			//self.pauseIt();
			if(self.options.playBtn) self.options.playBtn.set('text', 'play');
		}
		
	},
	
	
	slideIt: function(passedID) {
		
		var self = this;
		
		//get item to slide out
		var curItem = self.options.items[self.options.itemNum]; 
		if(self.options.numNavActive == true){
			var curNumItem =  self.numNav[self.options.itemNum];
		}
		
		//check for passedID presence
		if(passedID != null) {
			if(self.options.itemNum != passedID){
				if(self.options.itemNum > passedID) { 
					self.direction = 0; 
				} else { 
					self.direction = 1;
				}
				self.options.itemNum = passedID;
			}
		}
		else{
			self.changeIndex();	
		}
		
		
		//now get item to slide in using new index
		var newItem = self.options.items[self.options.itemNum];
		if(self.direction == 0){
			var curX = self.options.container.getSize().x;
			var newX = (-1 * newItem.getSize().x);
            var curY = self.options.container.getSize().y;
            var newY = (-1 * newItem.getSize().y);
		}
		else{
			var curX = (-1 * self.options.container.getSize().x);	
			var newX = newItem.getSize().x;
            var curY = (-1 * self.options.container.getSize().y);
            var newY = newItem.getSize().y;
		}
		
		
		//add/remove active number's highlight
		if(self.options.numNavActive == true){
			var newNumItem =  self.numNav[self.options.itemNum];
			newNumItem.addClass('active');
		}
		
		
		//set up our animation stylings
		var item_in = new Fx.Morph(newItem, {
		     duration: self.options.transitionTime, 
		     transition: self.options.transitionType,
		     link: 'ignore',
		     
		     onStart: function(){
				self.isSliding = 1;  //prevents extra clicks
			},
		     
		     onComplete: function(){
				self.isSliding = 0;  //prevents extra clicks
			}
		     
		});
		
		
		
        if(self.options.orientation == 'vertical'){
            if(self.options.fade == true){item_in.start({'opacity':[0,1],'top' : [newY, 0]});}
            else{item_in.start({'top' : [newY, 0]});}
        }else if(self.options.orientation == 'none') {
            item_in.start({'opacity':[0,1]});
        }else{
            if(self.options.fade == true){item_in.start({'opacity':[0,1],'left' : [newX, 0]});}
            else{item_in.start({'left' : [newX, 0]});}
        }
        
		
		if(curItem != newItem){
			var item_out = new Fx.Morph(curItem, {
				     duration: self.options.transitionTime, 
				     transition: self.options.transitionType,
				     link: 'ignore'
			});
			
			if(self.options.numNavActive == true){
				curNumItem.removeClass('active');
			}
			
            if(self.options.orientation == 'vertical'){
                if(self.options.fade == true){item_out.start({'opacity':[0],'top' : [(curY)]});}
                else{item_out.start({'top' : [(curY)]});}
            }else if(self.options.orientation == 'none') {
                item_out.start({'opacity':[1,0]});
            }else{
                if(self.options.fade == true){item_out.start({'opacity':[0],'left' : [(curX)]});}
                else{item_out.start({'left' : [(curX)]});}
            }
		}
	},
	
	
	//--------------------------------------------------------------------------------------------------------
	//supplementary functions  (mini-functions)
	//--------------------------------------------------------------------------------------------------------
	pauseIt: function () {
		
		var self = this;
		
		//only move if not currently moving
		if(self.isSliding == 0){
			if(self.options.isPaused == false){
				self.options.isPaused = true;
				$clear(self.timer);
				self.options.playBtn.set('text', 'play');				
			}
			else{
				self.options.isPaused = false;
				self.slideIt();
				self.timer = self.slideIt.periodical(self.options.slideTimer, this, null); 
				self.options.playBtn.set('text', 'pause');
			}
			
		} //end if not sliding
		
	},
	
	changeIndex: function() {
		var self = this; 
		
		var numItems = self.options.items.length;  //get number of slider items
		
		//change index based on value of 'direction' parameter
		if(self.direction == 1){
			if(self.options.itemNum < (numItems - 1)){
				self.options.itemNum++; 
			}
			else{
				self.options.itemNum = 0;
			}
		}
		else if(self.direction == 0){
			if(self.options.itemNum > 0){
				self.options.itemNum--; 
			}
			else{
				self.options.itemNum = (numItems - 1);
			}
		}	
		
	},
	
	numPress: function (theIndex) {
		var self = this;
		
		if((self.isSliding == 0) && (self.options.itemNum != theIndex)){
			if(self.options.isPaused == false){
				$clear(self.timer);
				self.timer = self.slideIt.periodical(self.options.slideTimer, this, null);
			}
			self.slideIt(theIndex);
		}
	}
	//------------------------  end supp. functions -----------------------------------------//
});



/*
Mootools dealerfinder
 */

var dealerFinder = new Class({
	Implements: [Options, Events],
	options: {
		googleMapsContainerId  		: 'theMap',
		formCheckBoxWandId 			: 'wand',
		formCheckBoxVloerId 		: 'vloer',
		formCheckBoxCineWallId		: 'cinewall',
		formCheckBoxLaminaatId		: 'laminaat',
		formInputPostcodeId			: 'postcode',
		formInputWoonplaatsId		: 'woonplaats',
		formSelectLandId			: 'land',
		formSubmitButtonId			: 'zoeken',
		googleMapsRouteContainerId	: 'googleMapTextRoute',
		googleApiSettingRadius		: '50',
		pathToGetData				: '/template/front_locator_area.php',
		autoRun						: false
	},
	myData: {
		objGoogleMap 			: null,
		objGoogleMarker			: [],
		objGoogleGeoCoder		: null,
		objGoogleInfoWindow		: null,
		objGoogleRenderer		: null,
		objGoogleDirection		: null,
		objGoogleBounds			: null,
		aGoogleMarkers			: null,
		sLanguage				: 'nl',
		sFrom					: '',
		sTo						: ''
	},
	initialize: function(options){
		this.setOptions(options);
		if(this.checkOptions() === false){ 
		//	console.log('one of the options with *Id where not found! Please check your spelling.'); 
		}
		else if(this.options.autoRun===true){
			this.run(); 
		}
	},
	checkOptions: function(){
		if($(this.options.googleMapsContainerId)==null){ return false; 
		}else if($(this.options.formCheckBoxWandId)==null){ return false; 
		}else if($(this.options.formCheckBoxVloerId)==null){ return false;
		}else if($(this.options.formCheckBoxCineWallId)==null){ return false;
		}else if($(this.options.formCheckBoxLaminaatId)==null){ return false; 
		}else if($(this.options.formInputPostcodeId)==null){ return false; 
		}else if($(this.options.formInputWoonplaatsId)==null){ return false; 
		}else if($(this.options.googleMapsRouteContainerId)==null){ return false;
		}else if($(this.options.formSelectLandId)==null){ return false;		
		}else if($(this.options.formSubmitButtonId)==null){ return false; }
		else { return true; }
	},
	setSubmitAction: function(){
		var obj = this;
		$(this.options.formSubmitButtonId).addEvent('click', function(){
			if(obj.validateReqFields(obj)===true){  
				obj.googleGetStartLocation(); 
			
				$('formWarning').setStyle('display','none');
				$('Incorrect').setStyle('display','none');
				
				
			}else {  obj.sendErrorMssg('requiredFields'); }
		});
	},
	validateReqFields: function(object){
		if(		($(object.options.formInputPostcodeId).getProperty('value').trim().length < 4) && 
				($(object.options.formInputWoonplaatsId).getProperty('value').trim().length < 2)){ return false;
		}else { return true; }		
	},
	sendErrorMssg: function(type){
		if(type==='requiredFields'){
			$('formWarning').setStyle('display','block');
			$('Incorrect').setStyle('display','block');
			
		}
		if(type==='addressNotFound'){ 
			$('formWarning').setStyle('display','block');
			$('notFound').setStyle('display','block');
		}
		
		this.resetMap();
		
	},
	resetMap: function(){
		
		this.myData.objGoogleRenderer.setPanel(null);
		
		this.myData.objGoogleRenderer = null;
		this.myData.objGoogleMap = null;
		this.myData.objGoogleMarker	= null;
		this.myData.objGoogleMarker = [];
		this.myData.objGoogleGeoCoder = null;
		this.myData.objGoogleInfoWindow = null;
		this.myData.objGoogleRenderer = null;
		this.myData.objGoogleDirection = null;
		this.myData.objGoogleBounds = null;
		this.myData.aGoogleMarkers = null;
		
		this.run();
		
	},
	googleGetStartLocation: function(){
		var obj = this;

		var inputPostcode = $(this.options.formInputPostcodeId).getProperty('value').trim();
		var inputWoonplaats = $(this.options.formInputWoonplaatsId).getProperty('value').trim();
		var inputLand = $(this.options.formSelectLandId).getProperty('value').trim();
				
		var sAddress = inputPostcode+', '+inputWoonplaats+', '+inputLand; 
		
		var geoCoder = new google.maps.Geocoder();
		this.myData.objGoogleGeoCoder = geoCoder;
		geoCoder.geocode({address: sAddress}, function(results, status){
			if(status == google.maps.GeocoderStatus.OK){
				

				obj.myData.sFrom = results[0].formatted_address;
				
				var marker = new google.maps.Marker({
					map: obj.myData.objGoogleMap,
					position: results[0].geometry.location,
					icon: '/template/images/locations/home.png'
				});
				
				obj.myData.objGoogleMap.panTo(marker.getPosition());
				obj.myData.objGoogleMap.setZoom(11);
				
				obj.googleRemoveMarkers();
				
				obj.googleSearchLocationsNear(results[0].geometry.location);
				obj.myData.objGoogleMarker.push(marker);
				
				$('formWarning').setStyle('display','none');
				$('notFound').setStyle('display','none');
				
				
			}else {
				obj.sendErrorMssg('addressNotFound');
			}
		});

	},
	googleParseXML: function(str){
		if (window.ActiveXObject) {
			var doc = new ActiveXObject('Microsoft.XMLDOM');
			doc.loadXML(str);
			return doc;
		} else if (window.DOMParser) {
			return (new DOMParser).parseFromString(str, 'text/xml');
		}
	},
	googleSearchLocationsNear: function(Location){
		
		var obj = this;
	
		var lat = Location.lat();
		var lng = Location.lng();
			
		var radius 	= this.options.googleApiSettingRadius;
		
		var floor 	= $(this.options.formCheckBoxVloerId).checked;
		var wand 	= $(this.options.formCheckBoxWandId).checked;
		var cine 	= $(this.options.formCheckBoxCineWallId).checked;
		var laminaat= $(this.options.formCheckBoxLaminaatId).checked;
		
		var myHTMLRequest = new Request.HTML({url:this.options.pathToGetData, onSuccess:function(responseTree,responseElements,responseHTML){

			var xml = obj.googleParseXML(responseHTML);
			var markerNodes = xml.documentElement.getElementsByTagName("marker");
			var bounds = new google.maps.LatLngBounds();
			obj.myData.objGoogleBounds = bounds;
			
			if(markerNodes.length !== 0){
				for(var i=0; i < markerNodes.length; i++){
					var aWand = markerNodes[i].getAttribute("wand");
					var aCinewall = markerNodes[i].getAttribute("cinewall");
					var aFloor = markerNodes[i].getAttribute("floor");
					var aLaminaat = markerNodes[i].getAttribute("laminaat");
					
					var name = markerNodes[i].getAttribute("name");
					var address = markerNodes[i].getAttribute("address");
					var postcode = markerNodes[i].getAttribute("postcode");
					var plaats = markerNodes[i].getAttribute("plaats");
					var telefoon = markerNodes[i].getAttribute("telefoon");
					
					var website = markerNodes[i].getAttribute("website");
					
					var distance = parseFloat(markerNodes[i].getAttribute("distance"));
					var latlng = new google.maps.LatLng(
						parseFloat(markerNodes[i].getAttribute("lat")),
						parseFloat(markerNodes[i].getAttribute("lng"))
					);
					obj.googleSetNearbyMarkers(latlng, aWand, aCinewall, aFloor, aLaminaat, website, name, address, postcode, plaats, telefoon, distance, i, Location);
				}
				obj.myData.objGoogleBounds.extend(Location);
				obj.myData.objGoogleMap.setCenter(obj.myData.objGoogleMarker[0].getPosition());
				obj.myData.objGoogleMap.panToBounds(bounds);				
			}
		}}).get({'lat':lat,'lng':lng,'radius':radius,'floor':floor,'wand':wand,'cine':cine,'laminaat':laminaat});
	},
	googleSetNearbyMarkers: function(latlng, wand, cinewall, floor, laminaat, website, name, address, postcode, plaats, telefoon, distance, i, Location){
		
		var obj = this;
		
		if(this.myData.sLanguage ==='nl'){
			var sLangTel 	= 'Tel: ';
			var sLangJa 	= 'Ja';
			var sLangNee	= 'Nee';
			var sLangTitle  = 'Productgroep aanwezig';
			var sLangWand   = 'Wand- en plafondpanelen: ';
			var sLangVloer	= 'Vloeren: ';
			var sCinewall 	= 'Cinewall: ';
			var sLangLaminaat = 'Laminaat: ';
			var sLangPlan	= 'Plan Route';
		} else if(this.myData.sLanguage ==='en') {
			var sLangTel 	= 'Tel: ';
			var sLangJa 	= 'Yes';
			var sLangNee	= 'No';
			var sLangTitle  = 'Product group available';
			var sLangWand   = 'Wall and ceiling panels: ';
			var sCinewall 	= 'Cinewall: ';
			var sLangVloer	= 'Floor: ';
			var sLangLaminaat = 'Laminate: ';
			var sLangPlan	= 'Plan route';
		} else if(this.myData.sLanguage ==='du') {
			var sLangTel 	= 'T&eacute;l: ';
			var sLangJa 	= 'Oui';
			var sLangNee	= 'Non';
			var sLangTitle  = 'groupe de produits pr&eacute;sents';
			var sLangWand   = 'Lambris: ';
			var sLangVloer	= 'Rev&ecirc;tements de sol: ';
			var sCinewall 	= 'Cinewall: ';
			var sLangLaminaat = 'Schichtstoff: ';
			var sLangPlan	= 'Route Plan';
		} else if(this.myData.sLanguage ==='fr') {
			var sLangTel 	= 'T&eacute;l: ';
			var sLangJa 	= 'Oui';
			var sLangNee	= 'Non';
			var sLangTitle  = 'groupe de produits pr&eacute;sents';
			var sLangWand   = 'Lambris: ';
			var sLangVloer	= 'Rev&ecirc;tements de sol: ';
			var sCinewall 	= 'Cinewall: ';
			var sLangLaminaat = 'Stratifié: ';
			var sLangPlan	= 'Route Plan';
		}
				
		var myText = '';
			myText+= (address.trim())+'<br />';
			myText+= (postcode.trim())+' '+(plaats.trim())+'<br />';
			
			if(telefoon.trim().length > 3 ){
				myText+= sLangTel+(telefoon.trim())+'<br />';
			}else{
				myText+= '<br/>';
			}
			
			
			if(website.trim().length > 1){
				myText+= '<a style="color:green;text-decoration:none;" target="_BLANK" href="http://'+(website.trim())+'/">'+(website.trim())+'</a><br /><br />';
			}else{
				myText+= '<br /><br />';
			}
			myText+= '<b>'+sLangTitle+'</b><br />'
			myText+= sLangWand+((wand.trim()==1 ? sLangJa:sLangNee))+'<br />';
			myText+= sLangVloer+((floor.trim()==1 ? sLangJa:sLangNee ))+'<br />';					
			myText+= sCinewall+((cinewall.trim()==1 ? sLangJa:sLangNee))+'<br />';	
			myText+= sLangLaminaat+((laminaat.trim()==1 ? sLangJa:sLangNee ))+'<br />';		
			
				
		var myDiv = new Element('div',{'class' : 'infoWindow'});	
		var myH1 = new Element('h3',{'html': (name.trim())});
		var myP	= new Element('p',{
			'html' : myText,
			'styles' : {
				'font-family' : 'Trebuchet MS',
				'color' : '#000'
			}
			});
		
		var myA = new Element('b',{
			'html':sLangPlan,
			'class': 'googleWindmyLink',
			'styles': {
				'cursor':'pointer',
				'display': 'inline-block',
				'color': '#666'
			},
			'events': {
				'click': function(){
					obj.googleCalculateRoute(Location, latlng);
					obj.myData.objGoogleRenderer.setMap(obj.myData.objGoogleMap);
				}
			}			
		});
		
		myH1.inject(myDiv);
		myP.inject(myDiv);
		myA.inject(myDiv);
		
		var sHtml = myDiv;
			
		var marker = new google.maps.Marker({
			map: obj.myData.objGoogleMap,
			position: latlng,
			icon: '/template/images/locations/location_'+(i+1)+'.png'
		});
		
		google.maps.event.addListener(marker, 'click', function(){
			
			obj.myData.objGoogleGeoCoder.geocode({location: latlng }, function(results,status){
				if(status == google.maps.GeocoderStatus.OK){
					obj.myData.sTo = results[0].formatted_address;
				}
			});
			
			
			obj.myData.objGoogleInfoWindow.setContent(sHtml);
			obj.myData.objGoogleInfoWindow.open(obj.myData.objGoogleMap, marker);
		
		
		});
		
		obj.myData.objGoogleMarker.push(marker);
		
	},
	googleCalculateRoute: function(start, end){
		this.myData.objGoogleRenderer.setPanel($(this.options.googleMapsRouteContainerId));		
		
		var obj = this;
		var request = {
				origin:obj.myData.sFrom, 
				destination:obj.myData.sTo,
				travelMode: google.maps.DirectionsTravelMode.DRIVING
			};
		this.myData.objGoogleDirection.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				obj.myData.objGoogleRenderer.setDirections(response);
			}
		});
	},
	googleRemoveMarkers: function(){
		
		this.myData.objGoogleInfoWindow.close();
		this.myData.objGoogleRenderer.setMap(null);
		this.myData.objGoogleRenderer.setPanel(null);
		
		
		for(var i=0; i < this.myData.objGoogleMarker.length; i++){
			this.myData.objGoogleMarker[i].setMap(null);
		}
		this.myData.objGoogleMarker.length = 0;
	},	
	googleInit: function(){
		var latlng = new google.maps.LatLng(50.8792675, 4.7021386);
		
		var myOptions = {
				zoom: 11,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DEFAULT}		      
		    };
		
		var map = new google.maps.Map(document.getElementById(this.options.googleMapsContainerId), myOptions);
		
		var directionsRenderer = new google.maps.DirectionsRenderer();
		var infoWindow = new google.maps.InfoWindow();
		var directionService = new google.maps.DirectionsService();

		directionsRenderer.setMap(map);
		
		directionsRenderer.setPanel($(this.options.googleMapsRouteContainerId));		
		
		
		this.myData.objGoogleMap = map;
		this.myData.objGoogleRenderer = directionsRenderer;
		
		this.myData.objGoogleInfoWindow = infoWindow;
		this.myData.objGoogleDirection = directionService;
	
	},
	setLanguage: function(str){
		if(str==='fr' || str==='nl' || str==='en' || str==='du'){
			this.myData.sLanguage = str;
		}
	},
	run: function(){
		this.setSubmitAction();
		this.googleInit();
	}
});







/*
Milkbox v2.2.1 - required: mootools.js v1.2.1 core + more: Assets
	
by Luca Reghellin (http://www.reghellin.com) February 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:100,
	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') sine:in: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','iframe');
	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('visibility','hidden') };

	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' }
	});
	
	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 Ajax test: please test addGalleries() on-line'); }
	});
	
	this.currentRequest.send();
},

setGalleries:function(container,xmlfile){
	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);
},

//retrieves galleries from strings like 'gall1' or 'milkbox[gall1]' or 'milkbox:gall1'
getGallery:function(gallery){
	var f = null;
	if(gallery.test(/^milkbox/i)){
		f = this.families;
	} else {
		//create a temporary array with names without 'milkbox'
		f = this.families.map(function(item){
			var trimmed = item.trim();
			var name = trimmed.slice(0,trimmed.length).substr(8);
			var cleanName = name.replace(/(.+)]$/,"$1");
			return cleanName;
		});
	}
	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','iframe');
	
	//reload standard galleries
	this.prepareGalleries();
	this.removeGalleriesEvents();
	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 ****** */

removeGalleriesEvents:function(){
	this.galleries.each(function(gallery){
		$$(gallery).removeEvents('click');
	},this);
},

setGalleriesEvents:function(){
	this.galleries.each(function(gallery){
	
		$$(gallery).addEvent('click',function(e){
			//console.log('click');
			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)+' / '+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|jpeg|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('visibility','') };
	
	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;


var MilkboxTS = new Class({
    Extends: Milkbox,
    
    options:{//set all the options here
		minHeight: 50,
		minWidth: 50
	},
    
	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() });
		}
		if (fileSize.width < this.options.minWidth) {
			fileSize.width = this.options.minWidth;
		}
		if (fileSize.height < this.options.minHeight) {
			fileSize.height = this.options.minHeight;
		}

		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
	}
});


/**
* @file elSelect.js
* @downloaded from http://www.cult-f.net/2007/12/14/elselect/
* @author Sergey Korzhov aka elPas0
* @site  http://www.cult-f.net
* @date December 14, 2007
* 
*/
var elSelect = new Class({
	options: {
		container: false,
		baseClass : 'elSelect'
	},
	source : false,
	selected : false,
	_select : false,
	current : false,
	selectedOption : false,
	dropDown : false,
	optionsContainer : false,
	hiddenInput : false,
	/*
	pass the options,
	create html and inject into container
	*/
	initialize: function(options){
		this.setOptions(options);
		
		if ( !this.options.container ) return
		
		this.selected = false;
		this.source = $(this.options.container).getElement('select');
		this.buildFrameWork();
		
		$(this.source).getElements('option').each( this.addOption, this );
		$(this.options.container).set('html','');
		this._select.injectInside($(this.options.container));
		
		this.bindEvents();
		
	},
	
	buildFrameWork : function() {
		this._select = new Element('div').addClass( this.options.baseClass );
		this.current = new Element('div').addClass('selected').injectInside($(this._select));
		this.selectedOption = new Element('div').addClass('selectedOption').injectInside($(this.current));
		this.dropDown = new Element('div').addClass('dropDown').injectInside($(this.current));
		new Element('div').addClass('clear').injectInside($(this._select));
		this.optionsContainer = new Element('div').addClass('optionsContainer').injectInside($(this._select));
		var t = new Element('div').addClass('optionsContainerTop').injectInside($(this.optionsContainer));
		var o = new Element('div').injectInside($(t));
		var p = new Element('div').injectInside($(o));
		var t = new Element('div').addClass('optionsContainerBottom').injectInside($(this.optionsContainer));
		var o = new Element('div').injectInside($(t));
		var p = new Element('div').injectInside($(o));

		this.hiddenInput = new Element('input').setProperties({
			type  : 'hidden',
			name  : this.source.getProperty('name'),
			id    : this.source.getProperty('name') + 'Hidden'
		}).inject($(this.options.container), 'before');
	},
	
	bindEvents : function() {
		document.addEvent('click', function() { 
				if ( this.optionsContainer.getStyle('display') == 'block') 
					this.onDropDown();
			}.bind(this));
			
		$(this.options.container).addEvent( 'click', function(e) { new Event(e).stop(); } );	
		this.current.addEvent('click', this.onDropDown.bindWithEvent(this) );
		
	},
	clearOptions: function() {
		//debugger;
		$(this.optionsContainer).getChildren('.option').dispose();
		this.selected = false;
		this.hiddenInput.setProperty('value','');
		//this.selectedOption.set('text','');
		updateInputField(this.source.name, this.getValue(), true);
	},
	//add single option to select
	addOption: function( option ){
    	var o = new Element('div').addClass('option').setProperty('value',option.value);
    	
		if ( option.disabled ) { o.addClass('disabled'); } else {
			o.addEvents( {
				'click': this.onOptionClick.bindWithEvent(this),
				'mouseout': this.onOptionMouseout.bindWithEvent(this),
				'mouseover': this.onOptionMouseover.bindWithEvent(this)
			});
		}
		
		if ( $defined(option.getProperty('class')) && $chk(option.getProperty('class')) ) 
			o.addClass(option.getProperty('class'));

	
		if ( option.selected) { 
			if ( this.selected) this.selected.removeClass('selected');
			this.selected = o;
			o.addClass('selected');
			this.selectedOption.set('text',option.text);
			this.hiddenInput.setProperty('value',option.value);
		}
		o.set('text',option.text);
		o.injectBefore($(this.optionsContainer).getLast());
	},
	getValue: function() {
		return this.selected.value;
	},
	onDropDown : function( e ) {
			
			if ( this.optionsContainer.getStyle('display') == 'block') {
				this.optionsContainer.setStyle('display','none');
			} else {
				this.optionsContainer.setStyle('display','block');
				this.selected.addClass('selected');
				//needed to fix min-width in ie6
				var width =  this.optionsContainer.getStyle('width').toInt() > this._select.getStyle('width').toInt() ?
															this.optionsContainer.getStyle('width')
															:
															this._select.getStyle('width');
															
				this.optionsContainer.setStyle('width', width);
				this.optionsContainer.getFirst().setStyle('width', width);
				this.optionsContainer.getLast().setStyle('width', width);
			}						
	},
	onOptionClick : function(e) {
		var event = new Event(e);
		if ( this.selected != event.target ) {
			this.selected.removeClass('selected');
			event.target.addClass('selected');
			this.selected = event.target;
			this.selectedOption.set('text',this.selected.get('text'));
			this.hiddenInput.setProperty('value',this.selected.getProperty('value'));
		}
		this.onDropDown();
		updateInputField(this.source.name, this.getValue());
		doSearchRequest();
	},
	onOptionMouseover : function(e){
		var event = new Event(e);
		this.selected.removeClass('selected');
		event.target.addClass('selected');
	},
	onOptionMouseout : function(e){
		var event = new Event(e);
		event.target.removeClass('selected');
	}
	
});
elSelect.implement(new Events);
elSelect.implement(new Options);




/*
Class: Slider
        Creates a slider with two elements: a knob and a container. Returns the values.
Note:
        The Slider requires an XHTML doctype.
Arguments:
        element - the knob container
        knob - the handle
        options - see Options below
        maxknob - an optional maximum slider handle
Options:
		start - the minimum value for your slider.
		end - the maximum value for your slider.
        mode - either 'horizontal' or 'vertical'. defaults to horizontal.
        offset - relative offset for knob position. default to 0.
        knobheight - positions the max slider knob
		snap - whether the slider will slide in steps 
		numsteps - number of slide steps 
Events:
        onChange - a function to fire when the value changes.
        onComplete - a function to fire when you're done dragging.
        onTick - optionally, you can alter the onTick behavior, for example displaying an effect of the knob moving to the desired position.
                Passes as parameter the new position.
*/
var Slider = new Class({
	options: {
		onChange: Class.empty,
		onComplete: Class.empty,
		onTick: function(pos){
			this.moveKnob.setStyle(this.p, pos);			
		},
		start: 0,
		end: 100,
		offset: 0,
		knobheight: 20,
		knobwidth: 14,
		mode: 'horizontal',
		clip_w:0, 
		clip_l:0,
		isinit:true,
		snap: false,
		range: false,
		numsteps:null
	},
    initialize: function(el, knob,bkg, options, maxknob) {
		this.setOptions(options);
		this.element = $(el);
		this.knob = $(knob);
		this.previousChange = this.previousEnd = this.step = -1;
		this.bkg = $(bkg);
		if(this.options.steps==null){
			this.options.steps = this.options.end - this.options.start;
		}
		if(maxknob!=null)
			this.maxknob = $(maxknob);
		//else
		//	this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
		var mod, offset;
		switch(this.options.mode){
			case 'horizontal':
				this.z = 'x';
				this.p = 'left';
				mod = {'x': 'left', 'y': false};
				offset = 'offsetWidth';
				break;
			case 'vertical':
				this.z = 'y';
				this.p = 'top';
				mod = {'x': false, 'y': 'top'};
				offset = 'offsetHeight';
		}
		this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.half = this.knob[offset]/2;
		this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
		this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
		this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);

		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) ;
		

		if(maxknob != null) {
			this.maxPreviousChange = -1;
			this.maxPreviousEnd = -1;
			this.maxstep = this.options.end;
			this.maxknob.setStyle('position', 'relative').setStyle(this.p, + this.max - this.options.offset).setStyle('bottom', this.options.knobheight);
		}
		var lim = {};
		//status = this.z
		lim[this.z] = [- this.options.offset, this.max - this.options.offset];
		//lim[this.z] = [100, this.max - this.options.offset];

		this.drag = new Drag(this.knob, {
			limit: lim,
			modifiers: mod,
			snap: 0,
			onStart: function(){
					this.draggedKnob();
			}.bind(this),
			onDrag: function(){
					this.draggedKnob();
			}.bind(this),
			onComplete: function(){
					this.draggedKnob();
					this.end();
			}.bind(this)
		});
		if(maxknob != null) {  
			this.maxdrag = new Drag(this.maxknob, {
				limit: lim,
				modifiers: mod,
				snap: 0, 
				onStart: function(){
					this.draggedKnob(1);
				}.bind(this),
				onDrag: function(){
					this.draggedKnob(1);
				}.bind(this),
				onComplete: function(){
					this.draggedKnob(1);
					this.end();
				}.bind(this)
			});		
		}

		if (this.options.snap) {
			//this.drag.options.grid = Math.ceil(this.stepWidth);
			this.drag.options.grid = (this.full)/this.options.numsteps ;
			this.drag.options.limit[this.z][1] = this.full;
			//this.drag.options.grid = this.drag.options.grid - (this.knob[offset]/this.options.numsteps);
			status = "GRID - " + this.drag.options.grid  + "  , full = " + this.full// DEBUG

		}
		if (this.options.initialize) this.options.initialize.call(this);
    },
	setMin: function(stepMin){
		this.step = stepMin.limit(this.options.start, this.options.end);
		this.checkStep();
		this.end();
		this.moveKnob = this.knob;
		this.bkg.style.clip = "rect(0px "+  (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)";
		status =this.bkg.style.clip + "  vl= " + parseInt(this.toPosition(this.step)) ; //Debug
		this.fireEvent('onTick', this.toPosition(this.step));
		return this;
	},
	setMax: function(stepMax){
		this.maxstep = stepMax.limit(this.options.start, this.options.end);
		this.checkStep(1);
		this.end();
		this.moveKnob = this.maxknob;
		var w= Math.abs(this.toPosition(this.step)- this.toPosition(this.maxstep)) + 3 ;
		var r = parseInt(this.clip_l + w); 
		this.bkg.style.clip = "rect(0px "+  r + "px 10px "+ this.clip_l + "px)";

		this.fireEvent('onTick', this.toPosition(this.maxstep));
		// For Init Only 
		if(this.options.isinit){
			var lim = {}; var mi,mx;
			mi = - this.options.offset; 
			mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
			lim[this.z] = [mi, mx];
			this.drag.options.limit = lim;
			this.options.isinit = false;
		}
		return this; 
	},
	clickedElement: function(event){
		var position = event.page[this.z] - this.getPos() - this.half;
		position = position.limit(-this.options.offset, this.max -this.options.offset);

		this.step = this.toStep(position);

		//this.moveKnob = this.knob;
		this.bkg.style.clip = "rect(0px "+  (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)"  
		//status =this.bkg.style.clip; //Debug
		this.checkStep();
		this.end();
		this.fireEvent('onTick', position);
	},

	draggedKnob: function(mx){
		var lim = {}; var mi,mx;
		if(mx==null) {
			this.step = this.toStep(this.drag.value.now[this.z]);	 
			this.checkStep();
		}else {
			this.maxstep = this.toStep(this.maxdrag.value.now[this.z]); 
			this.checkStep(1);
		}
	},
	checkStep: function(mx){
		var lim = {}; var mi,mx;
		var limm = {};
		if(mx==null) {if (this.previousChange != this.step){this.previousChange = this.step;}}
		else {if (this.maxPreviousChange != this.maxstep){this.maxPreviousChange = this.maxstep;}}

		if(this.maxknob!=null) {
			mi = - this.options.offset; 
			mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
			//mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset ;
			lim[this.z] = [mi, mx];
			this.drag.options.limit = lim;

			mi = parseInt(this.knob.getStyle('left'))-this.options.offset+22; 
			//mi = parseInt(this.knob.getStyle('left'))-this.options.offset; 
			
			mx= this.max - this.options.offset;
			limm[this.z] = [mi, mx];
			this.maxdrag.options.limit = limm; 
			//console.log(this.step+' '+this.maxstep);
			if(this.step < this.maxstep){
				this.fireEvent('onChange', { minpos: this.step, maxpos: this.maxstep });
				//this.clip_l = parseInt(this.knob.getStyle('left'));
			}
			else{
				this.fireEvent('onChange', { minpos: this.maxstep, maxpos: this.step });
				//this.clip_l = (parseInt(this.maxknob.getStyle('left')) + 10) ;
			}	
			this.clip_l = parseInt(this.knob.getStyle('left')) + 10;
			//var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left'))) + 3;	
			var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left')));
			//if(w > 3) w = w+3;
			
			var r = parseInt(this.clip_l + w); 
			this.bkg.style.clip = "rect(0px "+  r + "px 10px "+ this.clip_l + "px)"  
			//status =this.bkg.style.clip  + " w= " + w //Debug

		}else {  
			this.fireEvent('onChange', this.step);
			this.bkg.style.clip = "rect(0px "+  (parseInt(this.drag.value.now[this.z]) +3)  + "px 10px 0px)"  
		}
	},
	end: function(){
		if (this.previousEnd !== this.step || (this.maxknob != null && this.maxPreviousEnd != this.maxstep)) {
			this.previousEnd = this.step;
			if(this.maxknob != null) {
				this.maxPreviousEnd = this.maxstep;
				if(this.step < this.maxstep)
					this.fireEvent('onComplete', { minpos: this.step + '', maxpos: this.maxstep + '' });
				else    
					this.fireEvent('onComplete', { minpos: this.maxstep + '', maxpos: this.step + '' });
			}else{  
				this.fireEvent('onComplete', this.step + '');
			}
		}
	},
	
	toStep: function(position){
		return Math.round((position + this.options.offset) / this.max * this.options.steps) + this.options.start;
	},

	toPosition: function(step){
		return (this.max * step / this.options.steps) - (this.max * this.options.start / this.options.steps) - this.options.offset;
	}

});

Slider.implement(new Events);
Slider.implement(new Options);
