function TableCal(mainId)
{
	this.mainId = mainId;
	this.request = null;
	this.sizeControl = null;
	this.resultset = null;
	this.resultsTab = null;
	TableCal.instances[ this.mainId ] = this;
}

TableCal.instances = new Array();
TableCal.activeInstance = null;

TableCal.prototype.init = function(target, months, weekdays, ws, sourceId, goback, gocal, golist)
{
	this.container = document.getElementById( target );
	if( !this.container ) return;

	this.months = months;
	this.weekdays = weekdays;
	this.weekStarts = ws;
	this.sourceId = sourceId;
	this.goback = goback;
	this.mode = "calendar";
	this.gocal = gocal;
	this.golist = golist;
	
	this.waitScreen = document.createElement( "DIV" );
	this.setClass( this.waitScreen, "waiter" );
	setEventHandler( window, "resize", function() { if( TableCal.activeInstance != null ) TableCal.activeInstance.onWindowResize(); } );
	
	this.top = document.createElement( "DIV" );
	this.top.id = this.mainId;

	var today = new Date();
	
	this.current = {
		d : today.getDate(),
		m : today.getMonth() + 1,
		y : today.getFullYear()
	};
		
	this.monthyear = document.createElement( "DIV" );
	this.setClass( this.monthyear, "labelMonthYear" );
	this.top.appendChild( this.monthyear );
	
	var i = ws;
	
	for( var j = 0; j < 7; j ++ ) {
		var div = document.createElement( "DIV" );
		this.setClass( div, "weekdayName" );
		div.innerHTML = weekdays[i];
		
		if( j == 6 )
			div.style.borderRight = "none";
			
		this.top.appendChild( div );
		
		if( ++i >= this.weekdays.length )
			i = 0;
	}
	
	this.dayMatrix = new Array();
	
	for( var j = 0; j < 6; j ++ ) {
		this.dayMatrix[ j ] = new Array();
		
		for( var i = 0; i < 7; i ++ ) {
			this.dayMatrix[ j ][ i ] = document.createElement( "DIV" );
			this.top.appendChild( this.dayMatrix[ j ][ i ] );
		}
	}

	this.top.appendChild( this.waitScreen );
	this.container.appendChild( this.top );
	
	this.eventsList = document.createElement( "DIV" );
	this.setClass( this.eventsList, "eventsList" );
	this.eventsList.style.display = "none";	
	this.container.appendChild( this.eventsList );
		
	this.modeSwitcher = document.createElement( "A" );
	this.setClass( this.modeSwitcher, "archLink" );
	this.modeSwitcher.innerHTML = this.golist;
	this.modeSwitcher.href = "javascript:TableCal.instances['" + this.mainId + "'].onChangeMode()";
	this.container.appendChild( this.modeSwitcher );
	
	this.query( this.current.m, this.current.y );	
}

TableCal.prototype.query = function(month, year)
{
	if( this.request != null ) return;

	if (window.XMLHttpRequest)
		this.request = new XMLHttpRequest();
	else if (window.ActiveXObject)
	{
		try {
			this.request = new ActiveXObject("Msxml2.XMLHTTP")
		} catch (e) {
			try{
			        this.request = new ActiveXObject("Microsoft.XMLHTTP")
			} catch (e) {
			        return;
			}
		}
	} else {
		return;
	}
	
	this.waitScreen.style.display = "block";
	this.onWindowResize();
	
	TableCal.activeInstance = this;
	this.visibleMonth = month;
	this.visibleYear = year;
	this.request.onreadystatechange = function() { TableCal.activeInstance.onQueryResponse(); };
    this.request.open( "POST", "/php/agenda.php" );
    this.request.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
    this.request.send( "m=" + month + "&y=" + year + "&s=" + this.sourceId );
    
    this.sizeControl = window.setInterval( function() { if( TableCal.activeInstance != null ) TableCal.activeInstance.onWindowResize(); }, 200 );
}

TableCal.prototype.onWindowResize = function()
{
	var xy = getPageCoords( this.top );
	this.waitScreen.style.left = xy.x + "px";
	this.waitScreen.style.top = xy.y + "px";
	
	if( this.eventsList.style.display == "block" ) {
		if( this.eventsList.offsetHeight > 20 )
			this.waitScreen.style.height = (this.eventsList.offsetHeight + 20) + "px";
	} else {
		this.waitScreen.style.height = "";
	}
}

