/* DateSelector
(Rasmus Schultz) */

if(typeof window.DateSelector == 'undefined') { 
window.DateSelector = function(config){
//function DateSelector(config) {
	this.display = function(e) {
		//this.onClick();
		this.opening = true;
		this.show(e);
	}

	this.config = config;
	this.created = false;
	
	if (config['theme']) {
		if (!DateSelector.themes[config['theme']]) {
			DateSelector.themes[config['theme']] = true;
			var link = document.createElement('link');
			link.type = 'text/css';
			link.media = 'all';
			link.rel = 'stylesheet';
			link.href = '/modules/util/include/dateselector_' + config['theme'] + '.css';
			document.getElementsByTagName('head').item(0).appendChild(link);
		}
		config['class'] = 'datesel_'+config['theme'];
		if (!config['next_month']) {
			config['next_month'] = '/modules/util/images/datesel_'+config['theme']+'_next_month.gif';
			config['prev_month'] = '/modules/util/images/datesel_'+config['theme']+'_prev_month.gif';
		}
	}
	
	if (config['lang']) {
		if (config['lang'] == 'auto') config['lang'] = navigator.language || navigator.browserLanguage;
		config['lang'] = (config['lang'] ? config['lang'].substring(0,2) : 'default');
		switch (config['lang']) {
			case 'da':
				config['days'] = ['S&oslash;','Ma','Ti','On','To','Fr','L&oslash'];
				config['months'] = ['Januar','Februar','Marts','April','Maj','Juni','Juli','August','September','Oktober','November','December'];
				config['blank'] = '(ikke sat)';
			break;
			default:
				config['days'] = ['Su','Mo','Tu','We','Th','Fr','Sa'];
				config['months'] = ['January','February','March','April','May','June','July','August','September','October','November','December'];
				config['blank'] = '(empty)';
			break;
		}
	}
	
	if (!config['mainDiv']) config['mainDiv'] = 'datesel_'+config['input'];
	
	this.disp_y = config['disp_y'] ? config['disp_y'] : 0;
	this.disp_x = config['disp_x'] ? config['disp_x'] : 0;
	
	this.always_visible = (config['visible'] == 'always');
	
	this.create = function() {
		this.mainDiv = document.createElement('div');
		
		this.mainDiv.id = this.config['mainDiv'];
		this.mainDiv.className = this.config['class'];
		this.mainDiv.onmouseover = function() { this._ds.over(true); }
		this.mainDiv.onmouseout  = function() { this._ds.over(false); }
		this.mainDiv._ds = this;
		this.mainDiv.style.display = this.always_visible ? 'block' : 'none';
	
		if (this.config['parent']) {
			document.getElementById(this.config['parent']).appendChild(this.mainDiv);
		} else {
			document.getElementsByTagName('body').item(0).appendChild(this.mainDiv);
		}
		this.init();
		this.render();
		this.created = true;
	}
	
	this.input = document.getElementById(this.config['input']);
	this.input._ds = this;
	this.input.onclick = function() {
		this._ds.display(this);
		return false;
	}
	
	this.onClick = new Function();
	this.onChange = new Function();
	
	if (config['date']) {
		var bits = config['date'].split("-");
		if (bits[1].charAt(0) == '0') bits[1] = bits[1].substr(1);
		if (bits[2].charAt(0) == '0') bits[2] = bits[2].substr(1);
		this.date = this.seldate = new Date(bits[0], bits[1]-1, bits[2]);
	} else {
		this.date = this.seldate = new Date();
		if (config['clear']) this.seldate = null;
	}
	
	this.opening = false;
	
	this.days = [31,28,31,30,31,30,31,31,30,31,30,31];
	
	this.instnum = DateSelector.instances.length;
	
	DateSelector.instances[this.instnum] = this;
	
	this.offset = function(e) {
		var o = {'left':0, 'top':0};
		do {
			o.left += e.offsetLeft || 0;
			o.top += e.offsetTop || 0;
			e = e.offsetParent;
			if (e) {
				var p = '';
				if (document.defaultView && document.defaultView.getComputedStyle) {
					// W3C
					var cur_style = document.defaultView.getComputedStyle(e,"");
					p = cur_style.getPropertyValue("position");
				} else if (e.currentStyle) {
					// IE5+
					p = e.currentStyle.position;
				} else {
					p = elem.style.absolute;
				}
				if (p == 'relative' || p == 'absolute') break;
			}
		} while (e);
		return o;
	}
	
	this.show = function(e) {
		if (!this.created)
			this.create();

		var d = this.seldate;
		this.date = d ? new Date(d.getFullYear(), d.getMonth(), d.getDate()) : new Date();
		var o = this.offset(e);
		var s = this.mainDiv.style;
		s.left = (o.left + this.disp_x) + 'px';
		s.top = (o.top + e.offsetHeight + this.disp_y) + 'px';
		s.display = 'block';
		this.showdate();
		this.render();
	}
	
	this.hide = function() {
		if (this.created)
			this.mainDiv.style.display = 'none';
	}
	
	if (config['display']) {
		this.displayDiv = document.createElement('div');
		this.displayDiv._ds = this;
		this.displayDiv.onclick = this.input.onclick;
		this.displayDiv.className = config['class']+'_display';
		this.displayDiv.id = config['display_id'];
		this.input.parentNode.insertBefore(this.displayDiv, this.input);
		this.input.style.display = 'none';
	}
	
	this.showdate = function() {
		// s: output string
		// f: date format
		// d: current date
		// i: iterator
		var s = '', f = config['format'], d = this.seldate;
		if (d) for (i=0; i<f.length; i++) {
			var c = f.charAt(i);
			switch (c) {
				case 'D':
					if (d.getDate()<10) s += '0';
				case 'd':
					s += d.getDate();
					break;
				case 'M':
					if (d.getMonth()+1<10) s += '0';
				case 'm':
					s += (d.getMonth()+1);
					break;
				case 'y':
				case 'Y':
					s += d.getFullYear();
					break;
				default:
					s += c;
			}
		}
		this.input.value = s;
		if (this.displayDiv) {
			if (this.displayDiv.childNodes.length) this.displayDiv.removeChild(this.displayDiv.childNodes[0]);
			this.displayDiv.appendChild( document.createTextNode( d ? this.seldate.toLocaleDateString() : this.config['blank'] ) );
		}
	}
	
	this.setdate = function() {
		var d = this.date;
		this.seldate = new Date(d.getFullYear(), d.getMonth(), d.getDate());
	}
	
	this.cleardate = function() {
		this.seldate = null;
		this.input.value = '';
	}
	
	this.showdate();
	if (config['clear'] && !config['date']) this.cleardate();
	
	this._render = function() {
		// d: date
		// c: config
		// i: iterator
		// s: output html string
		// mn: month names
		// dn: day names
		// cd: current day
		// cm: current month
		// cy: current year
		// td: today's day
		// tm: today's month
		// ty: today's year
		// ly: last shown year in dropdown
		// fy: first shown year in dropdown
		// d1: first date of the month
		// fd: first weekday
		// md: month days (number of days in month)
		// cn: class name prefix
		// H: elements that need hooking
		
		var d = this.date, c = this.config, now = new Date(), H = new Array();
		var i, s = '', mn = c['months'], dn = c['days'], cn = c['class'], cd = d.getDate(), cm = d.getMonth(), cy = d.getFullYear(), ty = ly = now.getFullYear()+1, tm = now.getMonth(), td = now.getDate(), fy = c['firstyear'] ? c['firstyear'] : 2006;
		var id = c['mainDiv'];
		var d1 = new Date(cy,cm,1);
		var fd = d1.getDay()-1; if (fd == -1) fd = 6;
		var md = ( cm != 1 ? this.days[cm] : ((cy % 4 == 0 && cy % 100 != 0) || cy % 400 == 0 ? 29 : 28) );
		var ly = this.config['lastyear'] ? this.config['lastyear'] : ly;
		
		s += '<img id="' + id + '_pm" src="' + c['prev_month'] + '" onclick="this._ds.date.setMonth(this._ds.date.getMonth()-1); this._ds.render();"/>';
		s += '<select class="' + cn + '_dropdown" id="' + id + '_m" onchange="this._ds.date.setMonth(this.selectedIndex); this._ds.render();">';
		for (i=0; i<12; i++) s+= '<option' + (cm==i ? ' selected="selected"' : '') + ' value="' + i + '">' + mn[i] + '</option>';
		s += '</select><select class="' + cn + '_dropdown" id="' + id + '_y" onchange="this._ds.date.setYear(this.options[this.selectedIndex].value); this._ds.render();">';
		for (i=fy; i<=ly; i++) s+= '<option' + (cy==i ? ' selected="selected"' : '') + ' value="' + i + '">' + i + '</option>';
		s += '</select>';
		s += '<img id="' + id + '_nm" src="' + c['next_month'] + '" onclick="this._ds.date.setMonth(this._ds.date.getMonth()+1); this._ds.render();"/>';
		s += '<table class="' + cn + '_table"><tr>';
		for (i=1; i<8; i++) s+= '<th>' + dn[i%7] + '</th>';
		s += '</tr>';
		
		H.push(id+'_m'); H.push(id+'_y'); H.push(id+'_nm'); H.push(id+'_pm');
		
		// a: array of rows
		// r: row number
		// p: padding (empty cells)
		// op: on page (boolean)
		
		var a = new Array(new Array()), r=0;
		for (i=0; i<fd; i++) a[0].push('<td>&nbsp;</td>');
		i=1; var op = this.seldate ? (this.seldate.getMonth() == cm && this.seldate.getFullYear() == cy) : false;
		while (i <= md) {
			if (a[r].length == 7) a[++r] = new Array();
			a[r].push('<td>' + this.render_day(id, op, i, cm, cy) + '</td>');
			H.push(id + '_a' + i);
			i++;
		}
		for (i=0; i<a.length; i++) {
			while(a[i].length < 7) {
				a[i].push('<td>&nbsp;</td>');
			}
			a[i] = a[i].join('');
		}
		s += '<tr>' + a.join('</tr><tr>') + '</tr></table>';
		
		if (c['clear']) {
			s += '<a href="#" class="'+cn+'_clear'+(this.seldate?'':'_selected')+'" id="' + id + '_clear" onclick="this._ds.cleardate(); this._ds.showdate(); this._ds._onChange(); return false">' + c['blank'] + '</a>';
			H.push(id + '_clear');
		}
		
		this.mainDiv.innerHTML = s;
		
		for (i=0; i<H.length; i++) {
			var e = document.getElementById(H[i]);
			if (e) e._ds = this;
		}
	}

	this.is_over = false;
	this.over = function(over) {
		this.is_over = over;
	}
	
	this.click = function() {
		if (!this.is_over && !this.opening &&!this.always_visible) this.hide();
		this.opening = false;
	}
	
	if (this.always_visible) {
		this.create();
	}
}

DateSelector.prototype.render_day = function(id, op, d, m, y) {
	if(this.config['direct_link']) {
		dd = d;
		dd = dd + "";
		while(dd.length < 2) {
			dd = "0" + dd;
		}
		m = m + 1;
		m = m + "";
		while(m.length < 2) {
			m = "0" + m;
		}
		if(this.config['userid'] != "") {
			return '<a id="' + id + '_a' + d + '" href="http://'+this.config['domain']+'.'+this.config['direct_link']+'/?mode=ws&skey='+this.config['skey']+'&uid='+this.config['userid']+'&paper='+this.config['paper']+'&date='+dd+'-'+m+'-'+y+'&folder='+this.config['paper_id']+'">' + d + '</a>';
		} else {
			return '<a id="' + id + '_a' + d + '" href="http://'+this.config['domain']+'.'+this.config['direct_link']+'/?mode=ws&paper='+this.config['paper']+'&date='+dd+'-'+m+'-'+y+'">' + d + '</a>';
		}
	} else {
		return '<a id="' + id + '_a' + d + '" href="#"' + (op && this.seldate && (this.seldate.getDate()==d) ? ' class="' + this.config['class'] + '_selected"' : '') + ' onclick="with(this._ds.date){setDate('+d+');setMonth('+m+');setYear('+y+');} this._ds.setdate(); this._ds.showdate(); this._ds._onChange(); this._ds.render(); return false">' + d + '</a>';
	}
}

DateSelector.prototype._onChange = function() {
	this.onChange();
}

DateSelector.prototype.init = function() {}

DateSelector.prototype.render = function() {
	this._render();
}

DateSelector.doc_click = document.onclick ? document.onclick : new Function();

DateSelector.instances = new Array();
DateSelector.themes = new Array();

document.onclick = function() {
	var inst = DateSelector.instances;
	for (i=0; i<inst.length; i++) {
		inst[i].click();
	}
	DateSelector.doc_click();
}

if (window['datesel_init']) {
	window.datesel_init();
}
}
