(function() {

var unitLength = [1,1000,60000,3600000,86400000];
Date.prototype.MILLISECOND = 0;
Date.prototype.SECOND = 1;
Date.prototype.MINUTE = 2;
Date.prototype.HOUR = 3;
Date.prototype.DAY = 4;
Date.prototype.add = function(unit, value)
{
	this.setTime(this.getTime()+value*unitLength[unit]);
}

// Load the appropriate language file (depending on user language [window.dm_lang])
var scriptFiles = document.getElementsByTagName('head')[0].getElementsByTagName('script');
var loc = null;
var script_loc;
for (var i = scriptFiles.length - 1; i >=0 && !loc; i--)
{
	script_loc = scriptFiles[i].src.substr(0, scriptFiles[i].src.lastIndexOf("/"));
	if (/lang$/i.test(script_loc))
	{
		loc = script_loc + "/" + window.dm_lang + ".js";
	}
}

if (loc != null)
{
	var script  = document.createElement('script');
	script.type = "text/javascript";
	script.src  = loc;
	script.setAttribute("charset", "utf-8");
	/*@cc_on
	/*@if(@_win32)
	        var bases = document.getElementsByTagName('base');
	        if (bases.length && bases[0].childNodes.length) {
	                bases[0].appendChild(script);
	        } else {
	                document.getElementsByTagName('head')[0].appendChild(script);
	        };
	@else @*/
	document.getElementsByTagName('head')[0].appendChild(script);
	/*@end
	@*/
}

datePickerController.removeEvent(window, 'load', datePickerController.create);
datePickerController.oldCreate = datePickerController.create;
datePickerController.create = function() {
	datePickerController.oldCreate();
	for (var i in datePickerController.datePickers)
	{
		fix_datepicker(datePickerController.datePickers[i]);
	}
	datePickerController.fireInit();
}
datePickerController.init = [];
datePickerController.addEvent(window, 'load', datePickerController.create);

datePickerController.addInitEvent = function(func)
{
	datePickerController.init[datePickerController.init.length] = func;
};

datePickerController.fireInit = function()
{
	for (var i = 0; i < datePickerController.init.length; i++)
	{
		datePickerController.init[i]();
	}
};

function fix_datepicker(dp)
{
	addEvent($("fd-but-"+dp.id), "click", new Function("event", "$('"+dp.id+"').focus();"));
	addEvent(document, "mousedown", new Function("event", "\
		if ( event == null ) event = document.parentWindow.event;\
		var el = event.target != null ? event.target : event.srcElement;\
		var found = false;\
		while(el.parentNode) {\
			if(el.id && (el.id == 'fd-"+dp.id+"' || el.id == 'fd-but-"+dp.id+"')) {\
				found = true;\
				break;\
			};\
			try {\
				el = el.parentNode;\
			} catch(err) {\
				break;\
			};\
		};\
		if(found){\
			window.setTimeout(function(){$('"+dp.id+"').focus();},20);\
			if (event.preventDefault) event.preventDefault();\
			event.returnValue = false;\
		}"));
	dp.legend = ["Date not available","Massification date"];
	dp.legendInfo = ["Images/cal_dates_disabled.gif", "Images/cal_dates_massification.gif"];
	// dp.legend can be overriden by locales, for labels...
	dp.specificDates = {};

	dp.addSpecificDates = function(classDate, dateArray) {
		var o = this;
		var fin = o.specificDates[classDate] ? o.specificDates[classDate]:[];
		for(var i = dateArray.length; i-- ;) {
			if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01])$/) != -1) fin[fin.length] = dateArray[i];
		}
		if(fin.length) {
			o.specificDates[classDate] = fin;
		};
	};
	dp.getSpecificDates = function(y, m) {
		var o = this;
		var obj = {};
		m = m < 10 ? "0" + String(m) : m;
		for (var classDate in o.specificDates)
		{
			for(var i = o.specificDates[classDate].length; i-- ;) {
				var tmp = o.specificDates[classDate][i].replace("****", y).replace("**", m);
				if(tmp < Number(String(y)+m+"01") || tmp > Number(y+String(m)+"31")) continue;
				obj[tmp] = classDate;
			}
		}
		return obj;
	};

	dp.create = function() {
		var o = this;

		function createTH(details) {
			var th = document.createElement('th');
			if(details.thClassName) th.className = details.thClassName;
			th.className+=" th";
			if(details.colspan) {
				th.colSpan = details.colspan;
			};
			return th;
		};

		function createThAndButton(tr, obj) {
			for(var i = 0, details; details = obj[i]; i++) {
				var th = createTH(details);
				tr.appendChild(th);
				var but = document.createElement('button');
				but.setAttribute("type", "button");
				but.className = details.className;
				but.id = o.id + details.id;
				but.appendChild(document.createTextNode(details.text));
				but.title = details.title || "";
				if(details.onmousedown) but.onmousedown = details.onmousedown;
				if(details.onclick) but.onclick = details.onclick;
				th.appendChild(but);
			}
		}
		var legend = "";
		if (hasClassName(document.getElementById(o.id), "legend_[0-9]*")) {
			legend = document.getElementById(o.id).className.match(/legend_([0-9]*)/i)[1];
		}
		function createLegend(tableFoot) {
			var tr;
			for (var i = 0; i < dp.legendInfo.length; i++) {
				if (legend.indexOf(i) != -1) {
					tr = document.createElement('tr');
					tr.className = "legend";
					tableFoot.appendChild(tr);

					var td=document.createElement('th');;
					tr.appendChild(td);
					td.colSpan = "7";
					var img = document.createElement('img');;
					img.src = dp.legendInfo[i];
					td.appendChild(img);
					td.align = "left";
					td.appendChild(document.createTextNode(dp.legend[i]));
				}
			}
		}


		/*@cc_on
		@if(@_jscript_version <= 5.6)
			if(!document.getElementById("iePopUpHack")) {
				o.iePopUp = document.createElement('iframe');
				o.iePopUp.src = "javascript:'<html></html>';";
				o.iePopUp.setAttribute('className','iehack');
				o.iePopUp.scrolling="no";
				o.iePopUp.frameBorder="0";
				o.iePopUp.name = o.iePopUp.id = "iePopUpHack";
				document.body.appendChild(o.iePopUp);
			} else {
				o.iePopUp = document.getElementById("iePopUpHack");
			};
		@end
		@*/

		if(typeof(fdLocale) == "object" && o.locale) {
			dp.titles  = fdLocale.titles;
			dp.months  = fdLocale.months;
			dp.fullDay = fdLocale.fullDay;
			if (fdLocale.legend)
				dp.legend = fdLocale.legend;
			// Optional parameters
			if(fdLocale.dayAbbr) dp.dayAbbr = fdLocale.dayAbbr;
			if(fdLocale.firstDayOfWeek) o.firstDayOfWeek = o.defaults.firstDayOfWeek = fdLocale.firstDayOfWeek;
		};

		if (o.div)
		{
			document.getElementsByTagName('body')[0].removeChild(o.div);
		}
		o.div = document.createElement('div');
		o.div.style.zIndex = 9999;
		o.div.style.display = "none";
		o.div.id = "fd-"+o.id;
		o.div.className = "datePicker";

		document.getElementsByTagName('body')[0].appendChild(o.div);

		var nbsp = String.fromCharCode( 160 );
		var tr, row, col, tableHead, tableBody, tableFoot;

		o.table = document.createElement('table');
		o.div.appendChild( o.table );

		tableHead = document.createElement('thead');
		o.table.appendChild( tableHead );

		tr  = document.createElement('tr');
		tableHead.appendChild(tr);

		//o.titleBar = createTH({thClassName:"date-picker-title", colspan:7});
		//tr.appendChild( o.titleBar );

       if(navigator.appName != "Netscape"){ // comme les codes ne functionne pas sous IE sans erreur... mais sous firefox ça marche bien
          //o.titleBar = createTH({thClassName:"date-picker-title", colspan:7});
		  //tr.appendChild( o.titleBar );

		   	o.titleBar = createTH({thClassName:"date-picker-title", colspan:6});
		   	tr.appendChild( o.titleBar );
			o.titleBar1 = createTH({thClassName:"date-picker-title", colspan:1});
			o.titleBar1.title = "Fermer";


			tr.appendChild( o.titleBar1 );
			var butc=document.createElement('A');
			butc.id = 'close-link-' + o.id;
        	butc.onclick = function(){
        		var inpId=this.id.replace('close-link-','');
        		var fdId = 'fd-' + inpId;
        		// alert(inpId + '\n' + fdId);
        		if(document.getElementById(fdId)) {
				    document.getElementById(fdId).style.display='none';
				    datePickerController.hideAll(document.getElementById(fdId));
				}
			}
        	butc.setAttribute("style","cursor:pointer;");
        	var butb=document.createElement('IMG');
			butb.src = "Provider/Images/Common/delete.jpg";
        	butb.alt = "Fermer";
        	o.titleBar1.appendChild(butc);
        	butc.appendChild(butb);
       }
       else{
        o.titleBar = createTH({thClassName:"date-picker-title", colspan:6});
		tr.appendChild( o.titleBar );
		o.titleBar1 = createTH({thClassName:"date-picker-title", colspan:1});
		o.titleBar1.title = "Fermer";
		tr.appendChild( o.titleBar1 );

        //var butc=document.createElement('A');
        //butc.setAttribute("onclick","document.getElementById('fd-dcc_calendar_My_date').style.visibility='hidden';");
        //var buta=document.createElement('BUTTON');
		//buta.className = "date_fermer";
		//buta.value = "F";


		//o.titleBar1.appendChild(butc);
		//butc.appendChild(buta);

        var butc=document.createElement('A');
        butc.setAttribute("onclick","document.getElementById('" + o.div.id + "').style.display='none';");
        butc.setAttribute("style","cursor:pointer;");
        var butb=document.createElement('IMG');
		butb.src = "Provider/Images/Common/delete.jpg";
        butb.alt = "Fermer";
        o.titleBar1.appendChild(butc);
        butc.appendChild(butb);
        }

		tr = null;

		tr  = document.createElement('tr');
		tableHead.appendChild(tr);

		tableBody = document.createElement('tbody');
		o.table.appendChild( tableBody );

		for(var rows = 0; rows < 7; rows++) {
			row = document.createElement('tr');

			if(rows != 0) tableBody.appendChild(row);
			else          tableHead.appendChild(row);

			for(var cols = 0; cols < 7; cols++) {
				col = (rows == 0) ? document.createElement('th') : document.createElement('td');
				row.appendChild(col);
				if(rows != 0) {
					col.appendChild(document.createTextNode(nbsp));
				} else {
					col.className = "date-picker-day-header";
					col.scope = "col";
				};
				col = null;
			};
			row = null;
		};

		// BAS TABLEAU
		tableFoot = document.createElement('tfoot');
		o.table.appendChild( tableFoot );

		//tr = document.createElement('tr');
		//tableFoot.appendChild(tr);

		createThAndButton
		(tr,
			[
				{colspan:2, className:"prev-but", id:"-prev-year-but", text:"\u00AB", title:dp.titles[2], onmousedown:function(e) { o.events.incDec(e,0,-1,0); window.setTimeout(function(){$(o.id).focus();},20);}},
				{className:"prev-but", id:"-prev-month-but", text:"\u2039", title:dp.titles[0], onmousedown:function(e) { o.events.incDec(e,0,0,-1); window.setTimeout(function(){$(o.id).focus();},20);}},
				{className:"today-but", id:"-today-but", text:"", onclick:o.events.gotoToday},
				{className:"next-but", id:"-next-month-but", text:"\u203A", title:dp.titles[1], onmousedown:function(e) { o.events.incDec(e,0,0,1); window.setTimeout(function(){$(o.id).focus();},20);}},
				{colspan:2, className:"next-but", id:"-next-year-but", text:"\u00BB", title:dp.titles[3], onmousedown:function(e) { o.events.incDec(e,0,1,0); window.setTimeout(function(){$(o.id).focus();},20);}}
			]);

		createLegend(tableFoot);

		tableFoot = tableBody = tableHead = tr = createThAndButton = createTH = null;
		o.created = true;
	};

	dp.oldUpdateTable = dp.updateTable;
	dp.updateTable = function() {
		var o = this;
		o.oldUpdateTable();

		var rows = 6;
		var cols = 7;
		var currentWeek = 0;

		var cells = new Array( rows );
		var trs = o.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
		for (var i = 0; i < rows; i++ )
		{
			cells[i] = new Array( cols );
			var tds = trs[i].getElementsByTagName('td');
			for (var j = 0; j < cols; j++ )
			{
				cells[i][j] = tds[j];
			}
		}

		// Set the tmpDate to the second day of this month (to avoid daylight savings time madness on Windows)
		var tmpDate = new Date( o.date.getFullYear(), o.date.getMonth(), 2 );
		tmpDate.setHours(5);

		// Do the disableDates for this year and month
		var m           = ((tmpDate.getMonth() + 1) < 10) ? "0" + (tmpDate.getMonth() + 1) : tmpDate.getMonth() + 1;
		var y           = tmpDate.getFullYear();

		var disabledDates = o.getDisabledDates(o.date.getFullYear(), o.date.getMonth() + 1);
		var specificDates = o.getSpecificDates(o.date.getFullYear(), o.date.getMonth() + 1);

		var today = new Date();

		for (var i = 1; i < 32; i++ ) {
			tmpDate.setDate( i );

			var weekDay  = ( tmpDate.getDay() + 6 ) % 7;
			var colIndex = ( (weekDay - o.firstDayOfWeek) + 7 ) % 7;
			var d        = (i < 10) ? ("0" + i) : i;
			var dt       = String(y)+m+d;

			var isToday = tmpDate.getDate() == today.getDate() &&
						tmpDate.getMonth() == today.getMonth() &&
						tmpDate.getFullYear() == today.getFullYear();

			if ( isToday ) {
				cells[currentWeek][colIndex].className += " date-picker-today";
			};
			if(dt in specificDates) {
				addClassName(cells[currentWeek][colIndex],specificDates[dt]);
			};

			if ( colIndex == 6 ) currentWeek++;
		};

	};

	dp.addWorkdays = function (date, nb)
	{
		var o = this;

		var y = Number(date.substr(0, 4));
		var m = Number(date.substr(4, 2));
		var d = Number(date.substr(6, 2));
		var currentDate = new Date(y, m-1, d);
		var disabledDates = o.getDisabledDates(y,m);

		while (nb > 0)
		{
			var currentDPdate;
			var weekDay;
			do
			{
				currentDate.add(currentDate.DAY, 1);
				y = currentDate.getFullYear();
				m = currentDate.getMonth()+1;
				d = currentDate.getDate();
				if(m < 10) m = "0" + m;
				if(d < 10) d = "0" + d;
				currentDPdate = String(y)+m+d;
				weekDay = (currentDate.getDay()+6)%7;
			}
			while (currentDPdate in disabledDates || o.disableDays[weekDay])
			nb--;
		}
		y = currentDate.getFullYear();
		m = currentDate.getMonth()+1;
		d = currentDate.getDate();
		if(m < 10) m = "0" + m;
		if(d < 10) d = "0" + d;
		return String(y)+m+d;
	};

	dp.addRangeLowWorkdays = function (nb)
	{
		var o = this;
		o.setRangeLow(o.addWorkdays(o.low, nb));
	};

	dp.addDisabledDates = function (dates)
	{
		var o = this;
		if (o.disabledDates.length > 0)
			o.setDisabledDates(o.disabledDates.concat(dates));
		else
			o.setDisabledDates(dates);
	};

	dp.fixHighlightDays = function ()
	{
		var o = this;
		var inp = document.getElementById(o.id);
		var highlightRegExp = /highlight-days-([1-7]){0,7}/g;           // the days to highlight in red
		// The days to highlight
		var dayArray = o.highlightDays;
		if(inp.className.search(highlightRegExp) != -1) {
			var tmp = inp.className.match(highlightRegExp)[0].replace(/highlight-days-/, '');
			dayArray = [0,0,0,0,0,0,0];
			for(var j = 0; j < tmp.length; j++) {
				dayArray[tmp.charAt(j) - 1] = 1;
			};
		}
		o.highlightDays = o.defaults.highlightDays = dayArray;
	};
	datePickerController.addInitEvent(function(){dp.fixHighlightDays();});

	dp.validateInput = function()
	{
		var o = this;
		var elem = o.getElem();
		if(!elem) return false;
		var madate = datePickerController.dateFormat(elem.value, o.format.search(/m-d-y/i) != -1);
		var y = madate.substr(0, 4);
		var m = madate.substr(4, 2);
		var d = madate.substr(6, 2);

		var realDate = new Date(y,m-1,d,5);// 5 is for 5 hours, to avoid daylight bugs...
		if (!o.outOfRange(realDate))
		{
			var disabledDates = o.getDisabledDates(y,m);
			var weekDay = (realDate.getDay()+6)%7;
			return !(madate in disabledDates || o.disableDays[weekDay]);
		}
		else
		{
			return false;
		}
	};

	dp.addLegendClass = function(newClass)
	{
		var o = this;
		var trs = o.table.getElementsByTagName("tr");
		for (var i = 0; i < trs.length; i++)
		{
			if (hasClassName(trs[i], 'legend'))
				addClassName(trs[i], newClass);
		}
	};

	dp.create();

}

})();

