//TODO: refactoring, make code more flexible and add config for js
var url_path = "/";
//var url_path = '/mp/147/projuve/web/';

if (!Array.prototype.indexOf){
   Array.prototype.indexOf = function(elt /*, from*/){
	   var len = this.length;
       var from = Number(arguments[1]) || 0;
       from = (from < 0) ? Math.ceil(from) : Math.floor(from);
       if (from < 0)
           from += len;
       for (; from < len; from++){
         if (from in this && this[from] === elt)
           return from;
           }
       return -1;
     };
   }
     


function map(func,list){
	ret = [];
	for(li in list){
		ret[ret.length] = func(list[li]);
	}
	return ret;
}

function filter(func,list){
	ret = [];
	for(li in list){
		if(func(list[li]) == true)
			ret[ret.length] = list[li];
	}
	return ret;
}

function reduce(func,list){
	last = new Object();
	if(list.length <= 1) return;
	if(list.length == 2) return func(list[0],list[1]);

	last = list[0];
	for(var li = 1;li < list.length;li++){
		last = func(last,list[li]);
	}
	return last;
}

function newElem(elem, attribs, inner){
	var e = document.createElement(elem)
	if (attribs) for (i in attribs){
		e.setAttribute(i, attribs[i])
		if(inner)
			e.innerHTML = inner
		}
	return e
	}
	
function mappend(elem, what){
	for(i=0; i<what.length; i++)
		elem.appendChild(what[i])
	}
	
// Some helper functions to make shortcuts