TableCal.prototype.onQueryResponse = function()
{
    if( (this.request.readyState == 4) &&
                ((this.request.status == 200) || (window.location.href.indexOf("http")==-1)) )
    {
        var sr = this.request.responseText;

        try {
            var structuredAnswer = sr.parseJSON(null);            
            this.draw( structuredAnswer );
        } catch( exception ) {
        }

		window.clearInterval( this.sizeControl );
		this.waitScreen.style.display = "none";
        this.request = null;
		TableCal.activeInstance = null;
		this.sizeControl = null;
        return true;
    }
}

TableCal.prototype.setClass = function(el, name)
{
	if( el.className !== undefined )
		el.className = name;
	else if( el.getAttribute )
		el.setAttribute( "class", name );
}

TableCal.prototype.getClass = function(el)
{
	if( el.className !== undefined )
		return el.className;
	else if( el.getAttribute )
		return el.getAttribute( "class" );

	return "";
}

TableCal.prototype.makeKey = function(day, month, year)
{
	var omonth = new String( month );
	
	if( month < 10 )
		omonth = "0" + new String( month );
		
	var oday = new String( day );
	
	if( day < 10 )
		oday = "0" + new String( day );
	
	var key = new String( year ) + "-" + omonth + "-" + oday + " 00:00:00";

	return key;
}

TableCal.prototype.draw = function(resultset)
{
	var month = new Number( resultset.month );
	var year = new Number( resultset.year );
	
	this.resultset = resultset;
	
	var currentDate = new Date();
	var baseDate = new Date()
	baseDate.setFullYear( year, month - 1, 1 );
	
	var mback = month - 1;
	var yback = year;
	var mforth = month + 1;
	var yforth = year;
	
	if( mback <= 0 ) {
		mback = 12;
		yback --;
	}
	
	if( mforth > 12 ) {
		mforth = 1;
		yforth ++;
	}
	
	this.monthyear.innerHTML = "<A class=\"goMonthBack\" href=\"javascript:TableCal.instances['" + 
							   this.mainId + 
							   "'].query(" + mback + 
							   "," + yback +
							   ");\">&nbsp;</A><SPAN class=\"titleMonthYear\">" +
							   this.months[ month - 1 ] + 
							   " " + year +
							   "</SPAN><A class=\"goMonthForth\" href=\"javascript:TableCal.instances['" + 
							   this.mainId + 
							   "'].query(" + mforth + 
							   "," + yforth +
							   ");\">&nbsp;</A>";
	
	while( baseDate.getDay() != this.weekStarts ) { // sunday == 0
		baseDate.setTime( baseDate.getTime() - (24 * 60 * 60 * 1000) );
	}

	if( this.mode == "calendar" ) {
		for( var j = 0; j < 6; j ++ ) {
			for( var i = 0; i < 7; i ++ ) {
				this.setClass( this.dayMatrix[ j ][ i ], "monthDay" );
				this.dayMatrix[ j ][ i ].style.display = "";
	
				var key = this.makeKey( baseDate.getDate(), baseDate.getMonth() + 1, baseDate.getFullYear() );0
				
				if( resultset.rows[ key ] != null ) {
					this.dayMatrix[ j ][ i ].innerHTML = "<A href=\"javascript:TableCal.instances['" +
														 this.mainId + 
														 "'].onChoose('" + key + "');\">" + 
														 baseDate.getDate() + 
														 "</A>";
				} else {
					this.dayMatrix[ j ][ i ].innerHTML = "<span>" + new String( baseDate.getDate() ) + "</span>";
				}
	
				if( (baseDate.getMonth() == (this.current.m - 1)) &&
					(baseDate.getDate() == this.current.d) &&
					(baseDate.getFullYear() == this.current.y) ) {
					this.setClass( this.dayMatrix[ j ][ i ], "selectedMonthDay" );
				} else if( baseDate.getMonth() != (month - 1) ) {
					this.setClass( this.dayMatrix[ j ][ i ], "otherMonthDay" );
				}
				
				if( i == 6 ) {
					this.dayMatrix[ j ][ i ].style.borderRight = "none";
				}
				
				if( j == 5 ) {
					this.dayMatrix[ j ][ i ].style.borderBottom = "none";
				}
	
				baseDate.setTime( baseDate.getTime() + (24 * 60 * 60 * 1000) );
			}
		}
		
		this.modeSwitcher.innerHTML = this.golist;
		this.modeSwitcher.style.display = "block";
		this.eventsList.style.display = "none";
		this.top.style.height = "";
	} else if( this.mode == "list" ) {
		for( var j = 0; j < 6; j ++ ) {
			for( var i = 0; i < 7; i ++ ) {
				this.setClass( this.dayMatrix[ j ][ i ], "monthDay" );
				this.dayMatrix[ j ][ i ].style.display = "none";
			}
		}
		
		this.eventsList.innerHTML = "";
		isfirst = true;
		
		for( var day = 1; day <= 31; day ++ ) {
			var key = this.makeKey( day, month, year );
			if( this.resultset.rows[ key ] != null ) {
				if( !isfirst ) {
					var br = document.createElement( "DIV" );
					br.style.display = "block";
					br.style.clear = "both";
					br.style.height = "20px";
					br.innerHTML = "&nbsp;";
					this.eventsList.appendChild( br );
				}
				this.addDay( this.eventsList, key, this.resultset.rows[ key ] );
				isfirst = false;
			}
		}
				
		this.eventsList.style.display = "block";
		this.top.style.height = "20px";
		this.modeSwitcher.innerHTML = this.gocal;
		this.modeSwitcher.style.display = "";
	}
}

