// JavaScript Document
function setDateCO(cid_giornoa, cid_mesea, cid_annoa, cid_notti, cid_giornop, cid_mesep, cid_annop) {
	var giornoa = document.forms[0].elements[cid_giornoa].value;
	var mesea = document.forms[0].elements[cid_mesea].value;
	if (mesea.indexOf("0") == 0) {
	    mesea = mesea.substr(1, 2);
	}
	var annoa = document.forms[0].elements[cid_annoa].value;
	var notti = document.forms[0].elements[cid_notti].value;
	
	var monthlen = getMonthLen(parseInt(annoa), parseInt(mesea));
    
	if (notti != "--") {
	    if (parseInt(giornoa) > parseInt(monthlen)) {
	        giornoa = monthlen;
	        document.forms[0].elements[cid_giornoa].value = giornoa;
	    }
	
		var co = new Date (annoa, mesea - 1, giornoa, 12, 0, 0, 0);
        
        co.setDate(co.getDate() + parseInt(notti));
		
		var giorno_co = co.getDate();
		var mese_co = co.getMonth() + 1;
		var anno_co = co.getFullYear();

		document.forms[0].elements[cid_giornop].value = giorno_co;
		document.forms[0].elements[cid_mesep].value = mese_co;
		document.forms[0].elements[cid_annop].value = anno_co;
	} else {
	    document.forms[0].elements[cid_giornop].value = "";
		document.forms[0].elements[cid_mesep].value = "";
		document.forms[0].elements[cid_annop].value = "";
	}
}

function setDateCOS(cid_datas, cid_notti, cid_giornop, cid_mesep, cid_annop) {
	var datas = document.forms[0].elements[cid_datas].value;
	
	var giornoa = datas.substring(0,2);
	var mesea = datas.substring(3,5);
	var annoa = datas.substring(6,10);
	var notti = document.forms[0].elements[cid_notti].value;
	
	var monthlen = getMonthLen(parseInt(annoa), parseInt(mesea));

	if (notti != "--") {
	    if (parseInt(giornoa) > parseInt(monthlen)) {
	        giornoa = monthlen;
	        document.forms[0].elements[cid_giornoa].value = giornoa;
	    }
	
		var co = new Date (annoa, mesea - 1, giornoa, 12, 0, 0, 0);
        
        co.setDate(co.getDate() + parseInt(notti));
		
		var giorno_co = co.getDate();
		var mese_co = co.getMonth() + 1;
		var anno_co = co.getFullYear();

		document.forms[0].elements[cid_giornop].value = giorno_co;
		document.forms[0].elements[cid_mesep].value = mese_co;
		document.forms[0].elements[cid_annop].value = anno_co;
	} else {
	    document.forms[0].elements[cid_giornop].value = "";
		document.forms[0].elements[cid_mesep].value = "";
		document.forms[0].elements[cid_annop].value = "";
	}
}

// number of days in month
function getMonthLen(theYear, theMonth) {
    var days = new Array(31, ((theYear % 4 == 0 && theYear % 100 != 0) || theYear % 400 == 0 ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    return days[theMonth - 1];
}

