/*** - Last Updated : 19-12-2008 13:36 - ***/
if (typeof Effect != 'undefined') {
	Object.extend(Effect.Transitions, {
		Cubic: function(pos) {
			return Math.pow(pos, 2);
		}
	});
}
var Calendar = Class.create();
	Calendar.prototype = {
		slideDuration: 500,
		fadeDuration: 500,
		transition: (typeof Effect != 'undefined') ? Effect.Transitions.Cubic : null,
		startMonday: false,
		filePath: '/www/scripts/',
		mode: false,
		style: '',
		id: false,
		request: false,
		initialize: function( container, options ) {
			this.options = Object.extend(this, options || {});
			this.loading = false;
			this.container = $(container);
			this.events = Object.extend({
				clickLabel:	this.clickLabel.bind(this)
			}, this.events);
		    
			this.AjaxEvents = {
		      onCreate: this.onCreate.bind(this),
		      onComplete: this.onComplete.bind(this)
			}
			
			var  pars = {}
			if(this.picker) {
				if(typeof(this.prefillDate) == 'object' && this.getInputDate(this.prefillDate)) pars.pickedDate = this.getInputDate( this.prefillDate );
				else if(date = this.getInputDate() ){
					pars.pickedDate = date;
					elements = date.split( this.separator );
					this.prefillDate = {
						day: elements[0],
						month: elements[1],
						year: elements[2]	
					}
					this.pick( this.prefillDate );
				}
				if(this.linkWithInput) pars.gotoPickedDate = 1;
				this.id = this.picker.id;
			}
			
			this.AjaxOnComplete = function( AjaxObject ) {
				if(this.id){
					this.mainLoader = $$('#'+this.id+' div.loaderA').first();
					this.tempLoader = $$('#'+this.id+' div.loaderB').first();
					this.label 		= $$('#'+this.id+' span.label').first();
					this.arrowLeft 	= $$('#'+this.id+' div.arrowLeft').first();
					this.arrowRight = $$('#'+this.id+' div.arrowRight').first();
				}else{
					this.mainLoader = this.container.select('div[class=loaderA]').first();
					this.tempLoader = this.container.select('div[class=loaderB]').first();
					this.label 	  	= this.container.select('span[class=label]').first();
					this.arrowLeft  = this.container.select('div[class=arrowLeft]').first();
					this.arrowRight = this.container.select('div[class=arrowRight]').first();				
				}
				this.tempLoader.setOpacity(0).setStyle({marginLeft:0}).show();
				this.mainLoader.setOpacity(1).setStyle({marginLeft:0}).show();

				this.toUpdate = this.mainLoader;				
				this.AjaxOnComplete = function(AjaxObject) {
					this.toUpdate = false				
					if(this.picker) {
						if(typeof (this.prefillDate) == 'object' && this.getInputDate( this.prefillDate )) this.pick( this.prefillDate ) ;
						else if(this.prefillDate == true) this.pick( this.label.readAttribute('date').evalJSON() );
					}
					
					this.initializeCalendarFunctions();
					
					this.AjaxOnComplete = Prototype.emptyFunction;
				}.bind(this);
				var  pars = {
					mode: 'month'
				}
				if(this.linkWithInput) pars.gotoPickedDate = 1;
				this.u( pars );
			}.bind(this);
			this.toUpdate = this.container;
			this.u( pars );
		},
		initializeCalendarFunctions: function() {
			this.resetArrows();
			
			this.vars = this.mainLoader.select('table').first().readAttribute('summary').evalJSON();
			
			this.label.update( this.vars.label ).removeClassName('noHover');
			this.label.onclick = (this.vars.parent ? this.events.clickLabel : null);
			
			if(this.vars.hide_left_arrow) this.arrowLeft.hide();
			else this.arrowLeft.show();
			
			if(this.vars.hide_right_arrow) this.arrowRight.hide();
			else this.arrowRight.show();
			
			this.arrowLeft.onclick = this.clickArrow.bind(this, this.arrowLeft );
			this.arrowRight.onclick= this.clickArrow.bind(this, this.arrowRight );
			
			var clickables = this.mainLoader.select('td');

			switch(this.vars.current) {
				case 'month':
					if(this.picker) {
						clickables.each( function(s){s.onclick = this.clickMonth.bind(this, s)}, this);
					}
				  break;
				case 'year':
					clickables.each( function(s){s.onclick = this.clickYear.bind(this, s)}, this);		
				  break;
				case 'decade':
					this.label.addClassName('noHover');
					clickables.each( function(s){s.onclick = this.clickDecade.bind(this, s)}, this);
				  break;
			}
		},
		u: function( _pars ) {
			if(!this.loading && !this.transitioning) {
				this.loading = true;
				_pars = Object.extend({
					picker:(this.picker ? 1 : 0),
					startMonday: (this.startMonday ? 1 : 0),
					style: this.style
				}, _pars);
				if(this.picker && this.getInputDate()) _pars.pickedDate = this.getInputDate();
				var options = {
					method:'get',
					parameters: _pars, 
					onCreate:  this.AjaxEvents.onCreate,
					onComplete:this.AjaxEvents.onComplete
				}
				new Ajax.Request(this.filePath, options);
			}
		},
		resetArrows: function() {
			this.arrowLeft.setStyle('visibility', 'visible');
			this.arrowRight.setStyle('visibility', 'visible');
		},
		clickArrow: function(elm, evt ) {
			var params = {
				ts: (elm.hasClassName('arrowLeft') ? this.vars.pr_ts : this.vars.nx_ts),
				mode: this.vars.current
			};
			this.vars.direction = (elm.hasClassName('arrowLeft') ? 'left' : 'right')
			this.AjaxOnComplete = function() {
					this.slide();
					this.AjaxOnComplete = Prototype.emptyFunction;
			}.bind(this);
			this.u( params );
		},
		clickLabel: function() {
			var params = {
				ts: this.vars.ts,
				mode: this.vars.parent,
				parent: this.vars.current
			};
			this.AjaxOnComplete = function() { 
					this.fade(); 
					this.AjaxOnComplete = Prototype.emptyFunction;
			}.bind(this);
			this.u( params);
		},
		clickMonth: function(elm, evt ) {
			this.pick(elm.readAttribute('date').evalJSON(), true);
			this.mainLoader.select('td').invoke('removeClassName', 'selected');
			
			elm.addClassName('selected'); 
		},
		clickYear:  function(elm, evt ) {
			var params = {
				ts: elm.readAttribute('ts'),
				mode: 'month',
				parent: this.vars.current
			};
			this.AjaxOnComplete = function() { 
					this.fade(); 
					this.AjaxOnComplete = Prototype.emptyFunction;
			}.bind(this);
			this.u( params );
		},
		clickDecade:  function(elm, evt ) {
			var params = {
				ts: elm.readAttribute('ts'),
				m_ts:elm.readAttribute('m_ts'),
				mode: 'year',
				parent: this.vars.current
			};
			this.AjaxOnComplete = function() { 
					this.fade(); 
					this.AjaxOnComplete = Prototype.emptyFunction;
			}.bind(this);
			this.u( params );
		},
		slide: function() {
			if (typeof Effect != 'undefined') {
				this.transitioning = true;
				var options = {
					transition: this.transition,
					sync:true
				};
				this.tempLoader.setOpacity(1).setStyle({marginLeft:0}).show();
				this.mainLoader.setOpacity(1).setStyle({marginLeft:0}).show();
				
				var from = this.vars.direction == 'left' ? -164 : 164;
				
				new Effect.Parallel([
					new Effect.Tween(this.tempLoader, from,0, options, function(p){this.setStyle({marginLeft:p+"px"});}),
					new Effect.Tween(this.mainLoader, 0 , -from, options, function(p){this.setStyle({marginLeft:p+"px"});})
				],{
					afterFinish: function(){this.transitioning = false}.bind(this),
					duration: this.slideDuration/1000,
					queue: {
						position: 'end',
						scope: 'CalendarScope'
					}
				});
			}else{
				this.tempLoader.setOpacity(1).show();
				this.mainLoader.setOpacity(0).hide();
			}
			this.switchLoaders();
		},
		fade: function( overRuleTrans ) {
			if (typeof Effect != 'undefined') {
				this.transitioning = overRuleTrans ? false : true;
				var options = {
					transition: this.transition,
					sync:true
				};
				this.tempLoader.setOpacity(0).setStyle({marginLeft:0}).show();
				this.mainLoader.setOpacity(1).setStyle({marginLeft:0}).show();
				new Effect.Parallel([
					new Effect.Fade( this.mainLoader, options),
					new Effect.Appear(this.tempLoader, options )
				],{
					duration: this.fadeDuration/1000,
					afterFinish: function(){
						this.tempLoader.hide();
						this.transitioning = false;
						
					}.bind(this),
					queue: {
						position: 'end',
						scope: 'CalendarScope'
					}
				});
			}else{
				this.tempLoader.setOpacity(1).show();
				this.mainLoader.setOpacity(0).hide();
			}
			this.switchLoaders();
		},
		switchLoaders: function() {
			var temp = this.mainLoader;
			this.mainLoader = this.tempLoader;
			this.tempLoader = temp;
			this.initializeCalendarFunctions();
		},
		onCreate: function( AjaxObject ) {
			Ajax.activeRequestCount++;
		},
		onComplete: function( AjaxObject ) {
			Ajax.activeRequestCount--;
			this.loading = false;
			$(this.toUpdate ? this.toUpdate : this.tempLoader).update(AjaxObject.transport.responseText);
			this.AjaxOnComplete( AjaxObject );
		}
};

