// Initialisation Date
var ds_i_date = new Date();
ds_c_month = ds_i_date.getMonth() + 1;
ds_c_year = ds_i_date.getFullYear();

// Get Element By Id
function ds_getel(id) {
	return document.getElementById(id);
}

// Get the left and the top of the element.
function ds_getleft(el) {
	var tmp = el.offsetLeft;
	el = el.offsetParent
	while(el) {
		tmp += el.offsetLeft;
		el = el.offsetParent;
	}
	return tmp;
}
function ds_gettop(el) {
	var tmp = el.offsetTop;
	el = el.offsetParent
	while(el) {
		tmp += el.offsetTop;
		el = el.offsetParent;
	}
	return tmp;
}

// Output Buffering
var ds_ob = ''; 
function ds_ob_clean() {
	ds_ob = '';
}
function ds_ob_flush() {
	ds_oe.innerHTML = ds_ob;
	ds_ob_clean();
}
function ds_echo(t) {
	ds_ob += t;
}

var ds_element; // Text Element...

var ds_monthnames = [ // 0 = Janvier
'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'
]; // You can translate it for your language.

var ds_daynames = [
'Dim', 'Lun', 'Mar', 'Me', 'Jeu', 'Ven', 'Sam', 'Sem.'
]; // You can translate it for your language.


// Calendar template
function ds_template_main_above(type, y, m) {
	var ds_today = new Date();
	ds_ty_m = ds_today.getMonth() + 1; // 1 = Janvier
	ds_ty_y = ds_today.getFullYear();

	var t = ds_monthnames[m - 1] + ' ' + y;
	var ret = '<table cellpadding="3" cellspacing="1" class="ds_tbl">' + '<tr>';
	if (m == ds_ty_m && y == ds_ty_y)
		ret = ret  + '<td class="ds_head" colspan="2"></td>';
	else
		ret = ret  + '<td class="ds_head" colspan="2" style="cursor: pointer" onclick="ds_pm(' + type + ');">&lt;&lt;</td>';
	ret = ret + '<td class="ds_head" style="cursor: pointer" onclick="ds_hi();" colspan="4">[Fermer]</td>'
	if ((type == 0 && m == 12 && y == (ds_ty_y + 2)) || (type == 1 && m == ds_ty_m && y == (ds_ty_y + 1)))
		 ret = ret + '<td class="ds_head" colspan="2"></td>'	
	else
		 ret = ret + '<td class="ds_head" colspan="2" style="cursor: pointer" onclick="ds_nm(' + type + ');">&gt;&gt;</td>'
	ret = ret + '</tr>' + '<tr>' + '<td colspan="8" class="ds_head">' + t + '</td>' + '</tr>' + '<tr>';
	return ret;
}

function ds_template_day_row(t) {
	return '<td class="ds_subhead">' + t + '</td>';
	// Define width in CSS, XHTML 1.0 Strict doesn't have width property for it.
}

function ds_template_new_week() {
	return '</tr><tr>';
}

function ds_template_blank_cell(colspan) {
	return '<td colspan="' + colspan + '"></td>'
}

function ds_template_week(type,w) {
	var ww = new String(w);
	return '<td class="ds_cellw" onclick="ds_onclick('+ type + ',' + ww.substr(0,4) + ',' + ww.substring(5) + ',0)">' + ww.substring(5) + '</td>';
	// Define width the day row.
}

function ds_template_day(type, d, m, y) {
	if (type == 1) // Quotidien
		return '<td class="ds_cellj" style="cursor:pointer; background-color: #EE0;" onclick="ds_onclick(' + type + ',' + y + ',' + m + ',' + d + ')">' + d + '</td>';
	else
		return '<td class="ds_cellj">' + d + '</td>';
	// Define width the day row.
}

function ds_template_main_below() {
	return '</tr>'
	     + '</table>';
}

