var data = [
    {
        'question_text': 'What do you think </textarea>about text on the site?',
        'question_id' : 'overall',
        'question_spec' : "default = N/A\ngood = rather good\nBad = too bad\nNice = very nice"
    },
    {
        'question_text': 'Do you like site\'s design?',
        'question_id' : 'design',
        'question_spec' : "default =  N/A\ngood  = good\nBad  = bad\nNice = nice"
    }
];
var maxquestions = 10;
var readonly = 0;//whether everything is readonly
var questionspec_hint = "questionspec hint goes here";

function $() {
        var elements = new Array();

        for (var i = 0; i < arguments.length; i++) {
                var element = arguments[i];
                if (typeof element == 'string')
                        element = document.getElementById(element);

                if (arguments.length == 1)
                        return element;

                elements.push(element);
        }

        return elements;
}

function on_sel_change(o)
{
    alert("selected " + o.options[o.selectedIndex].value);
}
//used for storing current values of questions/answers back into array
function _serialize_answers()
{
    var f = document.forms[0]; //assuming it's 1st form
    if (!f) return; //it's absent in view mode!
    var re = /^q([0-9]+)_(.+)$/;
    for(var i=0;i<f.length;++i)
    {
	var fi = f[i];
	var arr = re.exec(fi.name);
	//alert("amtching " + fi.name);
	if (arr != null) {
	    data[arr[1]]["question_" + arr[2]] = fi.value;
	};
    }
    {
	var e = $('data_json');
	if (e) { //it can be absent while document haven't been loaded fully
	    e.value = JSON.stringify(data);
	};
    }
}

function _qops(op,qidx)
{
    //alert("quops called " + op + " idx is " + question_idx);
    _serialize_answers();
    if (op == 'up')
    {
	if (qidx==0) return;
	var tmp=data[qidx-1];
	data[qidx-1]=data[qidx];
	data[qidx]=tmp;
    } else if (op == 'down') {
	if (qidx==data.length-1) return;
	var tmp=data[qidx+1];
	data[qidx+1]=data[qidx];
	data[qidx]=tmp;	
    } else if (op == 'del') {
	if (confirm("Do you really wish to completely delete question number " + (1+qidx) + "? This can't be undone")) {
	    data.splice(qidx,1);
	} else {
	    return;
	};
    } else if (op == 'xnew') {
	data.splice(qidx,0,{
    	    'question_text': 'Text of the question here (e.g. How do you like our logo?)',
	    'question_id' : 'question_id',
    	    'question_spec' : "default = N/A\ngood = good\nBad = bad\nNice = nice"
	});
    } else if (op == 'edit') {
	_update_question_piece(qidx,0);
	return;
    };
    construct_gui(data.divid);
    return 1;
}

function questions_validate()
{
    var qids = {};
    _serialize_answers();
    if (data.length > maxquestions) {
	alert("You've exceeded maximum number of questions allowed " + maxquestions + 
	    " by " + (data.length - maxquestions) + ". Please remove some questions");
	return false;
    };
    for(var qidx=0;qidx< data.length;++qidx)
    {
	var d = data[qidx];
	if (qids[d.question_id]) {
	    alert("Error: question " + (qidx+1) + " has the same ID as question " + (1+qids[d.question_id]) +
		" - please correct the error!");
	    return false;
	} else {
	    qids[d.question_id] = qidx;
	};
    }
    return true;
}

function htmlq(s)
{
    s = s.replace(/&/,"&amp;");
    s = s.replace(/>/,"&gt;");
    s = s.replace(/</,"&lt;");
    return s;
}
function _genbtn(op,idx)
{
    var op2html = { up: '&uarr;', down: '&darr;', del: 'x', xnew: '+', edit: 'edit' };
    return "<button type=button onclick='_qops(\"" + op + "\","  + idx + ")'>" + op2html[op]  + '</button>';
}

function question_done_editing(do_save,qidx)
{
    if (do_save) {
        var f = document.forms[0]; //assuming it's 1st form
	var spec = f['q'+qidx + '_spec'].value;
	var arr =  _parse_answers_spec(spec);
	if (arr.length<2) {
	    alert("Please define at least 2 answers. Each answer is defined on a new line, format is ANSWERID = ANSWER TEXT");
	    return;
	};
	 _serialize_answers();
    }
    _update_question_piece(qidx,1);
}

