// Tigra Calendar v4.0.2 (12-01-2009) European (dd-mm-yyyy)
// http://www.softcomplex.com/products/tigra_calendar/
// Public Domain Software... You're welcome.
// default settins
var A_TCALDEF = {
	'months' : ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
	'weekdays' : ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
	'yearscroll': false, //show year scroller
	'weekstart': 1, //first day of week: 0-Su or 1-Mo
	'centyear'  : 70, //2 digit years less than 'centyear' are in 20xx, othewise in 19xx.
	'imgpath' : 'js/calendar/img/', //directory with calendar images
	'textohoy' : 'hoy',
	'althoy' : 'Ir a la fecha actual',
	'anterior_a_hoy' : 'No se puede seleccionar fecha de entrada anterior o igual a hoy',
	'anterior_a_entrada' : 'No se puede seleccionar fecha de salida inferior o igual a la fecha de entrada',
	'primero_fecha_entrada' : 'Seleccione primero su fecha de entrada deseada'
}

var A_TCALDEF_EN = {
	'months' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	'weekdays' : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
	'yearscroll': false, //show year scroller
	'weekstart': 1, //first day of week: 0-Su or 1-Mo
	'centyear'  : 70, //2 digit years less than 'centyear' are in 20xx, othewise in 19xx.
	'imgpath' : 'js/calendar/img/', //directory with calendar images
	'textohoy' : 'today',
	'althoy' : 'Ir a la fecha actual',
	'anterior_a_hoy' : 'No se puede seleccionar fecha de entrada anterior o igual a hoy',
	'anterior_a_entrada' : 'No se puede seleccionar fecha de salida inferior o igual a la fecha de entrada',
	'primero_fecha_entrada' : 'Seleccione primero su fecha de entrada deseada'
}


var A_TCALDEF_VAL = {
	'months' : ['Gener', 'Febrer', 'Marį', 'Abril', 'Maig', 'Juny', 'Juliol', 'Agost', 'Setembre', 'Octubre', 'Novembre', 'Desembre'],
	'weekdays' : ['Dg','Dl', 'Dt', 'Dc', 'Dj', 'Dv', 'Ds'],
	'yearscroll': false, //show year scroller
	'weekstart': 1, //first day of week: 0-Su or 1-Mo
	'centyear'  : 70, //2 digit years less than 'centyear' are in 20xx, othewise in 19xx.
	'imgpath' : 'js/calendar/img/', //directory with calendar images
	'textohoy' : 'hui',
	'althoy' : 'Anar a la data actual',
	'anterior_a_hoy' : 'No es pot seleccionar data d\'entrada anterior o igual a hui',
	'anterior_a_entrada' : 'No es pot seleccionar data d\'eixida inferior o igual a la data d\'entrada',
	'primero_fecha_entrada' : 'Seleccione primer la seua data d\'entrada desitjada'
}

// date parsing function
function f_tcalParseDate (s_date) {

	var re_date = /^\s*(\d{1,2})\-(\d{1,2})\-(\d{2,4})\s*$/;
	if (!re_date.exec(s_date))
		return alert ("Invalid date: '" + s_date + "'.\nAccepted format is dd-mm-yyyy.")
	var n_day = Number(RegExp.$1),
		n_month = Number(RegExp.$2),
		n_year = Number(RegExp.$3);

	if (n_year < 100)
		n_year += (n_year < this.a_tpl.centyear ? 2000 : 1900);
	if (n_month < 1 || n_month > 12)
		return alert ("Invalid month value: '" + n_month + "'.\nAllowed range is 01-12.");
	var d_numdays = new Date(n_year, n_month, 0);
	if (n_day > d_numdays.getDate())
		return alert("Invalid day of month value: '" + n_day + "'.\nAllowed range for selected month is 01 - " + d_numdays.getDate() + ".");

	return new Date (n_year, n_month - 1, n_day);
}
// date generating function
function f_tcalGenerDate (d_date) {
	return (
		(d_date.getDate() < 10 ? '0' : '') + d_date.getDate() + "-"
		+ (d_date.getMonth() < 9 ? '0' : '') + (d_date.getMonth() + 1) + "-"
		+ d_date.getFullYear()
	);
}