// This one draws calendar...
function ds_draw_calendar(type, m, y) {
	// First clean the output buffer.
	ds_ob_clean();
	// Here we go, do the header
	ds_echo (ds_template_main_above(type, y, m));
	if (type == 1)
		fin = 7;
	else
		fin = 8;
	for (i = 0; i < fin; i ++) {
		ds_echo (ds_template_day_row(ds_daynames[i]));
	}
	// Make a date object.
	var ds_dc_date = new Date();
	ds_dc_date.setMonth(m - 1);
	ds_dc_date.setFullYear(y);
	ds_dc_date.setDate(1);
	if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
		days = 31;
	} else if (m == 4 || m == 6 || m == 9 || m == 11) {
		days = 30;
	} else {
		days = (y % 4 == 0) ? 29 : 28;
	}
	var first_day = ds_dc_date.getDay();
	var first_loop = 1;
	// Start the first week
	ds_echo (ds_template_new_week());
	// If sunday is not the first day of the month, make a blank cell...
	if (first_day != 0) {
		ds_echo (ds_template_blank_cell(first_day));
	}
	var j = first_day;
	for (i = 0; i < days; i ++) {
		// Today is sunday, make a new week.
		// If this sunday is the first day of the month,
		// we've made a new row for you already.
		if (j == 0 && !first_loop) {
			if (type == 0)
			{
				// Affichage numero semaine
				ds_echo (ds_template_week(type,ds_def_num_week(y,m,i)));
			}
			// New week!!
			ds_echo (ds_template_new_week());
		}
		// Make a row of that day!
		ds_echo (ds_template_day(type, i + 1, m, y));
		// This is not first loop anymore...
		first_loop = 0;
		// What is the next day?
		j ++;
		j %= 7;
	}
	if (j != 0)
		ds_echo (ds_template_blank_cell(7 - j));
	if (type == 0)
		ds_echo (ds_template_week(type,ds_def_num_week(y,m,i)));
	// Do the footer
	ds_echo (ds_template_main_below());
	// And let's display..
	ds_ob_flush();
	// Scroll it into view.
//	ds_ce.scrollIntoView();
}

// A function to show the calendar.
// When user click on the date, it will set the content of t.
function ds_sh(type,t) {
	// Set the element to set...
	ds_element = t;
	// Make a new date, and set the current month and year.
	var ds_sh_date = new Date();
	ds_c_month = ds_sh_date.getMonth() + 1;
	ds_c_year = ds_sh_date.getFullYear();
	// 
	if (document.getElementById('sem_deb'))
	{
		var sem_deb = document.getElementById('sem_deb').value;
		if (sem_deb != "")
		{
			ds_c_month = sem_deb.substring(3,5);
			ds_c_year = sem_deb.substring(6,10);
		}
	}
	// Draw the calendar
	ds_draw_calendar(type,ds_c_month, ds_c_year);
	// To change the position properly, we must show it first.
	ds_ce.style.display = '';
	// Move the calendar container!
	the_left = ds_getleft(t);
	the_top = ds_gettop(t) + t.offsetHeight;	
	ds_ce.style.left = the_left + 'px';
	ds_ce.style.top = the_top + 'px';
	// Scroll it into view.
//	ds_ce.scrollIntoView();
}

// Hide the calendar.
function ds_hi() {
	ds_ce.style.display = 'none';
}

// Moves to the next month...
function ds_nm(type) {
	// Increase the current month.
	ds_c_month ++;
	// We have passed December, let's go to the next year.
	// Increase the current year, and set the current month to January.
	if (ds_c_month > 12) {
		ds_c_month = 1; 
		ds_c_year++;
	}
	// Redraw the calendar.
	ds_draw_calendar(type,ds_c_month, ds_c_year);
}

// Moves to the previous month...
function ds_pm(type) {
	ds_c_month = ds_c_month - 1; // Can't use dash-dash here, it will make the page invalid.
	// We have passed January, let's go back to the previous year.
	// Decrease the current year, and set the current month to December.
	if (ds_c_month < 1) {
		ds_c_month = 12; 
		ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
	}
	// Redraw the calendar.
	ds_draw_calendar(type,ds_c_month, ds_c_year);
}