TableCal.prototype.addDay = function(target, key, events)
{
	var title = document.createElement( "h3" );
	title.innerHTML = TableCal.formatDate( "d/m/y", TableCal.parseDate( "y-m-d", key ) );
	title.style.marginBottom = "6px";
	target.appendChild( title );
	
	for( var j = 0; j < events.length; j ++ ) {
		var cell = document.createElement( "DIV" );
		cell.innerHTML = "<A class=\"objLink\" href=\"/" + events[j].ob_id + ",Incontro.html\">" + events[j].title + "</A>";
		target.appendChild( cell );
	}
}

TableCal.prototype.onChoose = function(key)
{
	var events = this.resultset.rows[ key ];
	
	if( events == null ) return;
	if( events === undefined ) return;
	if( events.length <= 0 ) return;
	
	this.top.style.display = "none";
	this.resultsTab = document.createElement( "DIV" );

	this.addDay( this.resultsTab, key, events );	
	
	var back = document.createElement( "A" );
	this.setClass( back, "archLink" );
	back.href = "javascript:TableCal.instances['" + this.mainId + "'].onCloseResults()";
	back.innerHTML = this.goback;
	this.resultsTab.appendChild( back );

	this.container.appendChild( this.resultsTab );
	this.modeSwitcher.style.display = "none";
}

TableCal.prototype.onChangeMode = function()
{
	if( this.mode == "calendar" )
		this.mode = "list";
	else
		this.mode = "calendar";

	this.query( this.visibleMonth, this.visibleYear );
}

TableCal.prototype.onCloseResults = function()
{
	this.container.removeChild( this.resultsTab );
	this.resultsTab = null;
	this.top.style.display = "";
	this.modeSwitcher.style.display = "block";
}

TableCal.formatDate = function(fmt, x)
{
	var res = "";
	
	for( j = 0; j < fmt.length; j ++ ) {
		switch( fmt.charAt( j ) ) {
			case "d"	:
				res += ((x.d < 10) ? "0" : "") + x.d;
				break;

			case "m"	:
				res += ((x.m < 10) ? "0" : "") + x.m;
				break;

			case "y"	:
				res += x.y;
				break;
				
			default:
				res += fmt.charAt( j );
				break;
		}
	}
	
	return res;		
}

TableCal.parseDate = function(fmt, t)
{
	var value = t;
	var index = 0;
	var buff = "";
	var res = { d:0, m:0, y:0 };
	
	if( (value != null) && (value !== undefined) && (value != "") ) {
		for( j = 0; j < fmt.length; j ++ ) {
			switch( fmt.charAt( j ) ) {
				case "d"	:
					buff = value.charAt( index++ );
					buff += value.charAt( index++ );
					res.d = new Number( buff );
					break;
	
				case "m"	:
					buff = value.charAt( index++ );
					buff += value.charAt( index++ );
					res.m = new Number( buff );
					break;
	
				case "y"	:
					buff = value.substr( index, 4 );
					index += 4;
					res.y = new Number( buff );
					break;
					
				default:
					index ++;
					break;
			}
		}
	}
	
	return res;
}