// implementation
function tcal (a_cfg, idioma, a_tpl) {

	// apply default template if not specified
	if (!a_tpl) a_tpl = A_TCALDEF;
	
	//se aplica el idioma
	if(idioma=='_en') a_tpl = A_TCALDEF_EN;
	if(idioma=='_cat') a_tpl = A_TCALDEF_VAL;

	// register in global collections
	if (!window.A_TCALS) window.A_TCALS = [];
	if (!window.A_TCALSIDX) window.A_TCALSIDX = [];
	
	this.s_id = a_cfg.id ? a_cfg.id : A_TCALS.length;
	window.A_TCALS[this.s_id] = this;
	window.A_TCALSIDX[window.A_TCALSIDX.length] = this;
	
	// assign methods
	this.f_show = f_tcalShow;
	this.f_hide = f_tcalHide;
	this.f_toggle = f_tcalToggle;
	this.f_update = f_tcalUpdate;
	this.f_relDate = f_tcalRelDate;
	this.f_parseDate = f_tcalParseDate;
	this.f_generDate = f_tcalGenerDate;
	this.f_resetea = f_tcalResetea;
	
	// save received parameters
	this.a_cfg = a_cfg;
	this.a_tpl = a_tpl;
}

function f_tcalShow (d_date) {

	// find input field
	if (!this.a_cfg.controlname)
		throw("TC: control name is not specified");
	if (this.a_cfg.formname) {
		var e_form = document.forms[this.a_cfg.formname];
		if (!e_form)
			throw("TC: form '" + this.a_cfg.formname + "' can not be found");
		this.e_input = e_form.elements[this.a_cfg.controlname];
	}
	else
		this.e_input = f_getElement(this.a_cfg.controlname);

	if (!this.e_input || !this.e_input.tagName || this.e_input.tagName != 'INPUT')
		throw("TC: element '" + this.a_cfg.controlname + "' does not exist in "
			+ (this.a_cfg.formname ? "form '" + this.a_cfg.controlname + "'" : 'this document'));

	// dynamically create HTML elements if needed
	
	this.e_div = f_getElement('tcal' + this.s_id);
	if (!this.e_div) {
		this.e_div = document.createElement("DIV");
		this.e_div.id = 'tcal';
		document.body.appendChild(this.e_div);
	}
	
	// hide all calendars
	f_tcalHideAll();
	

	// generate HTML and show calendar
	this.e_icon = f_getElement(this.s_iconId);
	if (!this.f_update())
		return;

	this.e_div.style.visibility = 'visible';
	if (this.e_iframe)
		this.e_iframe.style.visibility = 'visible';

}

function f_tcalHide (n_date) {
	fecha2Auto = false;
	if (n_date){
		hoy = new Date().valueOf();
		if(this.s_id==1){ //Si es el primer calendario
			if(n_date<=hoy){ //No se aceptan fechas anteriores a hoy
				alert(this.a_tpl.anterior_a_hoy);
				return false;
			}
			fecha2Auto = true;
		} else {
			fecha_1 = document.getElementById(A_TCALS['1'].a_cfg.controlname).value;
			if(fecha_1==''){
				alert(this.a_tpl.primero_fecha_entrada);
				return false;
			}
			fecha_1 = this.f_parseDate(fecha_1).valueOf();
			if(n_date<=fecha_1){
				alert(this.a_tpl.anterior_a_entrada);
				f_fechaSalidaAuto();
				return false;
			}
		}
		this.e_input.value = this.f_generDate(new Date(n_date));
	}
	this.f_update(n_date);
	if(fecha2Auto) f_fechaSalidaAuto();
}

function f_fechaSalidaAuto(){
	fecha_1 = document.getElementById(A_TCALS['1'].a_cfg.controlname).value;
	fecha_1 = A_TCALS['1'].f_parseDate(fecha_1).valueOf();
	fecha_2 = document.getElementById(A_TCALS['2'].a_cfg.controlname).value;
	if(fecha_2 != '') fecha_2 = A_TCALS['2'].f_parseDate(fecha_2).valueOf();
	if(fecha_2=='' || (fecha_1+86400000)>=fecha_2){
		fecha_2 = new Date(fecha_1 + 86400000);
		A_TCALS['2'].f_hide(fecha_2);
		fecha_2 = fecha_2.valueOf();
		fecha_2 = '#2-'+fecha_2;
		$(fecha_2).fadeTo(600,0);
		$(fecha_2).fadeTo(10,100);
		$(fecha_2).fadeTo(600,0);
		$(fecha_2).fadeTo(10,100);
	}
}

