//LIBRERÍA PARA MANIPULACIÓN DE FECHAS
var daysOfWeek = new Array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var dateToolsAlert = new Array();
var yearsComboArray = new Array();

var startDate,endDate;

Date.prototype.sumaDia = function (n){
	n = (arguments.length >0)? n : 1;
	this.setDate(this.getDate() + n);
}
Date.prototype.sumaMes = function (n){
	n = (arguments.length >0)? n : 1;
	this.setMonth(this.getMonth() + n);
}
Date.prototype.sumaAnyo = function (n){
	n = (arguments.length >0)? n : 1;
	this.setFullYear(this.getFullYear() + n);
}
Date.prototype.milisegundos = function(){
	return this.getTime();
}

Date.prototype.isSunday = function(){
	if(this.getDay()==0)
		return true;
	else return false;
}
Date.prototype.isSaturday = function(){
	if(this.getDay()==6)
		return true;
	else return false;
}
Date.prototype.isSunOrSat = function(){
	if(d.isSunday() || d.isSaturday(d))
		return true;
	else return false;
}
// escribe la fecha como cadena DD/MM/AA
Date.prototype.toDDMMAA = function (){
	var datestring = ''+ ts99(this.getDate())+'/'+ts99((this.getMonth()+1))+'/'+ yearToTwoDigits('' + this.getFullYear());
	return datestring;
}
// escribe la fecha como cadena DD/MM/AAAA
Date.prototype.toDDMMAAAA = function (){
	var datestring = ''+ ts99(this.getDate())+'/'+ts99((this.getMonth()+1))+'/'+ ''+this.getFullYear();
	return datestring;
}
// escribe la fecha en formato americano como cadena AAAA/MM/DD
Date.prototype.toAAAAMMDD = function (){
	var datestring = ''+this.getFullYear() + '/' + ts99((this.getMonth()+1))+'/'+ ts99(this.getDate());
	return datestring;
}

