/**
* 
*/
var i4_Datepicker = {
	// ids
	id: 'default_calendar_id', // if more than one calendar set different id with set_id()
	classname: 'calendar_container',
	content_class: 'calendar_content',
	parent_id: 'i4_popup',
	form_field_id: '',
	form_field_converted_id: '',
	
	div_container: null,
	
	is_open: false,
	
	// settins (default)
	cal_scroller: 'dropdown',
	month_name_en: ["January", "February", "March", "April", "May", "June","July","August", "September", "October", "November", "December"],
	month_name_de: ["Januar", "Februar", "März", "April", "Mai", "Juni","Juli","August", "September", "Oktober", "November", "Dezember"],
	month_name_fr: ["janvier", "février", "mars", "avril", "mai", "juin","juillet","août", "septembre", "oktobre", "novembre", "décembre"],
	month_name_it: ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugnio","luglio","agosto", "settembre", "ottobre", "novembre", "dicembre"],
	month_name_es: ["enero", "febrero", "marzo", "abril", "mayo", "junio","julio","agosto", "septiembre", "octubre", "noviembre", "diciembre"],
	month_name_nl: ["Januari", "Februari", "Moart", "April", "Mei", "Juni","Juli","Augustus", "September", "October", "November", "December"],
	month_name: [],
	weekday_name_en: ["Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
	weekday_name_de: ["Sonntag", "Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],
	weekday_name_fr: ["dimanche", "lundi","mardi","mercredi","jeudi","vendredi","samedi"],
	weekday_name_it: ["domenica", "lunedì","martedì","mercoledì","giovedì","venerdì","sabato"],
	weekday_name_es: ["domingo", "lunes","martes","miercoles","jueves","viernes","sabado"],
	weekday_name_nl: ["Zondag", "Moandag","Dinsdag","Woensdag","Dandersdag","Vrijdag","Zaterdag"],
	weekday_name: [],
	first_day: 1, // monday
	date_format: 'ddmmyyyy', // ddmmyyyy, mmddyyyy, yyyymmdd
	date_separator: '.',
	language: 'de',
	
	
	// cal object
	cal_object: '',
	
	date_today: '',
	date_selected: '',

	
	/**
	* setter
	*/
	set_form_field_id: function(form_field_id) { this.form_field_id = form_field_id; return this; },
	set_parent_id: function(parent_id) { this.parent_id = parent_id; return this; },
	set_cal_scroller: function(cal_scroller) { this.cal_scroller = cal_scroller; return this; },
	set_date_format: function(date_format) { this.date_format = date_format; return this; },
	set_date_separator: function(date_separator) { this.date_separator = date_separator; return this; },
	set_first_day: function(first_day) { this.first_day = first_day; return this; },
	set_language: function(language) { this.language = language; return this; },
	set_id: function(id) { this.id = id; return this; },
	
	/**
	* calendar object methods
	*/
	switch_year: function(year){ this.cal_object.year = year; return this; }, 
	switch_month: function(month){ this.cal_object.month = month; return this; },	
	dec_month: function(){ this.cal_object.dec_month(); return this; }, 
	inc_month: function(){ this.cal_object.inc_month(); return this; }, 
	
	initialize: function(){
		if ($(this.form_field_converted_id)) {
			log('test');
			$(this.form_field_id).setValue(Calendar.convert_date($(this.form_field_converted_id).getValue()));
		}
		
		this.div_container = new Element('div', {id: this.id}).addClassName(this.classname);	
		
		// set language arrays
		switch(this.language){
			case 'de':
				this.month_name = this.month_name_de;
				this.weekday_name = this.weekday_name_de;
				break;
			case 'en':
				this.month_name = this.month_name_en;
				this.weekday_name = this.weekday_name_en;
				break;
			case 'fr':
				this.month_name = this.month_name_fr;
				this.weekday_name = this.weekday_name_fr;
				break;
			case 'it':
				this.month_name = this.month_name_it;
				this.weekday_name = this.weekday_name_it;
				break;
			case 'es':
				this.month_name = this.month_name_es;
				this.weekday_name = this.weekday_name_es;
				break;
			case 'nl':
				this.month_name = this.month_name_nl;
				this.weekday_name = this.weekday_name_nl;
				break;
			default:
				this.month_name = this.month_name_en;
				this.weekday_name = this.weekday_name_en;
				break;
		}
		
		// week names
		var frist_day;
		var first_day_2 = this.weekday_name[this.first_day];
		while(this.weekday_name[0] != first_day_2){
			first_day = this.weekday_name[0];
			this.weekday_name = this.weekday_name.without(first_day);
			this.weekday_name.push(first_day);
		} 
		
		
		// get date from input field
		this.date_selected = this.get_selected_date();
		
		// get current date and time
		this.date_today = new Date();
		
		// show selected date or today date
		var show_date = '';
		if(this.date_selected){
			show_date = this.date_selected;
		}else{
			show_date = this.date_today;
		}
		this.cal_object = Calendar.set_date(show_date).set_date_format(this.date_format).set_date_separator(this.date_separator);
	},
	
	/**
	* creates and shows dom
	*/
	show: function(){
		if(!this.is_open){
			this.initialize();

			$(this.parent_id).appendChild(this.div_container);
			$(this.id).hide();
			this.div_container.insert(this.get_structure()+this.update()+'</div>');
						
			this.update_position();
			this.div_container.appear({
				duration: 0.3	
			});
		}
		
		this.is_open = true;
	},
	
	get: function(){
		this.initialize();
	
		this.div_container.insert(this.get_structure()+this.update()+'</div>');
		
		return this;
	},
	
	get_structure: function(){
		var html_output = '';
		// header (close)
		html_output += "<div class='calendar_header popup_draggable'><a href='#' class='close_popup'>close</a></div><div class='"+this.content_class+"'>";
		
		return html_output;
	},
	
	update: function(){
		var html_output = '';
		var day_count = 0;
				
		
		
		// cal scroller
		if(this.cal_scroller == 'dropdown'){
			
			// month
			dropdown =  "<select name='MonthSelector' onchange='javascript:i4_Datepicker.switch_month(this.selectedIndex).update();'>";
			for (i = 0; i < 12; i++) {
				if (i == this.cal_object.month) {
					SelectStr = "selected='selected'";
				}else{
					SelectStr="";
				}
				dropdown += "<option "+SelectStr+" value="+i+">"+this.month_name[i]+"</option>";
			}
			dropdown+="</select>";
			
			//	Year selector
			dropdown += "<select name='YearSelector' onchange='javascript:i4_Datepicker.switch_year(this.value).update()'>";
			for (i = this.date_today.getFullYear() - 10; i < (this.date_today.getFullYear() + 10);i++)	{
				if (i == this.cal_object.year){
					SelectStr = "Selected";
				}else{
					SelectStr = "";
				}
				dropdown += "<option "+SelectStr+" value="+i+">"+i+"</option>";
			}
			dropdown+="</select>";
			
			html_output += "<div class='calendar_scroller'>"+dropdown+"</div>";
			
		} else if (this.cal_scroller == 'arrow') {
			var prev_year = "<a href='#' onclick='javascript:i4_Datepicker.switch_year("+(this.cal_object.year-1)+").update();'>&#60;&#60;</a>";
			var prev_month = "<a href='#' onclick='javascript:i4_Datepicker.dec_month().update();'>&#60;</a>";
			var str_date = this.month_name[this.cal_object.month]+' '+this.cal_object.year;
			var next_month = "<a href='#' onclick='javascript:i4_Datepicker.inc_month().update();'>&#62;</a>";
			var next_year = "<a href='#' onclick='javascript:i4_Datepicker.switch_year("+(this.cal_object.year+1)+").update();'>&#62;&#62;</a>";
			
			html_output += "<table class='calendar_arrow'><tr><td>"+prev_year+"</td><td>"+prev_month+"</td><td class='date'>"+str_date+"</td><td>"+next_month+"</td><td>"+next_year+"</td></tr></table>";
			
		}else{
			html_output += "cal_scroller not defined!";
		}
		
		// calendar table
		html_output += "<table class='calendar'><tr class='calendar_week'>";
		
		
		for(i = 0; i < 7; i++) {
			html_output += "<td>"+this.weekday_name[i].substr(0,2)+"</td>";
		}
		html_output += "</tr>";
		
		// body
		cal_date = new Date(this.cal_object.year, this.cal_object.month);
		cal_date.setDate(1);
		first_day = cal_date.getDay();
		first_day = first_day - this.first_day;
		if(first_day < 0){ first_day = 7 - (0 - first_day); }
		
	
		html_output += "<tr>";
		// empty cells
		for (i = 0; i < first_day; i++) {
			html_output += "<td>&nbsp;</td>";
			day_count++;
		}

		for (j = 1; j <= this.cal_object.get_month_days(); j++) {
			var str_cell;
			if((day_count %7 == 0) && (j > 1)) {
				html_output += "\n<tr>";
			}
			
			if((j == this.date_today.getDate()) && (this.cal_object.month == this.date_today.getMonth()) && (this.cal_object.year == this.date_today.getFullYear())){
				str_cell = "<td class='today choose highlight' onclick=\"i4_Datepicker.pick('"+this.cal_object.format_date(j)+"')\">"+j+"</td>"; // today
			}else{
				if(this.date_selected && (j == this.date_selected.getDate()) && (this.cal_object.month == this.date_selected.getMonth()) && (this.cal_object.year == this.date_selected.getFullYear())) { 
					str_cell = "<td class='selected choose highlight' onclick=\"i4_Datepicker.pick('"+this.cal_object.format_date(j)+"')\">"+j+"</td>"; // selected
				}else{	
					var class_name = '';
					if((day_count+this.first_day) %7 == 0){
						class_name = 'sunday';
					}else if ((day_count+1+this.first_day) %7 == 0){
						class_name = 'saturday';
					}else{
						class_name = 'weekday';
					}			
					
					str_cell = "<td class='"+class_name+" choose' onclick=\"i4_Datepicker.pick('"+this.cal_object.format_date(j)+"')\">"+j+"</td>";
				}		
			}	
								
			html_output += str_cell;
			
			day_count++;
			if((day_count %7 == 0) && (j < this.cal_object.get_month_days())) {
				html_output += "</tr>";
			}
			
		}
	
		// finish the table proper
		if(!(day_count % 7) == 0) {
			while(!(day_count % 7) == 0) {
				html_output += "<td>&nbsp;</td>";
				day_count++;
			}
		}
		html_output += "</tr>";
		
		html_output += "</table>";
		if($$('#'+this.id+' .'+this.content_class)[0]){
			$$('#'+this.id+' .'+this.content_class)[0].update(html_output);
		}
		
		return html_output;
	},
	
	pick: function(date){
		$(this.form_field_id).value = date;
		this.close();
		$(this.form_field_id).focus();
	},
	
	close: function(){
		if($(this.id)){
			$(this.id).fade({
				duration: 0.3,
				afterFinish: (function(){
					$(this.id).remove();
				}).bind(this)
			});
		}
		this.is_open = false;
	},
	
	get_selected_date: function(){
		var result = null;
		var field_value = $(this.form_field_id).value;
		
		if(field_value != ''){
			var date = '';
			var month = '';
			var year = '';

			// where are the separators
			var sp1 = field_value.indexOf(this.date_separator,0);
			var sp2 = field_value.indexOf(this.date_separator,(parseInt(sp1)+1));
			
			
			var offset = parseInt(this.date_format.toUpperCase().lastIndexOf("M")) - parseInt(this.date_format.toUpperCase().indexOf("M"))-1;
			
			
			if ((this.date_format.toUpperCase() == "DDMMYYYY")) {
				if (this.date_separator == "") {
					month = field_value.substring(2, 4+offset);
					date = field_value.substring(0,2);
					year = field_value.substring(4+offset,8+offset);
				} else {
					month = field_value.substring(sp1+1,sp2);
					date = field_value.substring(0,sp1);
					year = field_value.substring(sp2+1,sp2+5);
				}
			}else if ((this.date_format.toUpperCase() == "MMDDYYYY")) {
				if (this.date_separator == "") {
					month = field_value.substring(0,2+offset);
					date = field_value.substring(2+offset,4+offset);
					year = field_value.substring(4+offset,8+offset);
				} else {
					month = field_value.substring(0,sp1);
					date = field_value.substring(sp1+1,sp2);
					year = field_value.substring(sp2+1,sp2+5);
				}
			}else if ((this.date_format.toUpperCase() == "YYYYMMDD")) {
				if (this.date_separator == "") {
					month = field_value.substring(4,6+offset);
					date = field_value.substring(6+offset,8+offset);
					year = field_value.substring(0,4);
				} else {
					month = field_value.substring(sp1+1,sp2);
					date = field_value.substring(sp2+1,sp2+3);
					year = field_value.substring(0,sp1);
				}
			}
			
			
			if(year == '' || month == '' || date == ''){
				result = null;
			}else{
				result = new Date(year, month-1, date); 
			}
			
		}
		
		return result;
	},
	
	update_position: function(){
		var input_element_offset = Element.viewportOffset($(this.form_field_id));
		var parent_element_offset = Element.viewportOffset($(this.parent_id));

    	xpos = input_element_offset.left-parent_element_offset.left+$(this.form_field_id).getDimensions().width+5;
    	ypos = input_element_offset.top-parent_element_offset.top;
    	    	
    	$(this.id).setStyle({
    		'top': ypos+'px',
    		'left': xpos+'px'	
    	});
	}
	
}


/*
* calendar
*/
var Calendar = {
	date: '',
	month: '',
	year: '',
	hours: '',
	minutes: '',
	seconds: '',
	
	date_format: '',
	date_separator: '',
	
	set_date_format: function(date_format){ this.date_format = date_format; return this; },
	set_date_separator: function(date_separator){ this.date_separator = date_separator; return this; },
	
	set_date: function(date){
		this.date = date.getDate();
		this.month = date.getMonth();
		this.year = date.getFullYear();
		this.hours = date.getHours();	
		
		if(date.getMinutes() < 10){
			this.minutes = '0'+date.getMinutes();	
		}else{
			this.minutes = date.getMinutes();
		}
		
		if(date.getSeconds() < 10){
			this.seconds = '0'+date.getSeconds();	
		}else{
			this.seconds = date.getSeconds();
		}
		
		return this;
	},
	
	/**
	* get number of days in a month
	*/
	get_month_days: function() { //Get number of days in a month
		var days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		if (this.is_leap_year()) {
			days_in_month[1] = 29;
		}	
		return days_in_month[this.month];	
	},
	
	is_leap_year: function() {
		if ((this.Year %4) == 0) {
			if ((this.Year % 100 == 0) && (this.Year % 400) != 0) {
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
	},
	
	format_date: function(date){
		var result = '';
		var precede_zero = true;
		var month_digit = this.month+1;
		if (precede_zero == true) {
			if (date < 10){
				date = "0"+date;
			}
			if (month_digit < 10){
				month_digit = "0"+month_digit;
			}
		}

		if (this.date_format.toUpperCase() == "DDMMYYYY"){
			result = date+this.date_separator+month_digit+this.date_separator+this.year
		}else if (this.date_format.toUpperCase()=="MMDDYYYY"){
			result = month_digit+this.date_separator+date+this.date_separator+this.year;
		}else if (this.date_format.toUpperCase()=="YYYYMMDD"){
			result = this.year+this.date_separator+month_digit+this.date_separator+date;
		}else{
			result = date+this.date_separator+(this.month+1)+this.date_separator+this.year;
		}			
		
		return result;
	},
	
	inc_month: function() {	
		this.month++;
		if (this.month>=12) {
			this.month = 0;
			this.year++;
		}
	},
	
	dec_month: function() {	
		this.month--;
		if (this.month < 0) {
			this.month = 11;
			this.year--;
		}
	}, 
	
	convert_date: function(date) {
		var result = '';
		var splitted_time = date.split(" ");
		
		if (splitted_time.size() == 2) {
			date = splitted_time[0];
		}
	
		var splitted_en = date.split("-");
		var splitted_de = date.split(".");
		
		if (splitted_en.size() == 3 && splitted_en[0].length == 4 && splitted_en[1].length == 2 && splitted_en[2].length == 2) {
			result = splitted_en[2]+'.'+splitted_en[1]+'.'+splitted_en[0];
		} else if (splitted_de.size() == 3 && splitted_de[0].length == 2 && splitted_de[1].length == 2 && splitted_de[2].length == 4){
			result = splitted_de[2]+'-'+splitted_de[1]+'-'+splitted_de[0];
		}

		return result;
	}
	
}
