// Validations for Calender Control.

function Calender(calenderId, curYear, adj){
	// Will hold the calender id prefix.
	var calId = calenderId; 
	
	// Current Year. In case user inputs invalid date, this will be restored.
	var currentYear = curYear;
	
	// adjust in future date
	var adjust = 0;
	if ( adj ) adjust = adj;

	// maxYear. The maximum year allowed.
	var maxYear = currentYear + adjust;
	this.init = initializeControl;
	this.getId = getControlId;
	this.adjust = adjustDays;
	this.populate = populateDays;
	
	function initializeControl(){
		var theDay = getControlId( "theDay" );
		var theMonth = getControlId( "theMonth" );
		theYear = getControlId( "theYear" );
		currentYear = theYear.value; // Current Date
		adjustDays(); 
		theMonth.onchange = adjustDays;
		theYear.onchange = adjustDays;
	}
	
	function getControlId( ctrl ){
		return document.getElementById(calId + "_" + ctrl);	
	}
	
	function adjustDays(){
		var monthNo = getControlId( "theMonth" ).value;
		var theYear	= getControlId( "theYear" );
		var re		= /^\d*$/
		
		if(re.test( theYear.value)){
			if ( theYear.value > 1900 && theYear.value <= maxYear ){
				currentDate = theYear.value;	
			}
			else{
				theYear.value = currentDate;	
			}
		}
		else{
			theYear.value = currentDate;
		}
		var isLeap = theYear.value % 4 == 0 ? true : false;
		
		if(monthNo == 2){
			if (isLeap) populateDays(29); // in leap year, feb is of 29 days
			else  populateDays(28); // its of 28 days otherwise.
		}
		else if(monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11){
			populateDays(30); // April(4), June(6), September(9), November(11) are of 30 days.
		}
		else{
			populateDays(31); // All others are of 31 days.
		}
	}
	
	function populateDays(no){
		theDay 	= getControlId( "theDay" );
		var diff = theDay.options.length - no;
	
		if (diff > 0){ // There are more days in dropdown than needed. Remove unwanted!
			for(var i=0; i < diff; i++){
				theDay.remove( theDay.options.length - 1 );	
			}
		}
		else if( diff < 0 ){ // There are less days. Add Needed!
			diff = -diff;
			for(var i=diff; i > 0; i--){
				theDay.options[ theDay.options.length ] = new Option( theDay.options.length + 1, theDay.options.length + 1 );
			}
		}
	}
}