function f_tcalToggle () {
	return this.b_visible ? this.f_hide() : this.f_show();
}

function f_tcalUpdate (d_date) {
	var d_today = this.a_cfg.today ? this.f_parseDate(this.a_cfg.today) : f_tcalResetTime(new Date());
	var d_selected = this.e_input.value == ''
		? (this.a_cfg.selected ? this.f_parseDate(this.a_cfg.selected) : d_today)
		: this.f_parseDate(this.e_input.value);
	// figure out date to display
	if (!d_date)
		// selected by default
		d_date = d_selected;
	else if (typeof(d_date) == 'number')
		// get from number
		d_date = f_tcalResetTime(new Date(d_date));
	else if (typeof(d_date) == 'string')
		// parse from string
		this.f_parseDate(d_date);
		
	if (!d_date) return false;

	// first date to display
	var d_firstday = new Date(d_date);
	d_firstday.setDate(1);
	d_firstday.setDate(1 - (7 + d_firstday.getDay() - this.a_tpl.weekstart) % 7);
	
	var a_class, s_html = '<table class="ctrl"><tbody><tr>'
		+ (this.a_tpl.yearscroll ? '<td' + this.f_relDate(d_date, -1, 'y') + ' title="Aņo anterior"><img src="' + this.a_tpl.imgpath + 'prev_year.gif" /></td>' : '')
		+ '<td' + this.f_relDate(d_date, -1) + ' title="Mes anterior" id="mesanterior"></td><th>'
		//+ '<td' + this.f_relDate(d_date, -1) + ' title="Mes anterior" id="mesanterior"><img src="' + this.a_cfg.ruta_aplicacion + '/' + this.a_tpl.imgpath + 'prev_mon.gif" /></td><th>'
		+ this.a_tpl.months[d_date.getMonth()] + ' ' + d_date.getFullYear()
		+ '</th><td' + this.f_relDate(d_date, 1) + ' title="Mes siguiente" id="messiguiente"></td>'
		//+ '</th><td' + this.f_relDate(d_date, 1) + ' title="Mes siguiente" id="messiguiente"><img src="' + this.a_cfg.ruta_aplicacion + '/' + this.a_tpl.imgpath + 'next_mon.gif" /></td>'
		+ (this.a_tpl.yearscroll ? '<td' + this.f_relDate(d_date, 1, 'y') + ' title="Aņo siguiente"><img src="' + this.a_tpl.imgpath + 'next_year.gif" /></td></td>' : '')
		+ '</tr></tbody></table><table><tbody><tr class="wd">';

	// print weekdays titles
	for (var i = 0; i < 7; i++)
		s_html += '<th>' + this.a_tpl.weekdays[(this.a_tpl.weekstart + i) % 7] + '</th>';
	s_html += '</tr>' ;

	// print calendar table
	var n_date, n_month, d_current = new Date(d_firstday);
	while (d_current.getMonth() == d_date.getMonth() ||
		d_current.getMonth() == d_firstday.getMonth()) {
	
		// print row heder
		s_html +='<tr>';
		for (var n_wday = 0; n_wday < 7; n_wday++) {

			a_class = [];
			n_date = d_current.getDate();
			n_month = d_current.getMonth();
			
			dia = n_date;
			if(dia<10) dia = '0'+dia.toString();
			mes = n_month+1;
			if(mes<10) mes = '0'+mes.toString();
			anyo = d_current.getFullYear().toString();
			fechaPaScript = anyo+mes+dia;

			// other month
			if (d_current.getMonth() != d_date.getMonth())
				a_class[a_class.length] = 'othermonth';
			// weekend
			if (d_current.getDay() == 0 || d_current.getDay() == 6)
				a_class[a_class.length] = 'weekend';
			// today
			if (d_current.valueOf() == d_today.valueOf())
				a_class[a_class.length] = 'today';
			// selected
			if (d_current.valueOf() == d_selected.valueOf())
				a_class[a_class.length] = 'selected';

			//s_html += '<td id="' + this.s_id + '-' + d_current.valueOf() + '" onclick="A_TCALS[\'' + this.s_id + '\'].f_hide(' + d_current.valueOf() + ')"' + (a_class.length ? ' class="' + a_class.join(' ') + '">' : '>') + n_date + '</td>'
			s_html += '<td id="' + this.s_id + '-' + d_current.valueOf() + '" ' + (a_class.length ? ' class="' + a_class.join(' ') + '">' : '>') + '<a class="enlaceCalendario" href="javascript:click_agenda(' + fechaPaScript + ');">' + n_date + '</a>' + '</td>'

			d_current.setDate(++n_date);
			while (d_current.getDate() != n_date && d_current.getMonth() == n_month) {
				d_current.setHours(d_current.getHours + 1);
				d_current = f_tcalResetTime(d_current);
			}
		}
		// print row footer
		s_html +='</tr>';
	}
	//enlaceHoy= 'dia=' + d_today.getDay() + '&mes=' + d_today.getMonth() + '&year=' + d_today.getYear();
	s_html += '<tr><td colspan="7"  id="tdenlacehoy"><a onclick="A_TCALS[\'' + this.s_id + '\'].f_resetea();" title="' + this.a_tpl.althoy + '" id="enlacehoy">' + this.a_tpl.textohoy + '</a></td></tr>';
	s_html +='</tbody></table>';
	
	// update HTML, positions and sizes
	this.e_div.innerHTML = s_html;
	
	return true;
}