var Datepicker = Class.create(Calendar,{
	separateInput: false,
	prefillDate: true,
	linkWithInput: true,
	leadingZero: true,
	twoDigitYear: false,
	separator: '/',
	format: 'd/m/y',
	onclick: false,
	openWith: null,
	alignX: 'right',
	alignY: 'inputTop',
	offset: { 'x': 0, 'y': 0 },
	style: '',
	ieTransitionColor: '#FFFFFF',
	toggleDuration: 350,
	
	initialize: function( $super, element, options ) {
		this.options = Object.extend(this, options || {});
		this.element = $(element);
		this.events = {
			show: this.show.bind(this),
			toggle: this.toggle.bind(this),
			hide: this.hide.bind(this),
			linkedUpdate: this.linkedUpdate.bind(this)
		};
		if(!this.element) throw 'No (existing) element to create a datepicker for specified: new Datepicker(ELEMENT, [options])';
		//Check if the user wants multiple input
		if(this.separateInput) {
			this.element.day   = this.element.select('input[name='+ this.separateInput.day +']').first();
			this.element.month = this.element.select('input[name='+ this.separateInput.month +']').first();
			this.element.year  = this.element.select('input[name='+ this.separateInput.year +']').first();

			//linkWithInput
			if(this.linkWithInput) {
				this.element.day.observe( 'keyup', this.events.linkedUpdate );
				this.element.month.observe( 'keyup', this.events.linkedUpdate );
				this.element.year.observe( 'keyup', this.events.linkedUpdate );
			}
		}else {
			this.element.observe( 'keyup', this.events.linkedUpdate );
		}

		//Create the picker and calendar and inject in in the body
		this.picker 		= new Element('div').hide().addClassName('Calendarpicker' + (this.style != '' ? ' ' + this.style : ''));
		this.pickerContent 	= new Element('div').addClassName('pickerBackground');
		this.picker.identify();
		$super(this.pickerContent);
		
		this.picker.insert({top:this.pickerContent});
		$(document.body).insert({top:this.picker});
		
		//Add events for showing and hiding the picker
		var target = (this.openWith ? $(this.openWith) : this.element);
			target.observe('focus', this.events.show);
			target.observe('click',  (this.openWith ? this.events.toggle: this.events.show) );
			target.observe('change', this.events.hide);

		//If the datepicker is visible an outside click makes it hide
		document.observe( 'mousedown', function(e) {
			if( this.outsideHide && this.outsideClick(e, this.picker)  ) this.hide();
		}.bind(this) );
		this.visible = false;
		this.outsideHide = false;	
	},
	position: function() {
		var top, left;		
		switch(this.alignX) {
			case 'left':
				left = this.element.cumulativeOffset()[0];
				break;
			case 'center':
				var pickerMiddle = parseInt( this.pickerContent.getStyle('width') ) / 2;
				if(pickerMiddle == 0) pickerMiddle = 83;
				left = this.element.cumulativeOffset()[0] + (this.element.getWidth() / 2) - pickerMiddle -
						((parseInt(this.pickerContent.getStyle('padding-left')) + parseInt(this.pickerContent.getStyle('padding-right'))) / 2);

				break;
			case 'right': default:
				left = this.element.cumulativeOffset()[0] + this.element.getWidth() ;
				break;
		}
		
		switch(this.alignY) {
			case 'bottom':
				top = this.element.cumulativeOffset()[1] + this.element.getHeight();
				break;
			case 'top': 
				top = this.element.cumulativeOffset()[1] - parseInt(this.pickerContent.getStyle('height')) - 
					(parseInt(this.pickerContent.getStyle('padding-top')) + parseInt(this.pickerContent.getStyle('padding-bottom')));
				break;
			case 'inputTop': default:
				top = this.element.cumulativeOffset()[1];
		}
		
		if( this.isNumber( this.offset.x ) ) left += this.offset.x;
		if( this.isNumber( this.offset.y ) ) top  += this.offset.y;

		this.picker.setStyle({top: top+'px', left: left+'px', zindex: '999', position: 'absolute'});
	},
	show: function() {
		this.position();
		this.position();
		if(!this.visible) {
			this.outsideHide = this.visible =  true;
			if (typeof Effect != 'undefined') {
				//this.picker.setStyle({'background-color': this.ieTransitionColor});
				var options = {
					transition: this.transition,
					afterFinish: function(){
						//this.picker.setStyle('background-color', 'transparent');
					}.bind(this),
					duration: this.toggleDuration/1000,
					queue: {
						position: 'end',
						scope: 'PickerScope'
					}
				}
				this.picker.setOpacity(0).setStyle({display:'inline'})
				new Effect.Appear(this.picker, options );
			}else{
				this.picker.show();
			}
		}
	},	
	hide: function() {
		if(this.visible) {
			this.outsideHide = this.visible = false;
			//this.picker.setStyle({'background-color': this.ieTransitionColor});
			if (typeof Effect != 'undefined') {
				var options = {
					transition: this.transition,
					afterFinish: function(){
						//this.picker.setStyle('background-color', 'transparent');
					}.bind(this),
					duration: this.toggleDuration/1000,
					queue: {
						position: 'end',
						scope: 'PickerScope'
					}
				}
				//this.picker.setOpacity(1).setStyle({display:'inline'})
				new Effect.Fade(this.picker, options );
			}else{
				this.picker.hide();
			}
		}
	},
	toggle: function() {
		if(this.visible) this.hide();
		else this.show();
	},
	pick: function(_date, event) {

		if(this.leadingZero) {
			if(_date.day < 10)   _date.day = '0' + parseInt(_date.day, 10);
			if(_date.month < 10) _date.month = '0' + parseInt(_date.month, 10);
		}
		if(this.twoDigitYear) _date.year = _date.year.toString().substring(2, 4);
		if(this.separateInput) {

			if(this.element.day)   this.element.day.value = _date.day;
			if(this.element.month) this.element.month.value = _date.month;
			if(this.element.year)  this.element.year.value = _date.year;
			if(this.onclick && event)this.onclick.call(this,_date.day+"-"+_date.month+"-"+_date.year);
			this.hide();
		} else {
			switch(this.format) {
				case "m/d/y": this.element.value = _date.month + this.separator + _date.day + this.separator + _date.year; break;
				case "y/m/d": this.element.value = _date.year + this.separator + _date.month + this.separator + _date.day; break;
				case "y/d/m": this.element.value = _date.year + this.separator +  _date.day + this.separator + _date.month; break;
				case "d/m/y": default: this.element.value = _date.day + this.separator + _date.month + this.separator + _date.year;
			}
			if(this.onclick && event)this.onclick.call(this, _date.day+ this.separator +_date.month+ this.separator +_date.year);
			this.hide();
		}
		
	},
	getInputDate: function( _date ) {
		var day, month, year;
		if(_date) {
			day		= _date.day;
			month	= _date.month;
			year	= _date.year;
		} else if(this.separateInput) {
			day 	= parseInt($F(this.element.day), 10);
			month 	= parseInt($F(this.element.month), 10);
			year 	= parseInt($F(this.element.year), 10);
		} else {
			var date = $F(this.element).split( this.separator );
			if( date.length != 3 ) return null;
			switch(this.format) {
				case "m/d/y": day = date[1]; month = date[0]; year = date[2]; break;
				case "y/m/d": day = date[2]; month = date[1]; year = date[0]; break;
				case "y/d/m": day = date[1]; month = date[2]; year = date[0]; break;
				case "d/m/y": default: day = date[0]; month = date[1]; year = date[2];
			}
		}

		if( !this.isNumber( day ) || !this.isNumber( month ) || !this.isNumber( year ) || day == 0 || month == 0 || year == 0 ||
			(this.twoDigitYear && year > 99) || (!this.twoDigitYear && year < 1979) || (!this.twoDigitYear && year > 2030) || month > 12 || day > 31 ) return null;
		
		if(this.twoDigitYear && !Object.isNumber( year ) && year < 100) {
			year = parseInt(year);
			if(year < 10) year = '200'+  year;
			else if(year < 70) year = '20'+  year;
			else if(year > 69) year = '19'+  year;
			else year = new Date().getFullYear();
		}
		return day +'/'+ month +'/'+ year;
	},	
	linkedUpdate: function() {
		var date = this.getInputDate();
		if(date && this.pickedDate != date) {
			this.hide();
			this.AjaxOnComplete = function(AjaxObject) {
				this.fade(true);
				this.AjaxOnComplete = Prototype.emptyFunction;
			}
			this.u({mode:'month', gotoPickedDate: 'true'});
			this.pickedDate = date;
		}
	},
	outsideClick: function(_event, _element) {
		return (_event.pointerX() > _element.cumulativeOffset()[0] && _event.pointerX() < (_element.cumulativeOffset()[0] + _element.getWidth()) )
			  &&
			  (_event.pointerY() > _element.cumulativeOffset()[1] && _event.pointerY() < (_element.cumulativeOffset()[1] + _element.getHeight()) )
			   ? false : true;
	},
	isNumber: function(_number) {
		if(_number == '') return false;
		return (_number >= 0) || (_number < 0) ? true : false;
	}
});
document.observe('dom:loaded', function(){
	$$('span.datum').each(function(s){
			options = { 
				prefillDate: false,
				openWith: s.select('pickerImg').first(),
				filePath: '/calendar/',
				offset: { y:5, x: 2 },
				separateInput: { day: 'd', month: 'm', year: 'y' },
				alignX: 'center',
				alignY: 'bottom',
				style: 'adobe_cs3'
			};
			if(s.up('div#choose_period')) options.onclick = choose_period;
			else{
				if(s.id == 'dcp') 		options.onclick = open_day;
				if(s.id == 'overzicht') options.onclick = open_overzicht;
				if(s.id == 'advies') 	options.onclick = open_advies;
			}
			new Datepicker(s, options );
	});
});

