if(typeof(ics)=='undefined')	ics={};

ics.datatable={};
ics.datatables={}

ics.datatable.newDatatable=function(dtName,dtUrl,dtLimit,dtTotalPages,dtSortColumn,dtSortDirection){
	ics.datatables[dtName]={page:1,url:dtUrl,data:[],limit:dtLimit,totalPages:dtTotalPages,sortColumn:dtSortColumn,sortDirection:dtSortDirection,filters:{},afterDataChange:'',beforeDataChange:''}
	ics.datatable.setSortClass(dtName,dtSortColumn,dtSortDirection);
}

ics.datatable.setFilter=function(dtName,filterName,filterValue){
	if(filterValue == ''){
		filterValue = '<RESET>';
	}
	ics.datatables[dtName].filters[filterName]=filterValue;
	ics.datatable.changePage(dtName,'goto',1,true);
}

ics.datatable.resetFilters=function(dtName){
	for(a=0;a<arguments[1].length;a++){
		if(ics.getE(arguments[1][a]).type == 'select-one'){
			ics.getE(arguments[1][a]).selectedIndex=0;	
			ics.datatables[dtName].filters[arguments[2][a]] = '<RESET>';
		}
		if(ics.getE(arguments[1][a]).type == 'text'){
			ics.getE(arguments[1][a]).value='';
			ics.datatables[dtName].filters[arguments[2][a]] = '<RESET>';
		}			
	}
	ics.datatable.changePage(dtName,'goto',1,true);
}



ics.datatable.assembleFilters=function(dtName){
	s='';
	for(key in ics.datatables[dtName].filters){
		s+='&'+key+'='+ics.datatables[dtName].filters[key];
	}
	return s;
}

ics.datatable.sort=function(dtName,dtColumn){
	ics.datatable.unsetSortClass(dtName,ics.datatables[dtName].sortColumn);
	newDir='asc';

	if(ics.datatables[dtName].sortColumn == dtColumn){
		newDir= (ics.datatables[dtName].sortDirection=='asc')?'desc':'asc';
	}
	
	data=dtName+'_page=1';
	ics.datatables[dtName].sortColumn=dtColumn;
	ics.datatables[dtName].sortDirection=newDir;
	
	data+='&'+dtName+'_sort_column='+(dtColumn);
	data+='&'+dtName+'_sort_direction='+(ics.datatables[dtName].sortDirection);
	data+=ics.datatable.assembleFilters(dtName);
	ics.setSelector(ics.getE(dtName+'_page_selector'),1);
	
	ics.datatable.setSortClass(dtName,dtColumn,newDir);
	ics.datatable.getData(dtName,data);
}

ics.datatable.setSortClass=function(dtName,dtColumn,dtDirection){
	obj=ics.getE(dtName+'_column_'+dtColumn);
	if(obj && (dtDirection=='asc' || dtDirection=='desc')){
		obj.setAttribute(ics.getClassAttrib(),'dtcolhead_'+dtDirection)
	}
}

ics.datatable.unsetSortClass=function(dtName,dtColumn){
	obj=ics.getE(dtName+'_column_'+dtColumn);
	if(obj){
		obj.setAttribute(ics.getClassAttrib(),'dtcolhead_sort');
	}
}
ics.datatable.changeRows=function(dtName,newLimit){
	ics.datatables[dtName].limit = newLimit;
	ics.datatable.changePage(dtName,'first',true);
}

ics.datatable.changePage=function(dtName,newDirection,forceChange){
	oldPage=ics.datatables[dtName].page;
	newPage=oldPage;
	switch(newDirection){
		case 'first': newPage=1; break;
		case 'previous': newPage--; break;
		case 'next': newPage++; break;
		case 'last': newPage=ics.datatables[dtName].totalPages; break;
		case 'goto': newPage=arguments[2]; break;
	}
	if((newPage==oldPage && newDirection=='first' && !arguments[3]) || newPage<1){
		if(!forceChange){
			alert('You\'re already on page 1.');
			return;
		}
	}
	if(	!arguments[3] && ((newPage==oldPage && newDirection=='last')
			|| newPage>ics.datatables[dtName].totalPages)){
		alert('You\'re already on the last page.');
		return;
	}
	
	ics.setSelector(ics.getE(dtName+'_page_selector'),newPage)
	
	data=dtName+'_page='+(newPage);
	data+='&'+dtName+'_sort_column='+(ics.datatables[dtName].sortColumn);
	data+='&'+dtName+'_sort_direction='+(ics.datatables[dtName].sortDirection);
	data+='&'+dtName+'_limit='+(ics.datatables[dtName].limit);
	data+=ics.datatable.assembleFilters(dtName);
	ics.datatable.getData(dtName,data);	
}

ics.datatable.getData=function(dtName,dtData){
	requestor=ics.getXmlRequestor();
	requestor.onreadystatechange=function(){
		if(requestor.readyState==4)
			ics.datatable.updateData(dtName,requestor);
	}
	requestor.open('POST','index.php'+ics.datatables[dtName].url,true);
	requestor.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	requestor.send(dtData);
	if(ics.datatables[dtName].progressId){
		ics.toggleDisplay('dt_'+dtName);
		ics.toggleDisplay(ics.datatables[dtName].progressId);
	}
}