// Format the date to output.
function ds_format_sem(y, s) {
	// Semaine sur 2 digits
	s2 = '00' + s;
	s2 = s2.substr(s2.length - 2);
	// YYYY-SS
	return y + '-' + s2;
}

// Format the date to output.
function ds_format_jour(y, m, d) {
	y2 = '0000' + y;
	y2 = y2.substr(y2.length - 4);
	m2 = '00' + m;
	m2 = m2.substr(m2.length - 2);
	d2 = '00' + d;
	d2 = d2.substr(d2.length - 2);
	// JJ-MM-YYYY
	return d2 + '-' + m2 + '-' + y2;
//	// YYYY-MM-JJ
//	return y2 + '-' + m2 + '-' + d2;
}

// When the user clicks the day.
function ds_onclick(type, y, pa, pb) {
	// Hide the calendar.
	ds_hi();
	// Mise en forme
	if (type == 1)
		affich = ds_format_jour(y,pa,pb);
	else
		affich = ds_format_sem(y,pa);
	
	// Set the value of it, if we can.
	if (typeof(ds_element.value) != 'undefined') {
		ds_element.value = affich;
	// Maybe we want to set the HTML in it.
	} else if (typeof(ds_element.innerHTML) != 'undefined') {
		ds_element.innerHTML = affich;
	// I don't know how should we display it, just alert it to user.
	} else {
		alert(affich);
	}
}

function ds_def_num_week(yy,mm,dd)
{
	// La date passée en paramètre correspond toujours à un dimanche (getDays = 0)
	
	// On regarde la première semaine de l'année en cours
	var date_prem = new Date();
	date_prem.setFullYear(yy);
	date_prem.setMonth(0);
	date_prem.setDate(1);
	jour_prem = date_prem.getDay() // 0=Dimanche => 6=Samedi
	var nb_jour_prem = 8 - jour_prem;
	if (jour_prem == 0)
		nb_jour_prem = 1;
	
	// On détermine le n° de jour dans l'année correspondant au couple jour/mois
	var num_jour = 0;
	for (n=1; n<mm; n++)
	{
		if (n == 1 || n == 3 || n == 5 || n == 7 || n == 8 || n == 10 || n == 12) {
			num_jour += 31;
		} else if (n == 4 || n == 6 || n == 9 || n == 11) {
			num_jour += 30;
		} else {
			num_jour += (yy % 4 == 0) ? 29 : 28;
		}
	}
	num_jour += dd;
	
	num_week = (num_jour - nb_jour_prem) / 7;
	// Traitement des cas :
	// 1. Cas dernière semaine de l'année
	if (dd == 31 && mm == 12)
	{
		// On détermine le nombre de jours de la semaine de l'année d'après
		var dates_prem = new Date();
		dates_prem.setFullYear(yy + 1);
		dates_prem.setMonth(0);
		dates_prem.setDate(1);
		jours_prem = dates_prem.getDay() // 0=Dimanche => 6=Samedi
		var nbs_jour_prem = 8 - jours_prem;
		if (jours_prem == 0)
			nbs_jour_prem = 1;
		// Le 31.12 fait partie de la semaine 1 de l'année d'après 
		if (nbs_jour_prem > 3)
			return String(yy+1) + "-" + String(1);
		else if (nb_jour_prem > 3)
			return String(yy) + "-" + String(Math.floor(num_week) + 2);
		else
			return String(yy) + "-" + String(Math.floor(num_week) + 1);
	}
	if (nb_jour_prem > 3)
		return String(yy) + "-" + String(Math.floor(num_week) + 2);
	else if (num_week < 0)
		return ds_def_num_week(yy - 1,12,31);
	else
		return String(yy) + "-" + String(Math.floor(num_week) + 1);
}