function liveGrid(liveupdateurl){

	this.updateUrl = liveupdateurl
	this.tableClass = 'livetable'
	this.id = 'livetable'
	
	this.decorationHooks = {}
	
	// Table elements and shortcuts	
	this.htmlRows = []
	this.columns = {}
	this.parentTbody = newElem("tbody")
	this.htmlHead = newElem("thead")
	this.htmlTable = newElem("table", {"id":this.id, "class":"livegrid"})
	mappend(this.htmlTable, [this.htmlHead, this.parentTbody])
	
	this.liveContainerId = "livecontainer" 
	
	this.updateForm = document.getElementById('liveupdateform');
	
	this.reinitTable = function(){
		this.parentTbody = newElem("tbody")
		this.htmlHead = newElem("thead")
		this.htmlTable = newElem("table", {"id":this.id, "class":"livegrid"})
		mappend(this.htmlTable, [this.htmlHead, this.parentTbody])
		}
	
	this.hasDecorationHook = function (columnName) {
		return (this.decorationHooks[columnName]) && 
			(typeof(this.decorationHooks[columnName])=='function')
		}
		
	this.applyDecorationHook = function (columnName, columnValue){
		return (this.hasDecorationHook(columnName))?
			(this.decorationHooks[columnName](columnValue)):
			columnValue
		}
	
	this.htmlRow = function (json_row){
		var htmlcontainer = newElem("tr");
		for(var i in json_row){
			//alert(i);
			//if(i == 'message') alert(json_row.toString());
			var el = newElem("td", {"class":("td-"+i)}, this.applyDecorationHook(i, json_row[i]))
			//alert("after")
			htmlcontainer.appendChild(el)
		
		}
		return this.decorateRow(htmlcontainer)
		}
		
	this.decorateRow = function (row){
		if(this.rowCounter)
			row.className = (this.rowCounter % 2 == 0)?"tr-even":"tr-odd"
		return row
		}
	
	this.removeRow = function(html_row){
		with (this.htmlRows)
			splice(indexOf(html_row), 1)
		this.parentTbody.removeChild(html_row)
		}
		
	this.makeHeader = function(json_row){
		var htmlcontainer = newElem("tr");
		for(var i in json_row){
			var th = newElem("th", {"class":("th-"+i)});
			if(this.sortables.indexOf(i) != -1)
				th.appendChild(this.createSortLink(i, json_row[i]));
			else
				th.innerHTML = "<span class='th-inner'>"+json_row[i]+"</span>";
			htmlcontainer.appendChild(th);
			}
		return htmlcontainer
		}
		
    this.pageRibbon = function(){
		var f = this.updateForm
		var page = parseInt(f.page.value)
		var pagescnt = parseInt(f.pagescnt.value)
		var width = 9 // heh, must be odd
		var half = (width-1)/2
		var on_right = ((pagescnt-page) >= half) ? half : (pagescnt - page);
		var on_left = (page >= half) ? half : page
		if((on_left<half) && (pagescnt>half)) on_right = on_right + half - on_left
		// IE does not understand how to format generated lists!
		var res_ul = newElem('div', {"class":"pagenav", "style":"font-size:11px;font-weight:bold"});
		// on left
		res_ul.appendChild(newElem('p'));
		var style =  'style="text-decoration:none;color:#369;font-weight:bold;font-size:11px"';
		var selected = 'style="text-decoration:none;color:#036;background:#bacaff;font-weight:bold;font-size:11px"';
                if(on_left > 0){
                        mappend(res_ul, [newElem('span', {'class':''},
                        '<a href="" onclick="document.liveupdateform.page.value=0; '+
                        'liveUpdate(); return false" title="First page" '+style+'>&lt;&lt;</a>'),
                        newElem('span', {'class':''}, '&nbsp;<a href="" onclick="document.liveupdateform.page.value='+
                        (page-1)+'; liveUpdate(); return false" title="Previous page" '+style+'>&lt;</a>')])
                }
		// pages
                for(var i=(page - on_left); i <= (page + on_right - 1); i++){
                if(i == (page))
                        var span = newElem('span', {'class':'selected'}, '<a href="" title="Selected Page" '+
					' onclick="document.liveupdateform.page.value='
                                        +(i)+'; liveUpdate(); return false" '+selected+'>&nbsp;'+(i+1)+'&nbsp;</a>')
                else
                        var span = newElem('span', {'class':''}, '<a href="" title="Go to page '+
                                        (i+1)+'" onclick="document.liveupdateform.page.value='
                                        +(i)+'; liveUpdate(); return false" '+style+'>&nbsp;'+(i+1)+'&nbsp;</a>')
                        res_ul.appendChild(span)
                }
		// right
                if(on_right > 1){
	                mappend(res_ul, [newElem('span', {'class':''},
                        '&nbsp;<a href="#" onclick="document.liveupdateform.page.value='
                        +(page+1)+'; liveUpdate(); return false" title="Next page" '+style+'>&gt;</a>'),
                        newElem('span', {'class':''},
                        '&nbsp;<a href="#" onclick="document.liveupdateform.page.value='
                        +(pagescnt-1)+'; liveUpdate(); return false" title="Last page" '+style+'>&gt;&gt;</a>')])
                }
		res_ul.appendChild(newElem('p'));

		return res_ul;
	}

		
	this.decorate = function(){
		// In this class, put page ribbons here and there
		var c1 = this.pageRibbon()
		var c2 = this.pageRibbon()
		var c = document.getElementById(this.liveContainerId)
		}

	this.redecorate = function(){
		var c1 = this.pageRibbon()
		var c2 = this.pageRibbon()
		var c = document.getElementById(this.liveContainerId)
			
		}

		
	this.fill = function(data){
this.htmlRows = []
		if(this.refillDisabled) return
		this.refillDisabled = true
		this.reinitTable()	
		if(document.getElementById('debugarea'))
				document.getElementById('debugarea').value = data
		var jsondata =  eval("("+data+")")
		this.liveData = jsondata
		var f = this.updateForm
		f.timestamp.value = jsondata.timestamp
		f.page.value = jsondata.page
		f.pagescnt.value = jsondata.pagescnt
		this.sortables = jsondata.sortables
		
		if(jsondata.rows) for(var i=0; i<jsondata.rows.length; i++){
	    	var row = jsondata.rows[i]
		var tr = this.htmlRow(row)
		tr.setAttribute('id', 'list-row-'+row.id)
	    	tr.className = (i % 2 == 0)?("row-0"):("row-1")
	    	this.htmlRows.push(tr)	    	
	    	this.parentTbody.appendChild(tr)
	    	}
		
		this.htmlHead.appendChild(this.makeHeader(jsondata.columns))

		var dt =  document.getElementById(this.id)
		if(dt){
			with(dt.parentNode){
				if(dt.previousSibling)removeChild(dt.previousSibling)
				if(dt.nextSibling) removeChild(dt.nextSibling)
				removeChild(dt)
				this.htmlTable.setAttribute('id', this.id)
				appendChild(this.pageRibbon())
				appendChild(this.htmlTable)
				var tds = this.htmlTable.getElementsByTagName('TD')
				for(var j=0; j < tds.length; j++){
					for(var k=0; k<tds[j].childNodes.length; k++)
					if(tds[j].childNodes[k].getAttribute && tds[j].childNodes[k].getAttribute('onappend')){
						tds[j].childNodes[k].onAppend = function(){eval(tds[j].childNodes[k].getAttribute('onappend'))}
						tds[j].childNodes[k].onAppend()
						}
					}
				
				appendChild(this.pageRibbon())
				}
	    }
		else{
			var c = document.getElementById(this.liveContainerId)
			with(c){
				appendChild(this.pageRibbon())
				appendChild(this.htmlTable)
				var tds = this.htmlTable.getElementsByTagName('TD')
				for(var j=0; j < tds.length; j++){
					for(var k=0; k<tds[j].childNodes.length; k++)
					if(tds[j].childNodes[k].getAttribute && tds[j].childNodes[k].getAttribute('onappend')){
						tds[j].childNodes[k].onAppend = function(){eval(tds[j].childNodes[k].getAttribute('onappend'))}
						tds[j].childNodes[k].onAppend()
						}
					}
				
				appendChild(this.pageRibbon())
			}
	    }

		//alert("d");
		this.refillDisabled = false
		}

	this.fetch = function(){
		if(this.refillDisabled) return
		var f = this.updateForm
		var t = this
		var status = AjaxRequest.submit(f, {'onSuccess':function(req){
			t.fill(req.responseText)}})
		return status
		}
		
    this.createSortLink = function(id, value){
		var f = this.updateForm
		var t = this
		if(f.sortby.value == id){
	    	value += "<span class='sortorder-"+f.sortorder.value+"'>&nbsp;</span>"
	    	}
		var anchor = newElem('a', {'href':'#'}, value);
	    anchor.onclick = function(){eval("var f = document.getElementById('liveupdateform');"+
	    	" if(f.sortby.value == '"+id+"'){ f.sortorder.value = (f.sortorder.value == 'asc')?('desc'):('asc');} "+
	    	" else{f.sortby.value = '"+id+"';f.sortorder.value = 'asc'}; t.fetch()"); return false
	    	}
		return anchor
		}

    this.updateForm.hasFilter = function(nam, val){
		for (i=0; i<this.childNodes.length; i++) {
	    	if((this.childNodes[i].nodeName=='input')&&(this.childNodes[i].getAttribute('type') == 'hidden') && (this.childNodes[i].getAttribute('name') == 'name')
				&& (this.childNodes[i].getAttribute('value') == value))
				return true;
	    	}
		return false;
		}

	this.updateForm.addToFilter = function(nam, val){
	    if(this.hasFilter(nam, val)) return;
	    var h = newElem('input', {'type':'hidden', 'name':nam, 'value':val})
	    this.appendChild(h)
	    }

    this.updateForm.delFromFilter = function(nam, val){
		for (i=0; i<this.childNodes.length; i++) {
	    	if((this.childNodes[i].nodeName=='input')&&(this.childNodes[i].getAttribute('type') == 'hidden') && 
	    		(this.childNodes[i].getAttribute('name') == 'name')
				&& (this.childNodes[i].getAttribute('value') == value)){
				this.removeChild(this.childNodes[i]);
				return true;
				}
	   		}
		return false;
		}
	
    this.updateForm.toggleFilter = function(nam, val){
		var r = this.hasFilter(nam, val)
		if(r)
		    this.delFromFilter(nam, val)
		else
	    	this.addToFilter(nam, val)
		return r
		}
	
    this.updateForm.toggleFilter = function(nam){
	for (i=0; i<this.childNodes.length; i++)
	    if((this.childNodes[i].nodeName=='input')&&(this.childNodes[i].getAttribute('type') == 'hidden') && (this.childNodes[i].getAttribute('name') == 'name'))
			this.removeChild(this.childNodes[i]);
	return true;
	}
	
	}
	