Date.prototype.getDayNameOfWeek = function(){
	return daysOfWeek[this.getDay()];
}
Date.prototype.daysBetweenDates = function(d2){
	return ((((d2.milisegundos() - this.milisegundos())/1000)/60)/60)/24;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///// funciones para reescribir los combos de sección de anio con el rango de anios disponible //////
///////////////////////////////////////////////////////////////////////////////////////////////////
function populateYearsArray(year){
	if (yearsComboArray.length<=0 || year > yearsComboArray[yearsComboArray.length-1])
		yearsComboArray.push(year);
	
}
function replaceYearsCombo(cmb){
	var combo = document.getElementById(cmb);
	while(combo.length > 1){
		for(var i = 1; i < combo.length; i++){
			combo.remove(i);
		}
	}
	for(var j = 1; j <= yearsComboArray.length; j++)
		combo.options[j] = new Option (yearsComboArray[j-1],yearsComboArray[j-1])
}
////////////////////////////////////////////////////////////////////////////////
//// funciones para escribir fecha de incio y de fin en milisegundos y comprobar que son fechas validas
////////////////////////////////////////////////////////////////////////////////
// funciones para comprobar fechas compuestas por DÍA, MES y AÑO
// comprueba que existe fecha de inicio y, si existe, la convierte a milisegundos
function setStartDate(f){
	startDate = concatdate(f.startYear.value, f.startMonth.value,f.startDay.value);
	if (startDate){
		f.startDate.value = startDate.milisegundos();
		if (!f.startDate.value || isNaN(f.startDate.value)){
			alert(dateToolsAlert['setStartDate']);
			return false;
		}
		return true;
	}

	return false;
}
// comprueba que existe fecha de fin y, si existe, la convierte a milisegundos
function setEndDate(f){
	endDate = concatdate(f.endYear.value, f.endMonth.value,f.endDay.value);
	if (endDate){
		f.endDate.value = endDate.milisegundos();
		if (!f.endDate.value || isNaN(f.endDate.value)){//
			alert(dateToolsAlert['setEndDate']);
			return false;
		}
		return true;
	}

	return false;
}

// comprueba que la fecha de inicio es menor que la de fin
function checkDates(f){
	if((f.startDate.value - f.endDate.value)> 0){
		alert(dateToolsAlert['checkDates']);
		return false;
	}

	return true;
}

//comprueba que la fecha de fin es menor o igual a la fecha especificada. El parámetro fRef debe pasarse en formato DD/MM/AAAA
function checkEndDate(f, fRef) {
	dateRef = new Date(fRef.substring(6, 10), fRef.substring(3, 5) - 1, fRef.substring(0, 2));
	if (f.endDate.value > dateRef.getTime()) {
		alert(dateToolsAlert['checkEndDate'] + fRef);
		return false;
	}

	return true;
}

////////////////////////
//// funciones auxiliares
////////////////////////

var tst;

// f. auxiliar de setStartDate y setEndDate
function concatdate(y,m,d){
	if((y && m && d)&&(!isNaN(y)||!isNaN(m)||!isNaN(d)))
		tst = isDate (parseInt(y,10),parseInt(m,10)+1,parseInt(d,10));
	else
		tst = 1

	if (tst == 0){
		newdate = new Date (y,m,d);
		return newdate;
	}else{
		alert (getDateMsg(tst));
		return null;
	}
}

//Escribe el anio como cadena de dos dígitos
function yearToTwoDigits(y){
	sy = y.substr(2);
	return sy;
}
function newVlDate(str){ // para convertir cadenas del tipo "DD/MM/AAAA" a fechas
	var tar = str.split('/');
	var day = parseInt(tar[0],10);
	var month = parseInt(tar[1]-1,10);
	var year = parseInt(tar[2],10);
	var newdate = new Date(year, month, day);
	return newdate;
}


// escribe los enteros entre 0-99 como cadena de dos dígitos
function ts99(n){
	var nts = (n < 10)? '0'+ n : ''+ n;
	return nts;
}

///// FUNCIONES PARA HABILITAR/DESHABILITAR CONTROLES DE FECHA DE FORMULARIO //////////////
function disableDates(){
	document.getElementById('startDay').disabled =true;
	document.getElementById('startDay').className ="disabled";
	document.getElementById('startMonth').disabled =true;
	document.getElementById('startMonth').className ="disabled";
	document.getElementById('startYear').disabled =true;
	document.getElementById('startYear').className ="disabled";
	document.getElementById('startDate_label').className ="disabled";

	document.getElementById('endDay').disabled =true;
	document.getElementById('endDay').className ="disabled";
	document.getElementById('endMonth').disabled =true;
	document.getElementById('endMonth').className ="disabled";
	document.getElementById('endYear').disabled =true;
	document.getElementById('endYear').className ="disabled";
	document.getElementById('endDate_label').className ="disabled";
}
function enableInit(){
	document.getElementById('startDay').disabled =false;
	document.getElementById('startDay').className ="";
	document.getElementById('startMonth').disabled =false;
	document.getElementById('startMonth').className ="";
	document.getElementById('startYear').disabled =false;
	document.getElementById('startYear').className ="";
	document.getElementById('startDate_label').className ="";
}
function enableEnd(){
	document.getElementById('endDay').disabled =false;
	document.getElementById('endDay').className ="";
	document.getElementById('endMonth').disabled =false;
	document.getElementById('endMonth').className ="";
	document.getElementById('endYear').disabled =false;
	document.getElementById('endYear').className ="";
	document.getElementById('endDate_label').className ="";
}

/**************************************
* FUNCIONES PARA VALIDAR FECHAS
* Jonas Raoni Soares Silva
* http://www.joninhas.ath.cx
**************************************/
isDate = function(y, m, d){ //v1.0
		if(typeof y == "string" && m instanceof RegExp && d){
			if(!m.test(y)) return 1;
			y = RegExp["$" + d.y], m = RegExp["$" + d.m], d = RegExp["$" + d.d];
		}
		d = Math.abs(d) || 0, m = Math.abs(m) || 0, y = Math.abs(y) || 0;
		return arguments.length != 3 ? 1 : d < 1 || d > 31 ? 2 : m < 1 || m > 12 ? 3 : /4|6|9|11/.test(m) && d == 31 ? 4
		: m == 2 && (d > ((y = !(y % 4) && (y % 1e2) || !(y % 4e2)) ? 29 : 28)) ? 5 + !!y : 0;
};

getDateMsg = function(x){
	return x ==1 || x==2 ||x==3 ? dateToolsAlert['neddDayMonthYearMsg']
	: x == 4 ? dateToolsAlert['just30DaysMsg']
	: x == 5 ? dateToolsAlert['febJust28Msg']
	: x == 6 ? dateToolsAlert['febJust29Msg']
	: dateToolsAlert['neddDayMonthYearMsg'];
}