function f_tcalResetea(){
	hoy = new Date();
	this.e_input.value = hoy.getDate() + '-' + (hoy.getMonth()+1) + '-' + hoy.getFullYear();
	this.f_update();
}

function f_getPosition (e_elemRef, s_coord) {
	var n_pos = 0, n_offset,
		e_elem = e_elemRef;

	while (e_elem) {
		n_offset = e_elem["offset" + s_coord];
		n_pos += n_offset;
		e_elem = e_elem.offsetParent;
	}
	// margin correction in some browsers
	if (b_ieMac)
		n_pos += parseInt(document.body[s_coord.toLowerCase() + 'Margin']);
	else if (b_safari)
		n_pos -= n_offset;
	
	e_elem = e_elemRef;
	while (e_elem != document.body) {
		n_offset = e_elem["scroll" + s_coord];
		if (n_offset && e_elem.style.overflow == 'scroll')
			n_pos -= n_offset;
		e_elem = e_elem.parentNode;
	}
	return n_pos;
}

function f_tcalRelDate (d_date, d_diff, s_units) {
	var s_units = (s_units == 'y' ? 'FullYear' : 'Month');
	var d_result = new Date(d_date);
	d_result['set' + s_units](d_date['get' + s_units]() + d_diff);
	if (d_result.getDate() != d_date.getDate())
		d_result.setDate(0);
	return ' onclick="A_TCALS[\'' + this.s_id + '\'].f_update(' + d_result.valueOf() + ')"';
}

function f_tcalHideAll () {
	for (var i = 0; i < window.A_TCALSIDX.length; i++)
		window.A_TCALSIDX[i].f_hide();
}	

function f_tcalResetTime (d_date) {
	d_date.setHours(0);
	d_date.setMinutes(0);
	d_date.setSeconds(0);
	d_date.setMilliseconds(0);
	return d_date;
}

f_getElement = document.all ?
	function (s_id) { return document.all[s_id] } :
	function (s_id) { return document.getElementById(s_id) };
	
// global variables
var s_userAgent = navigator.userAgent.toLowerCase(),
	re_webkit = /WebKit\/(\d+)/i;
var b_mac = s_userAgent.indexOf('mac') != -1,
	b_ie5 = s_userAgent.indexOf('msie 5') != -1,
	b_ie6 = s_userAgent.indexOf('msie 6') != -1 && s_userAgent.indexOf('opera') == -1;
var b_ieFix = b_ie5 || b_ie6,
	b_ieMac  = b_mac && b_ie5,
	b_safari = b_mac && re_webkit.exec(s_userAgent) && Number(RegExp.$1) < 500;