function liveQuestionGrid(){
	this.inherit = liveGrid
	this.inherit()
	this.questions = new Array()
	this.beingAnswered = false
	this.backuptd = ''
	
	this.answerQuestion = function(id){
	    if(this.beingAnswered) return;
	    this.beingAnswered = true
	    AjaxRequest.get({
	    'url':url_path+'question/answer',
	    'parameters':{'id':id},
	    'onSuccess': function(req){
	    	var data = eval("("+req.responseText+")")
	    	if(!data.can_answer){
	    		liveUpdater.beingAnswered = false
	    		return
	    		}
			var t = document.getElementById('list-row-'+id)
			with(liveUpdater){
				targetTD = t.childNodes[4]
				backuptd = targetTD.innerHTML
				refillDisabled = true
				answerOldClassName = t.className
				}
			t.className = 'being-answered'
			var container = newElem('form', 
				{'action':url_path+'question/answer', 'method':'post', 'name':'liveanswer',
				 'id':'liveanswer', 'onsubmit':'liveUpdater.submitAnswer()'})
			var val = document.createTextNode(data.rawanswer).nodeValue;
			if(val == "null") val = "";
			var inside = [
				newElem('input', {'type':'hidden', 'id':'id', 'name':'id', 'value':id}),
				newElem('p', {'class':'question'}, liveUpdater.questions[id].question.value),
				/*newElem('textarea', {'id':'answer', 'class':'answer', 'cols':'30', 'rows':'10', 'name':'answer',
					'onkeyup':'document.getElementById("q_counter").innerHTML = this.value.length',
					'onclick':'document.getElementById("q_counter").innerHTML = this.value.length'},
					val),*/
				newElem('span', {'class':'question'}, '<textarea style="width:375px;height:130px" id="answer" class="answer" name="answer" onkeyup="document.getElementById(\'q_counter\').innerHTML = this.value.length" onclick="document.getElementById(\'q_counter\').innerHTML = this.value.length">'+val+'</textarea>'),
				newElem('br'),
				newElem('select', {'id':'q_classes', 'size':'1', 'class':'classes'}),
				newElem('span', {'class':'counter', 'id':'q_counter'}, ''),
				newElem('br'),
				newElem('input', {'type':'button', 'name':'discard', 'value':'Abbrechen', 'onclick':'liveUpdater.discardAnswer('+id+');return false', 'class':'submit'}),			
				newElem('input', {'type':'submit', 'name':'send', 'value':'Speichern', 'class':'submit', 'onclick':'liveUpdater.submitAnswer('+id+');return false'})
				]
			mappend(container, inside)
			var c = newElem('div')
			c.appendChild(container)
			with(liveUpdater){
				targetTD.innerHTML = c.innerHTML
				fillClasses(document.getElementById('q_classes'), 'answer')
				//var oldUnload = "";//document.body.onunload
				document.body.onunload = "liveUpdater.discardAnswer("+id+")"
				}
	    	}
	    })		
		}

	this.editQuestion = function(id, element){
	    if(this.beingAnswered) return;
	    this.beingAnswered = true
	    this.refillDisabled = true
		var t = document.getElementById('list-row-'+id)
		var parentTD = t.childNodes[4]
		this.oldClassName = parentTD.parentNode.className
		this.questionTD = parentTD
		this.backuptd = parentTD.innerHTML  
		parentTD.parentNode.className = 'being-answered'
			var container = newElem('form', 
				{'action':url_path+'question/edit', 'method':'post', 'name':'liveanswer',
				 'id':'liveanswer', 'onsubmit':'liveUpdater.submitEditQuestion()'})
			var val = document.createTextNode(liveUpdater.questions[id].rawquestion).nodeValue;
			if(val == "null") val = "";
			var inside = [
				newElem('input', {'type':'hidden', 'id':'id', 'name':'id', 'value':id}),
				/*newElem('textarea', {'id':'question', 'class':'answer', 'cols':'30', 'rows':'5', 'name':'question',
					'onkeyup':'document.getElementById("q_counter").innerHTML = this.value.length',
					'onclick':'document.getElementById("q_counter").innerHTML = this.value.length'},
					val),*/
                                newElem('span', {'class':'question'}, '<textarea style="width:375px;height:130px" id="question" class="question" name="question" onkeyup="document.getElementById(\'q_counter\').innerHTML = this.value.length" onclick="document.getElementById(\'q_counter\').innerHTML = this.value.length">'+val+'</textarea>'),

				liveUpdater.questions[id].answer ? newElem('p', {'class':'answer'}, liveUpdater.questions[id].answer.value) : newElem('span'),
				newElem('br'),
				newElem('span', {'class':'counter', 'id':'q_counter'}, ''),
				newElem('br'),
				newElem('input', {'type':'button', 'name':'discard', 'value':'Abbrechen', 'onclick':'liveUpdater.discardAnswer('+id+');return false', 'class':'submit'}),			
				newElem('input', {'type':'submit', 'name':'send', 'value':'Speichern', 'class':'submit', 'onclick':'liveUpdater.submitAnswer('+id+');return false'})
				]


		mappend(container, inside)
		var c = newElem('div')
		c.appendChild(container)
		with(liveUpdater){
			parentTD.innerHTML = c.innerHTML
			}		
		}
		

		
	this.fillClasses = function(sel, areaid){
		var txtarea = document.getElementById(areaid)
		AjaxRequest.get({'url':url_path+'question/messageclasslist',
			'onSuccess':function(r){
				var data = eval("("+r.responseText+")")
				sel.classes = data
				var opt = newElem("option", {'value':''}, 
					document.createTextNode('(None)').nodeValue)
				sel.appendChild(opt)
				for(var i=0; i<data.length; i++){
					if(data[i] == null) continue;
					var opt = newElem("option", {'value':data[i][4]}, 
						document.createTextNode(data[i][2]).nodeValue)
					sel.appendChild(opt)
				}
				sel.onchange = function(){
					txtarea.value = this.options[this.selectedIndex].value
					document.getElementById("q_counter").innerHTML = txtarea.value.length
				}
			}})
		}
		
	this.discardAnswer = function(id){
	        // insert some ajax
	        AjaxRequest.post({
	        'url':url_path+'question/answer',
	        'parameters':{'id':id, 'dismiss':'dismiss'},
	        'onSuccess':function(req){
	        	with(liveUpdater){
	        		targetTD.innerHTML = backuptd
	        		beingAnswered = false
	        		targetTD.parentNode.className = answerOldClassName
	        		refillDisabled = false
	        		fetch()
	        		//document.body.onunload = oldUnload
	        		}
	        	}
	        })
	        }
		
	this.discardComment = function(id){
        // insert some ajax
       	with(liveUpdater){
       		commentTD.innerHTML = backuptd
       		beingAnswered = false
       		commentTD.parentNode.className = oldClassName
       		refillDisabled = false
       		fetch()
       		}
        }
		
	this.submitAnswer = function(id){
//alert(document.getElementById('question').value);
	        AjaxRequest.submit(
	        document.getElementById('liveanswer'),
	        {	        
	        'parameters':{'send':'send'},
	        'onSuccess':function(req){
	        	with(liveUpdater){
	        		refillDisabled = false
	        		beingAnswered = false
	        		fetch()
	        		//document.body.onunload = oldUnload
	        		}
	        	}
	        })			
		}
		
	this.archiveQuestion = function(id){
			liveUpdater.refillDisabled = true
	        AjaxRequest.get({
	        'url':url_path+'question/archive?id='+id,	        
	        'onSuccess':function(req){
	        	with(liveUpdater){
	        		refillDisabled = false
	        		fetch()
	        		}
	        	}
	        })			
		}
		
	this.unarchiveQuestion = function(id){
			liveUpdater.refillDisabled = true
	        AjaxRequest.get({
	        'url':url_path+'question/unarchive?id='+id,	        
	        'onSuccess':function(req){
	        	with(liveUpdater){
	        		refillDisabled = false
	        		fetch()
	        		}
	        	}
	        })			
		}
		
	this.submitEditQuestion = function(id){
	        AjaxRequest.submit(
	        document.getElementById('liveanswer'),
	        {	        
	        'parameters':{'send':'send'},
	        'onSuccess':function(req){
	        	with(liveUpdater){
	        		refillDisabled = false
	        		beingAnswered = false
	        		fetch()
	        		}
	        	}
	        })			
		}
		
	this.submitComment = function(id){
	        AjaxRequest.submit(
	        document.getElementById('livecomment'),
	        {	        
	        'parameters':{'send':'send', 'cfield':'1'},
	        'onSuccess':function(req){
	        	with(liveUpdater){
	        		refillDisabled = false
	        		beingAnswered = false
	        		fetch()
	        		}
	        	}
	        })			
		}

/** kw 29-04-08 **/
        this.submitCategory = function(id){
                AjaxRequest.submit(
                document.getElementById('livecategory'),
                {
                'parameters':{'send':'send'},
                'onSuccess':function(req){
                        with(liveUpdater){
                                refillDisabled = false
                                beingAnswered = false
                                fetch()
                                }
                        }
                })
                }

		
	this.rejectQuestion = function(id){
	        AjaxRequest.post({
	        'url':url_path+'question/answer',
	        'parameters':{'id':id, 'reject':'reject'},
	        'onSuccess':function(req){
        		beingAnswered = false
	        	liveUpdater.fetch()
	        	}
	        })		
	    }
	    
	this.approveQuestion = function(id){
	        AjaxRequest.post({
	        'url':url_path+'question/answer',
	        'parameters':{'id':id, 'approve':'approve'},
	        'onSuccess':function(req){
        		beingAnswered = false
	        	liveUpdater.fetch()
	        	}
	        })		
		}
		
	this.editComment = function(id, element){
	    if(this.beingAnswered) return;
	    this.beingAnswered = true
	    this.refillDisabled = true
		var parentTD = element.parentNode
		this.oldClassName = parentTD.parentNode.className
		this.commentTD = parentTD
		this.backuptd = parentTD.innerHTML  
		parentTD.parentNode.className = 'being-answered'
		var container = newElem('form', 
			{'action':url_path+'question/answer', 'method':'post', 'name':'livecomment',
			 'id':'livecomment', 'onsubmit':'liveUpdater.submitComment(); return false;'})
		var val = document.createTextNode(liveUpdater.questions[id].rawcomment).nodeValue;
		if(val == "null") val = "";
		var inside = [
			newElem('input', {'type':'hidden', 'id':'id', 'name':'id', 'value':id}),
			newElem('textarea', {'id':'comment', 'class':'comment', 'cols':'30', 'rows':'5', 'name':'comment'},
				val),
				//document.createTextNode(liveUpdater.questions[id].rawcomment).nodeValue),
			newElem('br'),
			newElem('input', {'type':'button', 'name':'discard', 'value':'Abbrechen', 'onclick':'liveUpdater.discardComment('+id+');return false', 'class':'submit'}),			
			newElem('input', {'type':'submit', 'name':'send', 'value':'Speichern', 'class':'submit', 'onclick':'liveUpdater.submitComment('+id+');return false'})
			]
		mappend(container, inside)
		var c = newElem('div')
		c.appendChild(container)
		with(liveUpdater){
			parentTD.innerHTML = c.innerHTML
			}		
		}

/** kw 29-04-08 **/
        this.editCategory = function(id, element, cat){
            if(this.beingAnswered) return;
            this.beingAnswered = true
            this.refillDisabled = true
                var parentTD = element.parentNode
                this.oldClassName = parentTD.parentNode.className
                this.commentTD = parentTD
                this.backuptd = parentTD.innerHTML
                parentTD.parentNode.className = 'being-answered'
		
                var container = newElem('form',
                        {'action':url_path+'question/category', 'method':'get', 'name':'livecategory',
                         'id':'livecategory', 'onsubmit':'liveUpdater.submitCategory(); return false;'})
                var val = liveUpdater.questions[id].rawcategory;
                if(val == "null") val = "1";
		// generate select dropdown
		cat=unescape(cat);

		var catPairs = cat.split(";");
		var options = "<select name='category' id='category'>";
		for(i=0; i < catPairs.length; i++){
		  var catPair = catPairs[i];
		  //alert(catPair);
		  if(catPair.length > 0){
		    var elem = catPair.split(":");
		    var checked = "";
		    if(elem[0] == val) checked = " selected='selected'";
		    options += "<option value='"+elem[0]+"'"+checked+">"+elem[1]+"</option>";
		  }
		}
		options += "</select>";
                var inside = [
                        newElem('input', {'type':'hidden', 'id':'id', 'name':'id', 'value':id}),
			//newElem('select', {'id':'category', 'name':'category'}, options),
			newElem('div', {'id':'cat'}, options),
//"<option value='1'>shit</option><option value='2'>bull</option>"),
                        //newElem('textarea', {'id':'comment', 'class':'comment', 'cols':'30', 'rows':'5', 'name':'comment'},
                        //        val),
                                //document.createTextNode(liveUpdater.questions[id].rawcomment).nodeValue),
                        newElem('br'),
                        //newElem('input', {'type':'button', 'name':'discard', 'value':'Abbrechen', 'onclick':'liveUpdater.discardComment('+id+');return false', 'class':'submit'}),
                        newElem('input', {'type':'submit', 'name':'send', 'value':'Speichern', 'class':'submit', 'onclick':'this.value="saving..";liveUpdater.submitCategory('+id+');return false'})
                        ]
                mappend(container, inside)
                var c = newElem('div')
                c.appendChild(container)
                with(liveUpdater){
                        parentTD.innerHTML = c.innerHTML
                        }
                }


			        
	this.undoRejectQuestion = function(id){
	        AjaxRequest.post({
	        'url':url_path+'question/answer',
	        'parameters':{'id':id, 'undoreject':'undoreject'},
	        'onSuccess':function(req){
        		beingAnswered = false
	        	liveUpdater.fetch()
	        	}
	        })		
		}
		
	this.decorationHooks['question'] = function(question){
		// well, this needs to be json, repeating almost all the data
		if(question == null) return '';
		var q = question.id
		liveUpdater.questions[q] = question
		var t = this
		var container = newElem('div')
		if(question.question){
			container.innerHTML += "<div class=\"" +
				question.question.classname + "\">"+question.question.value + "</div>"
		}
		if(question.answer){
			container.innerHTML += "<div class=\"" +
				question.answer.classname + "\">"+question.answer.value + "</div>"
		}
		var container2 = newElem('div', {'class':'controls'}, '')
		var buttons = []
		if(question.buttons){
			for(var i = 0; i < question.buttons.length; i++){
				switch(question.buttons[i]){
				case 'answer':
					buttons.push(newElem("button", {"onclick":"liveUpdater.answerQuestion("+
						question.id+")"}, "Beantworten"))
					break;
				case 'reject':
					buttons.push(newElem("button", {"onclick":"liveUpdater.rejectQuestion("+
						question.id+")"}, "Abweisen"))
					break;
				case 'editanswer':
					buttons.push(newElem("button", {"onclick":"liveUpdater.answerQuestion("+
						question.id+")"}, "Antwort bearbeiten"))
					break;
				case 'undoreject':
					buttons.push(newElem("button", {"onclick":"liveUpdater.undoRejectQuestion("+
						question.id+")"}, "Wiederherstellen"))
					break;
				case 'approve':
					buttons.push(newElem("button", {"onclick":"liveUpdater.approveQuestion("+
						question.id+")"}, "Absenden"))
					break;			
				case 'editquestion':
					buttons.push(newElem("button", {"onclick":"liveUpdater.editQuestion("+
						question.id+")"}, "Frage bearbeiten"))			
				}
			}
			var c3 = newElem('div')
			mappend(container2, buttons)
			c3.appendChild(container2)
		}
                if(c3 == null){
			return container.innerHTML;
		} else {
			return container.innerHTML + c3.innerHTML;
		} 
	}
}

