var oldLink = null;

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

var sCampoComparacion;
var oCampoComparacion;

function setActiveStyleSheet(link, title) {
	
	var i, a, main;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true;
			if(a.getAttribute("title") == title) a.disabled = false;
			
		}
	}
	if (oldLink) oldLink.style.fontWeight = 'normal';
	
	oldLink = link;
	link.style.fontWeight = 'bold';
	
	return false;
}

function selected(cal, date) {
	
	if(oCampoComparacion.value==""){
		cal.sel.value = date; 
	}else{
		
		aux1 = date;
		aux2 = oCampoComparacion.value;
		f1 = new Date(aux1.substring(6,10),aux1.substring(3,5)-1,aux1.substring(0,2));
		f2 = new Date(aux2.substring(6,10),aux2.substring(3,5)-1,aux2.substring(0,2));
			
		switch(iTipoComparacion){
		
		case 1:
			if(f2<f1){
				//alert("La fecha de inicio ha de ser anterior o igual a la fecha de fin");
				return false;
			}else{
				cal.sel.value = date;
				return true;
			}
			break;
		case 2:
			if(f1<f2){
				//alert("La fecha de inicio ha de ser anterior o igual a la fecha de fin");
				return false;
			}else{
				cal.sel.value = date;
				return true;
			}		
			break;
		
		}
		
	}
	
}

function borrarValor(cal) {
	
	cal.sel.value = ""; 
	
}

function closeHandler(cal) {
	
	cal.hide();
	//  cal.destroy();
  	calendar = null;
}

function showCalendar(id, format, campoComparacion, tipoComparacion) {

	var el = document.getElementById(id);
	
	oCampoComparacion = document.getElementById(campoComparacion);
	
	iTipoComparacion = tipoComparacion;
	
	if (calendar != null) {
	
		calendar.hide();
	}else{
	
		var cal = new Calendar(true, null, selected, closeHandler, borrarValor);

		calendar = cal;
		
		cal.setRange(1900, 2070);
		cal.create();
	}

	calendar.setDateFormat(format);
	calendar.parseDate(el.value);
	calendar.sel = el;
	
	calendar.showAtElement(el, "Br");

	return false;
}

function isDisabled(date) {
	
	var today = new Date();
	return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
	
}

function flatSelected(cal, date) {

	var el = document.getElementById("preview");
	el.innerHTML = date;
	
}

function showFlatCalendar() {
	
	var parent = document.getElementById("display");
	
	var cal = new Calendar(true, null, flatSelected);
	
	cal.weekNumbers = false;
	
	cal.setDisabledHandler(isDisabled);
	cal.setDateFormat("%A, %B %e");
	
	cal.create(parent);
	
	cal.show();
}
