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){
	ics.datatables[dtName].filters[filterName]=filterValue;
	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.changePage=function(dtName,newDirection){
	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){
		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+=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));
		}
	}

	// 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!
		*/
		
		// step i: figure out how many rows we actually need
		totalRows=0;
		if(data.length > 0){
			totalRows = (data.length * data[0].length) - 1;	
		}
		//alert('total rows in returned data: '+totalRows);
		
		// step 2: go through the table and rebuild the rows using dom
		dataStartRow=1;
		dataEndRow=0;
		numCurrentRows=0;
		table=ics.getE('dt_'+dtName);
		//alert('all rows in table: '+table.rows.length);
		// step 2a: find the start of data rows
		for(a=0;a<table.rows.length;a++){
			className=table.rows[a].getAttribute(ics.getClassAttrib());
			if(className == 'dtrow1' || className == 'dtrow'){
				dataStartRow=a;
				a=table.rows.length;
			}
		}
		
		
		// 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);
			}
		}
		numCurrentRows=dataEndRow - dataStartRow;
		
		// if there's just no data, just turn off all the rows
		//alert('current rows versus total needed: '+numCurrentRows + '/' + totalRows);
		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[dataStartRow].cells.length;
		//alert(numCols);
		
		// step 3: modify the number of rows... somehow >__<
		//
		if(numCurrentRows < totalRows){
			rowsAdded=0;
			for(a=numCurrentRows;a<totalRows;a++){
				row=table.tBodies[0].insertRow((dataEndRow + rowsAdded + 1));
				row.setAttribute(ics.getClassAttrib(),((((dataEndRow + rowsAdded) % 2) == 1)?'dtrow':'dtrow1'));
				//alert('trying to add '+dtName+'_'+(dataEndRow + rowsAdded )+'_0');
				row.setAttribute('id',dtName+'_'+(dataEndRow + rowsAdded )+'_0');
				for(b=0;b<numCols;b++){
					col=row.insertCell(-1);
					col.setAttribute(ics.getClassAttrib(),'dtcol');
					col.setAttribute('id',dtName+'_'+(dataEndRow + rowsAdded )+'_0_'+b);
				}
				rowsAdded++;
			}
		}
		else if(numCurrentRows > totalRows){
			// find the rows and turn them off
			//alert('turning off rows, starting on '+(numCurrentRows + 1)+' and ending when a=='+totalRows);
			for(a=(numCurrentRows + 1);a>(totalRows + 1);a--){
				//alert('trying to turn off '+dtName+'_'+(a)+'_0');
				row=ics.getE(dtName+'_'+(a)+'_0');
				if(row)
					row.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{
		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);
	}

}
