window.NETAVENIR_popCal = function(opts) {
	this.opts = opts;
	this.init();
	
	this.date = null;
};
NETAVENIR_popCal.prototype = {
	init: function(){
		var me = this;

		jQuery(function() {
			jQuery(me.opts.container).hide();

			/*@cc_on
			if (parseInt(jQuery.browser.version) < 7)
				jQuery('<iframe class="NETAVENIR_popCal" src="BLOCKED SCRIPT;" scrolling="no" frameborder="0"></iframe>').appendTo(me.opts.container);
			@*/
			var popCal = jQuery('<div class="NETAVENIR_popCal"><iframe src="about:blank"  width="100%" marginwidth="0" height="100%" marginheight="0" scrolling="no" frameborder="0" hspace="0" vspace="0" allowtransparency="true"></iframe></div>');
			jQuery(me.opts.container).append(popCal);

			// button Click Handler
			jQuery(me.opts.clickButton)
				.css('cursor', 'pointer')
				.click(function(e) {
					e.preventDefault();
					e.stopPropagation();

					if (jQuery(me.opts.container).is(':visible'))
						return me.close();

					var ym = new String(jQuery(me.opts.selectMonthYearId).val());
					var y = ym.substring(0, 4);
					var m = ym.substring(4).replace(/[^0-9]/, '');

					var popCalUrl = me.opts.url.replace(/ym=(\d{4}-\d{2})/, 'ym=' + y + '-' + m);
					if (popCal.find('iframe').attr('src') != popCalUrl)
						popCal.find('iframe').attr('src', popCalUrl);
					jQuery(me.opts.container).show();
				});
			jQuery(document).click(function() { me.close(); });

			var f = function() {
				me._updateDate.call(me);
				if (typeof me.opts.onDateSelect == 'function')
					me.opts.onDateSelect.call(me);
			};
			jQuery(me.opts.selectDayId).change(f);
			jQuery(me.opts.selectMonthYearId).change(f);
			
			var d = new Date();
			me.setDate(d.getFullYear(), d.getMonth() + 1, d.getDate());
			if (typeof me.opts.onStart == 'function')
				me.opts.onStart.call(me);
		});
	},

	_updateDate: function() {
		var me = this;

		var ym = new String(jQuery(me.opts.selectMonthYearId).val());
		var y = ym.substring(0, 4);
		var m = ym.substring(4);
		var d = new String(jQuery(me.opts.selectDayId).val());
		
		me.setDate(y, m, d);
	},
	
	close: function() {
		var me = this;
		if (jQuery(me.opts.container).is(':visible'))
			jQuery(me.opts.container).hide();
	},

	// Compatibility-hook for calendrier.php
	selectDate: function(y, m, d){
		var me = this;

		me.setDate(y, m, d);
		if (typeof me.opts.onDateSelect == 'function')
			me.opts.onDateSelect.call(me);
	},
	
	// Real YYYY/MM/DD (MM => from 1 to 12)
	setDate: function(y, m, d) {
		var me = this;

		var d = d.length == 1 ? '0' + d : d;
		jQuery(me.opts.selectDayId).val(d);

		var ym = new String(y) + ((new String(m)).length == 1 ? '0' + m : m);
		jQuery(me.opts.selectMonthYearId).val(ym);

		me.date = new Date(y, m - 1, d);
		me.close();
	}
};