ics.datatable.download=function(dtName){
	if(arguments[1]=='' || (!arguments[1]))
		arguments[1]='csv';
	data=dtName+'_page='+(1);
	data+='&'+dtName+'_sort_column='+(ics.datatables[dtName].sortColumn);
	data+='&'+dtName+'_sort_direction='+(ics.datatables[dtName].sortDirection);
	data+=ics.datatable.assembleFilters(dtName);
	data+='&'+dtName+'_download=on&'+dtName+'_format='+arguments[1];
	newUrl='index.php'+ics.datatables[dtName].url+data;
	location.href=newUrl;
}


ics.datatable.updateData=function(dtName,newData){
	if(ics.datatables[dtName].beforeDataChange!=''){
		eval(ics.datatables[dtName].beforeDataChange);
	}
	//alert(newData.responseText);
	eval(newData.responseText);
	data=ics.datatables[dtName].data;
	
	selector=ics.getE(dtName+'_page_selector');
	while(selector.options.length > 0){
		selector.remove(0);
	}
	for(a=1;a<=ics.datatables[dtName].totalPages;a++){
		if(ics.datatables[dtName].page == a){
			selector.options.add(new Option('Page '+a+' of '+ics.datatables[dtName].totalPages,a,true));
		}else{
			selector.options.add(new Option('Page '+a+' of '+ics.datatables[dtName].totalPages,a));
		}
	}
	
	// step i: figure out how many rows we actually need
	totalRows=0;
	
	//alert('figuring out total rows: '+data.length+'/'+data[0].length+'/'+((data.length * data[0].length) - 1));
	//totalRows = (data.length * data[0].length) - 1;	
	totalRows=data.length;

	// step 2: go through the table and rebuild the rows using dom
	dataStartRow=0;
	dataEndRow=0;
	rowOffset = 2;
	numCurrentRows=0;
	hasNoDataRow=false;
	noDataRow=false;
	hasRows=false;
	table=ics.getE('dt_'+dtName);

	
	for(a=1;a<table.rows.length;a++){
		className=table.rows[a].getAttribute(ics.getClassAttrib());
		if(table.rows[a].cells[0].getAttribute(ics.getClassAttrib()) == 'dt_nodata'){
			hasNoDataRow=table.rows[a];
		}
		if(className == 'dtrow1' || className == 'dtrow'){
			dataStartRow=a;
			a=table.rows.length;
			hasRows=true;
		}
	}
	rowOffset += ((hasNoDataRow)?1:0);
	
		
	// if we didn't find a proper start row, set to the first possible row:
	//alert(dataStartRow+'/'+dataEndRow+'/'+hasNoDataRow);
	if(dataStartRow == 0){
		dataStartRow = rowOffset;
	}
	//alert(dataStartRow+'/'+dataEndRow+'/'+hasNoDataRow);
	// step 2b: find the end of the data rows
	
	for(a=(table.rows.length - 1);a>=0;a--){
		className=table.rows[a].getAttribute(ics.getClassAttrib());
		if(className == 'dtrow1' || className=='dtrow'){
			dataEndRow=a;
			a=(-1);
			hasRows=true;
			
		}
	}
	
	if( dataEndRow == 0){
		dataEndRow= rowOffset;
	}
	//alert(dataStartRow+'/'+dataEndRow+'/'+hasNoDataRow);
	if(hasRows){
		dataEndRow++;
		numCurrentRows=dataEndRow - dataStartRow;
	}else{
		numCurrentRows=0
	}
	//alert(dataStartRow+'/'+dataEndRow+'/'+hasNoDataRow);
	//return;
	
	// if there's just no data, just turn off all the rows
	//
	if(totalRows == 0 && numCurrentRows > 0){
		for(a=(numCurrentRows + 1);a>totalRows;a--){
			row=ics.getE(dtName+'_'+(a)+'_0');
			if(row)
				row.style.display='none';
		}
		if(ics.datatables[dtName].progressId){
			ics.toggleDisplay(ics.datatables[dtName].progressId);
			ics.toggleDisplay('dt_'+dtName);
		}
		if(ics.datatables[dtName].afterDataChange!=''){
			//alert('trying to call: '+ics.datatables[dtName].afterDataChange);
			eval(ics.datatables[dtName].afterDataChange);
		}
		return;
	}		
	
	
	// step 2c: find the number of columns to create
	numCols=table.rows[1].cells.length;
	//alert(numCols);
	//return
	
	// step 3: modify the number of rows... somehow >__<

	//alert('current rows versus total needed: '+numCurrentRows + '/' + totalRows);
	//return
	
	if(numCurrentRows < totalRows){
		//alert('adding rows. end row: '+dataEndRow);
		//alert('current rows versus total needed: '+numCurrentRows + '/' + totalRows+'/'+dataStartRow+'/'+dataEndRow);
		rowsAdded=0;
		for(a=numCurrentRows;a<totalRows;a++){
			
			//alert('inserting row after '+(dataEndRow + rowsAdded + 1));
			//alert('adding row '+(dataEndRow + rowsAdded));
			//return
			row=table.tBodies[0].insertRow(dataEndRow + rowsAdded);
			row.setAttribute(ics.getClassAttrib(),((((dataEndRow + rowsAdded) % 2) == 1)?'dtrow':'dtrow1'));
			//alert('trying to add '+dtName+'_'+(dataEndRow + rowsAdded )+'_0');
			row.setAttribute('id',dtName+'_'+(dataEndRow + rowsAdded - rowOffset + 1)+'_0');
			for(b=0;b<numCols;b++){
				col=row.insertCell(-1);
				col.setAttribute(ics.getClassAttrib(),'dtcol');
				col.setAttribute('id',dtName+'_'+(dataEndRow + rowsAdded - rowOffset + 1)+'_0_'+b);
			}
			rowsAdded++;
		}
	}
	else if(numCurrentRows > totalRows){
		// find the rows and turn them off
		//alert('turning off rows, starting on '+(numCurrentRows)+' and ending when a=='+totalRows);
		for(a=(numCurrentRows);a>(totalRows);a--){
			//alert('trying to turn off '+dtName+'_'+(a)+'_0');
			row=ics.getE(dtName+'_'+(a)+'_0');
			if(row)
				row.style.display='none';
		}
	}

	// loop through data rows
	if(ics.datatables[dtName].limit == 0){

		/* 
		do complicated stuff. Since there's no row limit imposed on this table,
		there might be more or less data sent than there's rows for in the html. Therefore
		we need to add or remove table rows until the # matches. Oy vey!
		*/
		

		
		if(data.length > 0){
			//alert('figuring out total rows: '+data.length+'/'+data[0].length+'/'+((data.length * data[0].length) - 1));
			//totalRows = (data.length * data[0].length) - 1;	
			totalRows=data.length;
			
			// step 2: go through the table and rebuild the rows using dom
			dataStartRow=0;
			dataEndRow=0;
			rowOffset = 2;
			numCurrentRows=0;
			hasNoDataRow=false;
			noDataRow=false;
			hasRows=false;
			table=ics.getE('dt_'+dtName);
			//alert('all rows in table: '+table.rows.length);
			// step 2a: find the start of data rows
			
			
			
			if(hasNoDataRow){
				hasNoDataRow.style.display='none';
			}
			//alert('all rows added. There are now : '+table.rows.length+' to fit '+totalRows+' rows of data. '+rowsAdded+' rows were added');
			// step 4: the table is ready, now put the data in
			//alert('ok, ready for full data: '+data.length);
			for(a=0;a<data.length;a++){
				for(b=0;b<data[a].length;b++){
					obj=ics.getE(dtName+'_'+(a + 1)+'_'+b);
					if(obj)
						if(obj.style)
							obj.style.display='';
					for(cellId in data[a][b]){
						cellObj=ics.getE(cellId);
						if(cellObj)
							cellObj.innerHTML=data[a][b][cellId];
					}
				}
			}		
		}
		else
		{
			table=ics.getE('dt_'+dtName);
			for(a=1;a<table.rows.length;a++){
				className=table.rows[a].getAttribute(ics.getClassAttrib());
				if(table.rows[a].cells[0].getAttribute(ics.getClassAttrib()) == 'dt_nodata'){
					hasNoDataRow=table.rows[a];
				}
				if(className == 'dtrow1' || className == 'dtrow'){
					table.rows[a].style.display='none';	
				}
			}

		}
	}
	else{
		
		for(a=0;a<ics.datatables[dtName].limit;a++){
			// loop through table rows
			if(data[a]){
				for(b=0;b<data[a].length;b++){
					// check to see if there are fewer rows in the data set than in the html
					if(a>data.length){
						obj=ics.getE(dtName+'_'+(a + 1 ) +'_'+b);
						if(obj)
							obj.style.display=none;
					}
					else{
						obj=ics.getE(dtName+'_'+(a + 1 )+'_'+b);
						if(obj)
							if(obj.style)
								obj.style.display='';
						// loop through the cells and replace the contents :D
						for(cellId in data[a][b]){
							cellObj=ics.getE(cellId);
							if(cellObj)
								cellObj.innerHTML=data[a][b][cellId];
						}
					}
				}
			}else{
				foundRow=true;
				rowCounter=0;
				while(foundRow){
					obj=ics.getE(dtName+'_'+(a + 1 ) +'_'+rowCounter);
					if(obj){
						obj.style.display='none';
					}else{
						foundRow=false;
					}
					rowCounter++;
				}
			}
		}
	}
	if(ics.datatables[dtName].progressId){
		ics.toggleDisplay(ics.datatables[dtName].progressId);
		ics.toggleDisplay('dt_'+dtName);
	}
	if(ics.datatables[dtName].afterDataChange!=''){
		//alert('trying to call: '+ics.datatables[dtName].afterDataChange);
		eval(ics.datatables[dtName].afterDataChange);
	}

}