function tf(n, v){
	return !document.forms['liveupdateform'].toggleFilter(n, v)
	}

function liveMessageGrid(){
	this.inherit = liveQuestionGrid
	this.inherit()
	this.messages = []

	this.decorationHooks['message'] = function(message){
		// well, this needs to be json, repeating almost all the data
		if(message == null) return '';
		var m = message.id
		liveUpdater.messages[m] = message
		var t = this
		var container = newElem('div')
		if(message.message){
			container.innerHTML += "<div class=\"" +
				message.message.classname + "\">"+message.message.value + "</div>"
		}
		var container2 = newElem('div', {'class':'controls'}, '')
		var buttons = []
		if(message.buttons){
			for(var i = 0; i < message.buttons.length; i++){
				switch(message.buttons[i]){
				case 'reject':
					buttons.push(newElem("button", {"onclick":"liveUpdater.rejectMessage("+
						message.id+")"}, "Reject"))
					break;
				case 'editmessage':
					buttons.push(newElem("button", {"onclick":"liveUpdater.editMessage("+
						message.id+")"}, "Edit message"))
					break;
				case 'undoreject':
					buttons.push(newElem("button", {"onclick":"liveUpdater.undoRejectMessage("+
						message.id+")"}, "Wiederherstellen"))
					break;
				case 'approve':
					buttons.push(newElem("button", {"onclick":"liveUpdater.approveMessage("+
						message.id+")"}, "Absenden"))			
				}
			}
			var c3 = newElem('div')
			mappend(container2, buttons)
			c3.appendChild(container2)
		}
		return container.innerHTML + c3.innerHTML
	}

	this.editComment = function(id, element){
	    if(this.beingAnswered) return;
	    this.beingAnswered = true
	    this.refillDisabled = true
		var parentTD = element.parentNode.parentNode
		this.oldClassName = parentTD.parentNode.className
		this.commentTD = parentTD
		this.backuptd = parentTD.innerHTML  
		parentTD.parentNode.className = 'being-answered'
		var container = newElem('form', 
			{'action':url_path+'message/comment', 'method':'post', 'name':'livecomment',
			 'id':'livecomment', 'onsubmit':'liveUpdater.submitComment(); return false;'})
		var val = document.createTextNode(liveUpdater.messages[id].rawcomment).nodeValue;
		if(val == "null") val = "";
		var inside = [
			newElem('input', {'type':'hidden', 'id':'id', 'name':'id', 'value':id}),
			newElem('textarea', {'id':'comment', 'class':'comment', 'cols':'30', 'rows':'5', 'name':'comment'},
				val),
			newElem('br'),
			newElem('input', {'type':'button', 'name':'discard', 'value':'Abbrechen', 'onclick':'liveUpdater.discardComment('+id+');return false', 'class':'submit'}),			
			newElem('input', {'type':'submit', 'name':'send', 'value':'Speichern', 'class':'submit', 'onclick':'liveUpdater.submitComment('+id+');return false'})
			]
		mappend(container, inside)
		var c = newElem('div')
		c.appendChild(container)
		with(liveUpdater){
			parentTD.innerHTML = c.innerHTML
			}		
		}
			        
	this.submitComment = function(id){
	        AjaxRequest.submit(
	        document.getElementById('livecomment'),
	        {	        
	        'parameters':{'send':'send'},
	        'onSuccess':function(req){
	        	with(liveUpdater){
	        		refillDisabled = false
	        		beingAnswered = false
	        		fetch()
	        		}
	        	}
	        })			
		}
		
	this.approveMessage = function(id){
        AjaxRequest.post({
        'url':url_path+'message/approve',
        'parameters':{'id':id},
        'onSuccess':function(req){
       		beingAnswered = false
        	liveUpdater.fetch()
        	}
        })		
	}
		
	this.rejectMessage = function(id){
        AjaxRequest.post({
        'url':url_path+'message/reject',
        'parameters':{'id':id},
        'onSuccess':function(req){
       		beingAnswered = false
        	liveUpdater.fetch()
        	}
        })		
	}
		
	this.undoRejectMessage = function(id){
        AjaxRequest.post({
        'url':url_path+'message/undoreject',
        'parameters':{'id':id},
        'onSuccess':function(req){
       		beingAnswered = false
        	liveUpdater.fetch()
        	}
        })		
	}
		
	this.editMessage = function(id, element){
	    if(this.beingAnswered) return;
	    this.beingAnswered = true
	    this.refillDisabled = true
		var t = document.getElementById('list-row-'+id)
		var parentTD = t.childNodes[4]
		this.oldClassName = parentTD.parentNode.className
		this.questionTD = parentTD
		this.backuptd = parentTD.innerHTML  
		parentTD.parentNode.className = 'being-answered'
			var container = newElem('form', 
				{'action':url_path+'message/edit', 'method':'post', 'name':'liveanswer',
				 'id':'liveanswer', 'onsubmit':'liveUpdater.submitEditMessage(); return false'})
			var val = document.createTextNode(liveUpdater.messages[id].rawmessage).nodeValue;
	                if(val == "null") val = "";
			var inside = [
				newElem('input', {'type':'hidden', 'id':'id', 'name':'id', 'value':id}),
				/*newElem('textarea', {'id':'m_message', 'class':'answer', 'cols':'30', 'rows':'5', 'name':'message',
					'onkeyup':'document.getElementById("m_counter").innerHTML = this.value.length',
					'onclick':'document.getElementById("m_counter").innerHTML = this.value.length'},
					val),*/
                                newElem('span', {'class':'message'}, '<textarea style="width:375px;height:130px" id="message" class="answer" name="message" onkeyup="document.getElementById(\'m_counter\').innerHTML = this.value.length" onclick="document.getElementById(\'m_counter\').innerHTML = this.value.length">'+val+'</textarea>'),

				newElem('br'),
				newElem('span', {'class':'counter', 'id':'m_counter'}, ''),
				newElem('br'),
				newElem('input', {'type':'button', 'name':'discard', 'value':'Abbrechen', 'onclick':'liveUpdater.discardMessage('+id+');return false', 'class':'submit'}),			
				newElem('input', {'type':'submit', 'name':'send', 'value':'Speichern', 'class':'submit', 'onclick':'liveUpdater.submitEditMessage();return false'})
				]


		mappend(container, inside)
		var c = newElem('div')
		c.appendChild(container)
		with(liveUpdater){
			parentTD.innerHTML = c.innerHTML
			}		
		}

	this.discardMessage = function(id){
	        // insert some ajax
			var t = document.getElementById('list-row-'+id)
			var targetTD = t.childNodes[4]
        	with(liveUpdater){
	        		targetTD.innerHTML = backuptd
	        		beingAnswered = false
	        		targetTD.parentNode.className = this.oldClassName
	        		refillDisabled = false
	        		fetch()
	        		}
	        }

	this.submitEditMessage = function(){
	        AjaxRequest.submit(
	        document.getElementById('liveanswer'),
	        {	        
	        'parameters':{'send':'send'},
	        'onSuccess':function(req){
	        	with(liveUpdater){
	        		refillDisabled = false
	        		beingAnswered = false
	        		fetch()
	        		}
	        	}
	        })		
	        return false	
		}		

}