function _update_question_piece(qidx,is_view)
{
    var e = $('question_overall_block_' + qidx);
    e.innerHTML = is_view ? construct_viewmode_html(qidx) : construct_editmode_html(qidx);
}
function construct_editmode_html(qidx)
{
    var t = '';
    {
	var d = data[qidx];
	t += '<div class=question-editmode>';


	t += '<div class=questionops>' +  _genbtn('edit',qidx) +
			_genbtn('up',qidx) +  _genbtn('down',qidx) +
			 _genbtn('del',qidx) +  _genbtn('xnew',qidx) + '</div>';
    
	t += 'Question id <input class=entry name=q' + qidx + '_id value="' + 
		htmlq(d.question_id) +'" ><br>' + "\n";

	t += 'Question text:<br>';
	t += '<textarea name=q' + qidx + '_text>' + htmlq(d.question_text) + '</textarea><br>';

	t += questionspec_hint;
	t += '<textarea wrap=off name=q' + qidx + '_spec>' + htmlq(d.question_spec) + '</textarea>';
	t += '</div>' + "\n";
	t += '<div class=question-editmode-donebuttons>' +
		 '<button type=button onclick=question_done_editing(1,' + qidx +  ')>Save changes</button>' +
		 '<button type=button onclick=question_done_editing(0,' + qidx +  ')>Ignore changes</button>';
    }
    return t;
}

function imglinkify(txt)
{
    txt = txt.replace(/(http:\/\/\S+\.(jpe?g|gif|png))/ig, "<img src=\"$1\" style='padding:5px;' align=middle></img>");
    txt = txt.replace(/(\r?\n)+/g, "<br/>");
    return txt;
}

function _render_answers_as_radios(id,arrdef)
{
    var t = '';
    for(var i=0;i<arrdef.length;++i)
    {	
	t+= '<input type=radio name="' + id + '" value="' + arrdef[i].id + '" id="ans_' + id + 
	    '_' + i + '"><label for="ans_' + id + '_' + i + '">' + imglinkify(htmlq(arrdef[i].title)) +
	 '</label>';
	if (readonly) {
	    t += ' <span class=display-id>(id: ' + htmlq(arrdef[i].id) + ')</span>';
	};
	t += '<br>';
    }
    return t;
}

//returns [ { id: blah, title: "answer text here"},..]
function _parse_answers_spec(spec)
{
    var lines = spec.split(/\r?\n/);
    var ret = [];
    var re = /^\s*(\S+)\s*=\s*(.+)/;
    for(var lidx=0;lidx<lines.length;++lidx)
    {
	var l = lines[lidx];
	if (/^\s*$/.test(l)) continue; //empty line    
	var arr = re.exec(l);
	if (arr && arr[2].length)
	{
	    //alert("found id " + arr[1] + " and title = " + arr[2]);
	    ret[ret.length] = { id: arr[1], title: arr[2] };
	};
    };
    return ret;
}

function _get_rendered_answers(spec)
{
    
    return _render_answers_as_radios(spec.question_id,_parse_answers_spec(spec.question_spec));
}

function showhide(idx,state)
{
    if (readonly) return;
    e = $('question_context_block_' + idx);
    //e.style.display = state ? '' : 'none';
    e.style.visibility = state ? 'visible' : 'hidden';
}

function construct_viewmode_html(qidx)
{
    var t = '';
    var d = data[qidx];
	t += '<div class=question onmouseover=showhide('+qidx+
		',1) onmouseout=showhide(' + qidx + ',0)>';

	t += '<div style="visibility:hidden" class=question_context_block id=question_context_block_' + qidx + '>';
	t += '<div class=questionops>' + _genbtn('edit',qidx) +
			 _genbtn('up',qidx) +  _genbtn('down',qidx) +
			 _genbtn('del',qidx) +  _genbtn('xnew',qidx) + '</div>';
    
	//t += 'Question id: ' + htmlq(d.question_id) +"<br>\n";
	t += '</div>';

	t += '<div class=question_text>' + imglinkify(htmlq(d.question_text));
	if (readonly) {
	    t += ' <span class=display-id>(id: ' + htmlq(d.question_id) + ')</span>'
	};
	t += '</div>';

	t += '<div class=answers>' + _get_rendered_answers(d) + '</div>';
	t += '</div>' + "\n";
    return t;

}
function construct_gui(divid)
{
    var t = '<input type=hidden name=numquestions value=' + data.length + ">";    
    data['divid'] = divid; //keep state this way
    for(var qidx=0;qidx< data.length;++qidx)
    {
	t += '<div id=question_overall_block_' + qidx +'>';
	t+= construct_viewmode_html(qidx) + '</div>';
    }
    document.getElementById(divid).innerHTML = t;
}


