/*
 * Jobs page
 */
var $j = jQuery.noConflict(); 

function delete_job(id, ts){
	var r;
	if(id == null){
		id = get_checked();
		if(!id)
			return;
		r=confirm("Are you sure you want to delete the selected jobs?");
	}
	else
		r=confirm("Are you sure you want to delete this job?");
	if(!r)
		return;
		
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	ts.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = ts.href;
	insert_hidden_input(f, 'postaction', 'delete_job');
	insert_hidden_input(f, 'p0', id);
	f.submit();			
}

function set_job_permissions(jobid){
	
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "";
	insert_hidden_input(f, 'postaction', 'show_job_permissions');
	insert_hidden_input(f, 'jobids', jobid);
	f.submit();
	return;
}

function set_jobvalue(jobid, value, fmid, ts) {	
	if(jobid == 0){
		jobid = get_checked();
		if(!jobid)
			return;
	}

	if(value == null)
		value = $('field_'+fmid).value;
		
	var f = document.createElement('form'); 
	f.style.display = 'none';
	ts.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = ts.href;
	insert_hidden_input(f, 'postaction', 'update_jobvalue');
	insert_hidden_input(f, 'p0', jobid);
	insert_hidden_input(f, 'field_'+fmid, value);
	f.submit();
}

/*
 * Listing page
 */

function delete_listing(id, ts) {
	var r=confirm("Are you sure you want to delete the listing for this job?");
	if(!r)
		return false;
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	ts.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = ts.href;
	insert_hidden_input(f, 'postaction', 'delete_listing');
	insert_hidden_input(f, 'id', id);
	f.submit();
	return false;
}


/*
 * Questionnaire page
 */

function delete_questionnaire(id, ts){
	var r=confirm("Are you sure you want to delete this questionnaire?");
	if(!r)
		return false;
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	ts.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = ts.href;
	insert_hidden_input(f, 'postaction', 'delete_questionnaire');
	insert_hidden_input(f, 'p0', id);
	f.submit();
	return false;
}

function clone_questionnaire(qe_eid){
    new Ajax.Request('/c/questionnaires/show/', {
        method: 'post',
        parameters: {postaction: 'clone_questionnaire', p0: qe_eid},
        onSuccess: function(transport) {
            $('content').update(transport.responseText);
        }
    }); 
}

function detach_questionnaire(q_eid, job_eid) {
    var r=confirm("Are you sure you want to detach this questionnaire from this job?");
    if(!r)
        return;
    new Ajax.Request('/c/questions/show/'+job_eid, {
        method: 'post',
        parameters: {postaction: 'detach_questionnaire', p0: q_eid, p1:job_eid},
        onSuccess: function(transport) {
            $('content').update(transport.responseText);
        }
    });   
}

function open_questionnaire(href, ts){
	var value = $('otherq').options[$('otherq').selectedIndex].value;
	if(value == ''){
		alert('Please select a questionnaire');
		return false;
	}
	
	ts.href = href.replace('/otherq/', '/'+value+'/');
	return true;	
}

function move_qtn(dir, qtn_id){
	
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "";
	insert_hidden_input(f, 'postaction', 'move_qtn');
	insert_hidden_input(f, 'p0', dir);
	insert_hidden_input(f, 'p1', qtn_id);
	f.submit();
	return false;
}

function move_question_up(qtn_id, qorder, job_eid) {
    new Ajax.Request('/c/questions/show/'+job_eid, {
        method: 'post',
        parameters: {postaction: 'move_question_up', p0: qtn_id, p1:qorder, p2:job_eid},
        onSuccess: function(transport) {
            $('content').update(transport.responseText);
        }
    });    
    
}

function move_question_down(qtn_id, qorder, job_eid){
    new Ajax.Request('/c/questions/show/'+job_eid, {
        method: 'post',
        parameters: {postaction: 'move_question_down', p0: qtn_id, p1:qorder, p2:job_eid},
        onSuccess: function(transport) {
            $('content').update(transport.responseText);
        }
    });        
    
}

function new_question(){
	show_qeditor("","",[],[],"");
}

function qtype_changed() {
	var o = Element.extend($('qtype').options[$('qtype').selectedIndex]);
	if(o.hasClassName('hasAnswers')){			
		$('pansrow').show();
	}
	else {
		$('pansrow').hide();
	}
}
	
function apply_question() {
	var qtype = $F('qtype');
	var qtext = $F('qtext').strip().gsub('\n', '<BR>');
	var pans = '';
	if($('pansrow').visible()){
		if($('pansedit').visible()){
			reset_answers(true);
			var pans_text = $('panscontent').select('div.qe_atext').collect(function (e){return e.innerHTML;});
			var pans_id = $('panscontent').childElements().collect(function (e){return e.className.split('_')[2];});
		}
		else{
			var pans_text = $F('pans').split('\n').collect(function (e){return e;}).reject(function (e){return e.blank();});
			var pans_id = pans_text.collect(function (e){return 0;});
		}
		for(var i=0; i<pans_text.length; i++){
			pans += '<div '+(pans_id[i] != '0' ? 'id="a_'+pans_id[i]+'" ' : '')+'class="q_ans">'+pans_text[i]+'</div>';
		}
	}	
	var req = ($F('required') == 'on' ? 'Yes' : 'No');
	
	if(qtype.blank()) {alert('Please select a Question Type'); return;}
	if(qtext.blank()) {alert('Please enter Question Text'); return;}
	if($('pansrow').visible() && pans.blank()) {alert('Please enter Possible Answers'); return;}
	
	var actions = '';
	actions += '<a href="#" onclick="clone_qrow(this); return false;"><img src="/images/icons/clone.gif" width="16" height="16" alt="Clone"></a>';
	actions += '&nbsp;<a href="#" onclick="edit_qrow(this); return false;"><img src="/images/icons/edit.gif" width="16" height="16" alt="Edit"></a>';
	actions += '&nbsp;<a href="#" onclick="delete_qrow(this); return false;"><img src="/images/icons/delete.gif" width="16" height="16" alt="Delete"></a>';
	
	var qrow = '<tr class="dragrow"><td>'+qtype+'</td><td><div class="q_text">'+qtext+'</div>'+pans+'</td><td>'+req+'</td><td class="nowrap">'+actions+'</td></tr>';
	
	if($('qeditor').hasClassName('editmode')){
		var editrow = $$('.editrow')[0];
		var qid = editrow.id;
		editrow.insert({after:qrow});
		qrow = editrow.next();
		editrow.remove();
		qrow.id = qid;
		qrow_init(qrow);
	}
	else if($('qeditor').hasClassName('clonemode')){
		var editrow = $$('.editrow')[0];
		editrow.insert({after:qrow});
		qrow = editrow.next();
		qrow_init(qrow);
	}
	else{
		var lastrow = $('questiontable').down('tr');
		while(1){
			if(lastrow.next() == null)
				break;
			lastrow = lastrow.next();
		}
		lastrow.insert({after:qrow});
		qrow_init(lastrow.next());
	}
	hide_qeditor();
}

function qrow_init(row){
	new DDList(row);
	row.observe('dblclick', function(evt){
		edit_qrow(this);
	});
}

function get_arow(id, text){
	var row = '';
	row += '<div class="'+id+'">';
	row += '<div class="qe_atext" onclick="edit_answer(this)">'+text+'</div>';
	row += '<div class="qe_aactions editactions"><a href="#" onclick="edit_answer(this); return false;">Edit</a>&nbsp;<a href="#" onclick="delete_answer(this); return false;">Delete</a>&nbsp;<a href="#" onclick="moveup_answer(this); return false;"><img src="/images/moveup.gif" width="10" height="10"></a>&nbsp;<a href="#" onclick="movedown_answer(this); return false;"><img src="/images/movedown.gif" width="10" height="10"></a></div>';
	row += '<div class="qe_ainput" style="display:none"><textarea name="a'+i+'text" cols="32" rows="' + Math.ceil(text.length/40) + '" onblur="submit_answer(this, true)"></textarea></div>';
	row += '<div class="qe_aactions submitactions" style="display:none"><a href="#" onclick="submit_answer(this, true); return false;">Submit</a>&nbsp;<a href="#" onclick="submit_answer(this, false); return false;">Cancel</a></div>';
	row += '<br style="clear:both"/>';
	row += '</div>';
	row = html_to_element(row);
	row.down('textarea').observe('keydown', answer_keydown);
	return row;
}

function answer_keydown(evt){
	if(evt.keyCode == 13){
		submit_answer(this, true);
		evt.stop();
	}
	if(evt.keyCode == 27){
		submit_answer(this, false);
		evt.stop();
	}
}

function reset_answers(dosubmit){
	
	var cnt = $('panscontent');
	cnt.childElements().each(function(row){
		if(row.down('div.qe_ainput').visible() && dosubmit){
			row.down('div.qe_atext').innerHTML = row.down('textarea').value.strip();
			row.removeClassName('new_row');	
		}

		if(row.hasClassName('new_row'))
			row.remove();
			
		row.down('div.qe_atext').show();
		row.down('div.editactions').show();
		row.down('div.qe_ainput').hide();
		row.down('div.submitactions').hide();		
	});
}

function add_answer(){
	
	reset_answers(true);
	
	var cnt = $('panscontent');
	row = get_arow('qe_a_0', '');
	row.addClassName('new_row');
	cnt.insert({bottom: row});
	
	var ans = cnt.childElements().last();
	ans.down('textarea').value = ans.down('div.qe_atext').innerHTML;
	ans.down('div.qe_atext').hide();
	ans.down('div.editactions').hide();
	ans.down('div.qe_ainput').show().down('textarea').activate();
	ans.down('div.submitactions').show();
}

function edit_answer(ts){
	
	reset_answers(true);
	
	ts = Element.extend(ts);
	var ans;
	if(ts.className == 'qe_atext')
		ans = ts.up('div', 0);
	else
		ans = ts.up('div', 1);

	ans.down('textarea').value = ans.down('div.qe_atext').innerHTML;
	ans.down('div.qe_atext').hide();
	ans.down('div.editactions').hide();
	ans.down('div.qe_ainput').show().down('textarea').activate();
	ans.down('div.submitactions').show();
}

function submit_answer(ts, keep){

	ts = Element.extend(ts);
	var ans = ts.up('div', 1);
	if(ans.down('textarea').value.blank())
		delete_answer(ts);
		
	reset_answers(keep);
}

function delete_answer(ts){
	ts = Element.extend(ts);
	var ans = ts.up('div', 1);
	ans.remove();
}

function moveup_answer(ts){
	ts=Element.extend(ts);
	var ans = ts.up('div', 1);
	if(ans.previous() == null)
		return;
	ans.previous().insert({before:ans});		
}

function movedown_answer(ts){
	ts=Element.extend(ts);
	var ans = ts.up('div', 1);
	if(ans.next() == null)
		return;
	ans.next().insert({after:ans});
}

function show_qeditor(qtype, qtext, pans, paids, req){
	$('addquestion').hide();
	$('pansrow').hide();
	setvalue_qeditor(qtype, qtext, pans, paids, req);	
	$('qeditor').show();

	Event.observe('qtype', 'change', qtype_changed);
}

function setvalue_qeditor(qtype, qtext, pans, paids, req) {
	$('qtype').setValue(qtype);
	qtype_changed();
	$('qtext').setValue(qtext.gsub('<BR>', '\n'));
	if(pans.length > 0){
		$('panscontent').update('');
		for(var i=0; i<pans.length; i++){
			var id = (paids[i].empty() ? 'a_0' : paids[i]);
			$('panscontent').insert({bottom: get_arow('qe_'+id, pans[i])});
		}
		$('pansnew').hide();				
		$('pansedit').show();
	}
	else{
		$('pans').setValue('');
		$('pansedit').hide();
		$('pansnew').show();		
	}

	$('required').checked=(req=="Yes" ? 1 : 0);
}

function hide_qeditor(){
	if($('qeditor').hasClassName('editmode')){
		$('qeditor').removeClassName('editmode');
		$('formcontainer').appendChild($('qeditor'));
		$('qeditcontainer').remove();
		var editrow = $$('.editrow')[0];
		if(editrow){
			editrow.removeClassName('editrow');
			editrow.show();
		}
	}
	else if($('qeditor').hasClassName('clonemode')){
		$('qeditor').removeClassName('clonemode');
		$('formcontainer').appendChild($('qeditor'));
		$('qeditcontainer').remove();
		var editrow = $$('.editrow')[0];
		if(editrow){
			editrow.removeClassName('editrow');
		}
	}
	
	$('qeditor').hide();
	$('addquestion').show();
}

function edit_qrow(e){
	hide_qeditor();
	
	e=Element.extend(e);
	var row;
	if(e.tagName.toLowerCase() == 'tr')
		row = e;
	else
		row = e.up('tr');

	row.addClassName('editrow');
	row.hide();
	row.insert({after:'<tr id="qeditcontainer"><td colspan="99"></td></tr>'});
	row.next('tr').down('td').appendChild($('qeditor'));
	$('qeditor').addClassName('editmode');

	var qdata = parse_qrow(row);
	
	show_qeditor(qdata.qtype, qdata.qtext, qdata.pans, qdata.paids, qdata.req);
}

function clone_qrow(e){
	hide_qeditor();
	
	e=Element.extend(e);
	var row;
	if(e.tagName.toLowerCase() == 'tr')
		row = e;
	else
		row = e.up('tr');

	row.addClassName('editrow');
	row.insert({after:'<tr id="qeditcontainer"><td colspan="99"></td></tr>'});
	row.next('tr').down('td').appendChild($('qeditor'));
	$('qeditor').addClassName('clonemode');

	var qdata = parse_qrow(row);
	
	show_qeditor(qdata.qtype, qdata.qtext, qdata.pans, qdata.paids, qdata.req);
}

function parse_qrow(row){
	var ret = new Object();
	ret.id    = row.id.split('_')[1];
	ret.qtype = row.down('td', 0).innerHTML;
	ret.qtext = row.down('td', 1).select('div.q_text')[0].innerHTML;
	ret.req   = row.down('td', 2).innerHTML;
	ret.pans  = row.down('td', 1).select('div.q_ans').pluck('innerHTML');
	ret.paids = row.down('td', 1).select('div.q_ans').pluck('id');
	
	return ret;
}

function delete_qrow(e){
	if(!confirm('Are you sure you want to delete this question?'))
		return;
	
	e=Element.extend(e);
	e.up('tr').remove();
}

function moveup_qrow(e){
	
	e=Element.extend(e);
	var this_row = e.up('tr');
	if(this_row.previous().down().tagName.toLowerCase() == "th")
		return;
	this_row.previous().insert({before:this_row});
}

function movedown_qrow(e){
	
	e=Element.extend(e);
	var this_row = e.up('tr');
	if(this_row.next() == null)
		return;
	this_row.next().insert({after:this_row});
}

function presubmit_questionnaire(){
	var f=$('questiontable').up('form');
	$('questiontable').select('tr.dragrow').each(function(row,n){
		n=n+1;
		var qdata = parse_qrow(row);
		if(qdata.id != null)
			insert_hidden_input(f, 'q'+n+'_id', qdata.id);
		insert_hidden_input(f, 'q'+n+'_type', qdata.qtype);
		insert_hidden_input(f, 'q'+n+'_text', qdata.qtext);
		insert_hidden_input(f, 'q'+n+'_req', qdata.req);
		for(var i=0; i<qdata.pans.length; i++){
			var n2=i+1;
			insert_hidden_input(f, 'q'+n+'_a'+n2+'_text', qdata.pans[i]);
			if(!qdata.paids[i].empty())
				insert_hidden_input(f, 'q'+n+'_a'+n2+'_id', qdata.paids[i].split('_')[1]);
		}
	});
	
	$('qeditor').remove();
}

/* 
 * Scoring Functions
 */

function init_scoringform() {
	
	Event.observe(window, 'load', add_scoring_events);
}

function add_scoring_events() {

	['p1', 'p2', 'p3'].each(function(e){
		if ($(e) != null) {
			Event.observe($(e), 'change', scoringinput_changed);
		}
	});
	
	$('mainform').getInputs('checkbox').each(function (e){
		if (e.id.indexOf('_ko') != -1) {
			Event.observe(e, 'click', function(event){
				set_pointstext_style(this);
			});
			set_pointstext_style(e);
		}
	});
}
	
function set_pointstext_style(e){
	
	var textid = e.id.replace('_ko', '_value');
	if (e.checked) {
		$(textid).clear().addClassName('disabled');
		$(textid).value = 'KO';
	}
	else{
		if($(textid).hasClassName('disabled')){
			$(textid).removeClassName('disabled');
			$(textid).value = '';
		}
	}	
}

function scoringinput_changed(event) {

	var value = this.options[this.selectedIndex].value;
	var url = '/c/scoring/formcontent';
	['p0', 'p1', 'p2', 'p3'].each(function(e){
		if($(e) != null && $F(e) != 0){
			url += '&';
			url += Field.serialize(e);
		}
	});
	new Ajax.Request(url, {
		evalJS: 'force',
		method: 'get',
		onSuccess: function(transport) {
			var node = $('formcontainer');
			node.replace(transport.responseText);
			add_scoring_events();
		}
	});
}

function delete_scoring(id, jobid){
	
	var r=confirm("Are you sure you want to delete this scoring rule?");
	if(!r)
		return;
	new Ajax.Request('/c/scoring/show/'+jobid, {
		method: 'post',
		parameters: {postaction: 'delete_scoring', p0: id},
		onSuccess: function(transport) {
			$('content').update(transport.responseText);
		}
	});	
}

function run_scores(jobid){
	new Ajax.Request('/c/scoring/show/'+jobid, {
		method: 'post',
		parameters: {postaction: 'run_scores', p0: jobid}
	});	
}

/*
 * Workflow Functions
 */

function delete_stage(obj_type, id){
	var r=confirm("Are you sure you want to delete this stage?");
	if(!r)
		return;
	new Ajax.Request('/c/stages/table/'+obj_type, {
		method: 'post',
		parameters: {postaction: 'delete_stage', p0: id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}
 
function deleteall_stages(obj_type){
	var ids = get_checked();
	if(!ids)
		return;
	var r=confirm("Are you sure you want to delete the selected stages?");
	if(!r)
		return;
	new Ajax.Request('/c/stages/table/'+obj_type, {
		method: 'post',
		parameters: {postaction: 'delete_stage', p0: ids},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});	
} 

function delete_action(obj_type, id){
	var r=confirm("Are you sure you want to delete this action?");
	if(!r)
		return;
	new Ajax.Request('/c/actions/table/'+obj_type, {
		method: 'post',
		parameters: {postaction: 'delete_action', p0: id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}

function deleteall_actions(obj_type){
	var ids = get_checked();
	if(!ids)
		return;
	var r=confirm("Are you sure you want to delete the selected actions?");
	if(!r)
		return;
	new Ajax.Request('/c/actions/table/'+obj_type, {
		method: 'post',
		parameters: {postaction: 'delete_action', p0: ids},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});	
} 
 
/* 
 * Custom Field Functions
 */

function delete_field(obj_type, id){
	var r=confirm("Are you sure you want to delete this field and all field data?");
	if(!r)
		return;
	new Ajax.Request('/c/fields/table/'+obj_type, {
		method: 'post',
		parameters: {postaction: 'delete_field', p0: id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}

function deleteall_fields(obj_type){
	var ids = get_checked();
	if(!ids)
		return;
	var r=confirm("Are you sure you want to delete the selected fields and all field data?");
	if(!r)
		return;
	new Ajax.Request('/c/fields/table/'+obj_type, {
		method: 'post',
		parameters: {postaction: 'delete_field', p0: ids},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});	
}

function move_field(dir, obj_type, field_id){
	new Ajax.Request('/c/fields/table/'+obj_type, {
		method: 'post',
		parameters: {postaction: 'move_field', p0: dir, p1: field_id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}

function move_fieldoption(dir, field_id, option_id){
	new Ajax.Request('/c/fieldoptions/table/'+field_id, {
		method: 'post',
		parameters: {postaction: 'move_option', p0: dir, p1: option_id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}

function move_row(dir, obj_type, field_id){
	new Ajax.Request('/c/fields/table/'+obj_type, {
		method: 'post',
		parameters: {postaction: 'move_field', p0: dir, p1: field_id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}


function delete_fieldoption(field_id, option_id){
	var r=confirm("Are you sure you want to delete this option?");
	if(!r)
		return;
	new Ajax.Request('/c/fieldoptions/table/'+field_id, {
		method: 'post',
		parameters: {postaction: 'delete_option', p0: option_id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}

function deleteall_options(field_id){
	var ids = get_checked();
	if(!ids)
		return;
	var r=confirm("Are you sure you want to delete the selected options?");
	if(!r)
		return;
	new Ajax.Request('/c/fieldoptions/table/'+field_id, {
		method: 'post',
		parameters: {postaction: 'delete_option', p0: ids},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});	
}

/* 
 * Candidate Functions
 */

function show_popup_addnote() {
	close_popup();
	$('note').setValue('');
	$('addnotedialog').style.display = 'block';
	$('note').focus();
}

function set_appvalue(appid, value, fmid, ts) {	
	if(appid == 0){
		appid = get_checked();
		if(!appid)
			return;
	}

	if(value == null)
		value = $('field_'+fmid).value;
		
	var f = document.createElement('form'); 
	f.style.display = 'none';
	ts.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = ts.href;
	insert_hidden_input(f, 'postaction', 'update_appvalue');
	insert_hidden_input(f, 'p0', appid);
	insert_hidden_input(f, 'field_'+fmid, value);
	f.submit();
}

function set_stage(appid, value, ts) {
	
	if(appid == 0){
		appid = get_checked();
		if(!appid)
			return;
	}

	if(value == null)
		value = $('stage').value;
		
	var f = document.createElement('form'); 
	f.style.display = 'none';
	ts.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = ts.href;
	insert_hidden_input(f, 'postaction', 'update_stage');
	insert_hidden_input(f, 'p0', appid);
	insert_hidden_input(f, 'p1', value);
	f.submit();
}

function submit_note(appid) {
	if(appid == 0){
		appid = get_checked();
		if(!appid)
			return;
	}
	
	var note = $F('note');
	if(note == ''){
		alert('Please enter note text');
		return;
	}
	
	new Ajax.Request('/c/appdetail/notetable/'+appid, {
		method: 'post',
		parameters: {postaction: 'add_note', p0: appid, p1: note}, 
		onSuccess: function(transport) {
		close_popup();
			$('historytable').update(transport.responseText);
		}
	});
}

function delete_note(id, appid) {
	
	var r=confirm("Are you sure you want to delete this note?");
	if(!r)
		return;
	
	new Ajax.Request('/c/appdetail/notetable/'+appid, {
		method: 'post',
		parameters: {postaction: 'delete_note', p0: id},
		onSuccess: function(transport) {
			$('historytable').update(transport.responseText);
		}
	});
}

function send_email(appid, type){
	
	if(appid == 0){
		appid = get_checked();
		if(!appid)
			return false;
	}
			
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "";
	insert_hidden_input(f, 'postaction', 'compose_email');
	insert_hidden_input(f, 'p0', type);
	insert_hidden_input(f, 'toids', appid);
	f.submit();
	return false;
}

function update_email_status(eid, status){
	
	if(eid == 0){
		eid = get_checked();
		if(!eid)
			return false;
	}
	
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "";
	insert_hidden_input(f, 'postaction', 'update_email_status');
	insert_hidden_input(f, 'eids', eid);
	insert_hidden_input(f, 'status', status);
	f.submit();
	return false;
}

function update_email_page(){
	if($F('include_qlink') == 1){
		$('choose_qe_row').show();
	}
	else{
		$('choose_qe_row').hide();
	}
}

function forward_to_user(appid){
	
	if(appid == 0){
		appid = get_checked();
		if(!appid)
			return false;
	}
			
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "";
	insert_hidden_input(f, 'postaction', 'forward_to_user');
	insert_hidden_input(f, 'toids', appid);
	f.submit();
	return false;
}

function print_application(appid){
	
	if(appid == 0){
		appid = get_checked();
		if(!appid)
			return false;
	}
			
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "";
	f.target = "_blank";
	insert_hidden_input(f, 'postaction', 'print_application');
	insert_hidden_input(f, 'appids', appid);
	f.submit();
	return false;
}

function delete_application(appid, ts){

	if(appid == 0){	
		appid = get_checked();
		if(!appid)
			return;
		var r=confirm("Are you sure you want to delete the selected candidates?");
		if(!r)
			return;
	}
	else{	
		var r=confirm("Are you sure you want to delete this candidate?");
		if(!r)
			return;
	}
	
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	ts.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = ts.href;
	insert_hidden_input(f, 'postaction', 'delete_application');
	insert_hidden_input(f, 'p0', appid);
	f.submit();
}

function delete_attachment(att_id){
	var r=confirm("Are you sure you want to delete this attachment?");
	if(!r)
		return;
		
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "";
	insert_hidden_input(f, 'postaction', 'delete_attachment');
	insert_hidden_input(f, 'p0', att_id);
	f.submit();		
}

function load_adcontent(view, app_eid){
	
	new Ajax.Request('/c/appdetail/'+view+'/'+app_eid, {
		method: 'get',
		onSuccess: function(transport) {
			$('appdetailtabs').update(transport.responseText);
		}
	});	
}

function change_template(url){
	
	var id = $('template').value;
	if(id == '')
		return;
		
	new Ajax.Request(url+id, {
		method: 'get',
		onSuccess: function(transport) {
			$('formtable').replace(transport.responseText);
		}
	});	
}

/* 
 * Table Functions
 */
 
function changeview(id){
	var show = $('show'+id).value;
	var newlocation;
	if(window.location.search.indexOf('show'+id+'=') == -1){
		newlocation = window.location.href;
		newlocation += (window.location.href.indexOf('?') != -1 ? '&' : '?');
		newlocation += 'show'+id+'='+show;		
	}
	else{
		re = new RegExp('show'+id+'=[^&]*');
		newlocation = window.location.href.replace(re, 'show'+id+'='+show);
	}
	window.location = newlocation;
}

function changefilter(key){
	var show = encodeURIComponent($(key).value);
	var newlocation;
	if(window.location.search.indexOf(key+'=') == -1){
		newlocation = window.location.href;
		newlocation += (window.location.href.indexOf('?') != -1 ? '&' : '?');
		newlocation += key+'='+show;		
	}
	else{
		re = new RegExp(key+'=[^&]*');
		newlocation = window.location.href.replace(re, key+'='+show);
	}
	window.location = newlocation;
}
  
function checkall(){
	var check = $('globalcheck').checked;
	$$('.tablecheck').each(function(s){
		s.checked = check;
	});
}

function get_checked(){
	var ids = $$('.tablecheck').inject([], function(array, s){
		if (s.checked)
			array.push(s.id);
		return array;
	}).join(',');
	if (ids == '') {
		alert('Please select items from the table.');
		return false;
	}
	return ids;
}

function dosort(n){

	var sort = geturlparam('sort');
	var sortdir = geturlparam('sortdir');
	
	if(sort == null || sort != n){
		sort = n;
		sortdir = 'a';
	}
	else{
		sortdir = (sortdir == 'a' ? 'd' : 'a');
	}
	
	var newlocation = window.location.href;
	newlocation = addurlparam(newlocation, 'sort', sort);
	newlocation = addurlparam(newlocation, 'sortdir', sortdir);
		
	window.location = newlocation;	
}

function dopage(n){
	
	var page = n;
	var newlocation = window.location.href;
	newlocation = addurlparam(newlocation, 'pge', page);
		
	window.location = newlocation;
}

/* 
 * Launch Functions
 */
 
Event.observe(window, 'load', function() {	 
	init_linkcopy();
}); 

function init_linkcopy(){
	$$('.linkcopy').each(function(n){
		Event.observe(n, 'click', linkcopy_click);
		Event.observe(n, 'mousedown', linkcopy_click);
		Event.observe(n, 'keydown', linkcopy_keydown);
	});	
}

function linkcopy_click(evt){
	Event.element(evt).select();
}

function linkcopy_keydown(evt){
	if(evt['ctrlKey']) return;
	Event.stop(evt);
}

function change_launchlinks(job_eid){
	var source = $('launch_source').options[$('launch_source').selectedIndex].value;
	
	new Ajax.Request('/c/launch/linkstable/'+job_eid+'/'+source, {
		method: 'get',
		onSuccess: function(transport) {
			$('launchlinkstable').update(transport.responseText);
			init_linkcopy();
		}
	});		
}

/*
 * Forward Applicants
 */

function show_selectcontacts() {
	
	var contacts = get_to_contacts(true, false);
		
	$$('.inputcheck').each(function(s){
		var id1 = s.id.substr(8);
		s.checked = false;
		for(var i=0; i<contacts.length; i++){
			var id2 = contacts[i].id.substr(14);
			if(id1 == id2){
				s.checked = true;
				break;
			}	
		}
	});
	
	close_newcontact();
	$('selectcontacts').show();	
}

function close_selectcontacts() {
	
	$('selectcontacts').hide();
}

function submit_selectcontacts() {
	
	var contacts = get_to_contacts(false, true);
		
	$$('.inputcheck').each(function(s){
		if(s.id.substr(0, 8) == 'contact_' && s.checked){
			var id = 'selectcontact_' + s.id.substr(8);
			var name = s.nextSibling.nodeValue.strip();
			contacts[contacts.length] = {id:id, name:name};
		}
	});
	
	build_to_contacts(contacts);
	
	close_selectcontacts();
}

function get_to_contacts(include_select, include_new) {
	
	var c = new Array();
	
	$$('.to_contact').each(function(s){
		var id = s.id;
		var name = s.innerHTML;
		if((id.startsWith('selectcontact_') && include_select) || (id.startsWith('newcontact_') && include_new))
			c[c.length] = {id:id, name:name};
	});
	
	return c;
}

function build_to_contacts(contacts) {

	var html = '';
	
	contacts.sort(function(a, b){
		if(a.name > b.name)
			return 1;
		else if(a.name < b.name)
			return -1;
		else
			return 0;
	});
	
	for(var i=0; i<contacts.length; i++){
		var c=contacts[i];
		if(i > 0)
			html += '<br />';
		html += '<div id="' + c.id + '" class="to_contact">' + c.name.escapeHTML() + '</div>&nbsp;(<a href="javascript:remove_contact(\'' + c.id + '\')">Remove</a>)';
	}
	
	if(html == '')
		html = '(None Selected)';
	$('tocontacts').update(html);
}

function show_newcontact() {

	$('newcontact_name').setValue('');
	$('newcontact_email').setValue('');
	
	close_selectcontacts();
	$('newcontact').show();	
}

function close_newcontact() {
	$('newcontact').hide();
}

function submit_newcontact() {
		
	var contacts = get_to_contacts(true, true);
	
	var name = $F('newcontact_name');
	var email = $F('newcontact_email');
	var timezone = $F('newcontact_timezone');
	var id = escape("newcontact_" + name + "##" + email + '##' + timezone);
	contacts[contacts.length] = {id:id, name:name};
	
	build_to_contacts(contacts);
	
	close_newcontact();
}

function remove_contact(id){
	
	var contacts = get_to_contacts(true, true);
	var new_contacts = Array();
	
	for(var i=0; i<contacts.length; i++){
		var c = contacts[i];
		if(unescape(c.id) != id)
			new_contacts[new_contacts.length] = c;
	}
	
	build_to_contacts(new_contacts);
}
 
function presubmit_contacts(){
	
	var f=$('mainform');
	var n=1;
	$$('.to_contact').each(function(s){
		var id = s.id;
		insert_hidden_input(f, 'c'+n+'_id', id);
		n++;
	});
}
 
/*
 * User Functions
 */
 
function delete_user(id){

	var r;
	if(id == 0){
		id = get_checked();
		if(!id)
			return;
		r=confirm("Are you sure you want to delete the selected users?");
	}
	else
		r=confirm("Are you sure you want to delete this user?");
	if(!r)
		return;
	
	new Ajax.Request('/c/users/table', {
		method: 'post',
		parameters: {postaction: 'delete_user', p0: id},
		onSuccess: function(transport) {
			$('displaytable').update(transport.responseText);
		}
	});
}
 
function update_userform(){
	
	var type = $F('type');
	$$('.userrow').each(function(s){
		if(type == 1)
			s.show();
		else
			s.hide();
	});
}

/*
 * Logger
 */

function enable_logger(){
	var myContainer = document.body.appendChild(document.createElement("div"));
	var myLogReader = new YAHOO.widget.LogReader(myContainer);
	document.body.className = "yui-skin-sam";
}

/*
 * Reports
 */

function postback(formid, url, action){
	
	var post_params = $(formid).serialize(true);
	delete post_params['postaction'];
	if(action != null)
		post_params['postbackaction'] = action;
	
	new Ajax.Request(url, {
		method: 'post',
		parameters: post_params,
		onSuccess: function(transport) {
			$('content').update(transport.responseText);
		}
	});
}
 
function set_current_filter(r_eid){
	
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "#";
	insert_hidden_input(f, 'postaction', 'set_current_filter');
	insert_hidden_input(f, 'p0', r_eid);
	f.submit();
	return;
}

/*
 * Search
 */

function do_search(){

	var keywords = $('keywords').value;
	
	var start = 0;
	var end = 0;	
	if($('daterange_custom').checked){
		start = $('startdate').value;
		end = $('enddate').value;
	}
	
	var url = '/search/show/?keywords='+encodeURIComponent(keywords)+'&start='+start+'&end='+end;
	window.location = url;	
}

function add_to_job(job_id, appid){

	if(appid == null){
		appid = get_checked();
		if(!appid)
			return;
	}
		
	new Ajax.Request('/', {
		method: 'post',
		parameters: {postaction: 'add_to_job', p0: job_id, p1: appid},
		onSuccess: function(transport) {
			alert('Success!');
			close_popup();
		},
		onError: function(transport) {
			close_popup();
		}
	});	
}

/*
 * General
 */
 
function html_to_element(html){
	var e = new Element('div');
	e.update(html);
	return e.down();
}

function show_popup(dialogid) {
	close_popup();
	$(dialogid).style.display = 'block';
	
	var uiLayer = YAHOO.util.Dom.getRegion('selectLink');
	var overlay = YAHOO.util.Dom.get('uploaderOverlay');
	YAHOO.util.Dom.setStyle(overlay, 'width', uiLayer.right-uiLayer.left + "px");
	YAHOO.util.Dom.setStyle(overlay, 'height', uiLayer.bottom-uiLayer.top + "px");	
}

function close_popup() {
	$$('.popupdialog').each(function(s){
		s.style.display = 'none';
	});
}

function insert_hidden_input(f, name, value){
	var input = document.createElement("input");
	input.setAttribute("type", "hidden");
	input.setAttribute("name", name);
	input.setAttribute("value", value);
	f.appendChild(input);	
}

function limitText(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	}
}

function geturlparam(param){
	
	var re = new RegExp(param+'=([^&]*)');
	var match = window.location.href.match(re);
	if(match == null)
		return null;
	else
		return match[1];
}

function addurlparam(url, pname, pvalue){

	var newurl;
	if(url.indexOf(pname+'=') == -1){
		newurl = url;
		newurl += (url.indexOf('?') != -1 ? '&' : '?');
		newurl += (pname+'='+pvalue);
	}
	else{
		var re = new RegExp(pname + '=[^&]*');
		newurl = url.replace(re, pname+'='+pvalue);
	}

	return newurl;
}

function showmsg(msg){
	alert(msg);
}

function setfocus(){
	var bFound = false;

	if(document.forms == null)
		return;
		
	// for each form
	for (f = 0; f < document.forms.length; f++) {
		// for each element in each form
		for (i = 0; i < document.forms[f].length; i++) {
			try{
				if(document.forms[f][i].tagName.toLowerCase() != 'button'){
					document.forms[f][i].focus();
					var bFound = true;
				}
			}
			catch(e){}
			
			// if found in this element, stop looking
			if (bFound == true)
					break;
		}
		// if found in this form, stop looking
		if (bFound == true)
			break;				
	}
}

function showhelp(id){
	var url = '/help/show/' + id
	var helpwin = window.open(url, 'appstackhelp', 'width=700, height=500, toolbar=no, status=no, menubar=no, resizable=yes, scrollbars=yes');
	helpwin.focus();
}

Event.observe(window, 'load', function() {	 
	// Comment out line below to diable logger
	//enable_logger();
	setfocus();
}); 

/*
 * Global
 */
 
Ajax.Responders.register({	 
	onCreate: function() {		 
		if (Ajax.activeRequestCount === 1) {
			$('loading').show();
		}
	},	 
	onComplete: function() {		 
		if (Ajax.activeRequestCount === 0) {
			$('loading').hide();
		}
	} 
});

/*
 * Timezone functions
 */
 
function get_timezone_name() {
	tmSummer = new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0));
	so = -1 * tmSummer.getTimezoneOffset();
	tmWinter = new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0));
	wo = -1 * tmWinter.getTimezoneOffset();

	if (-660 == so && -660 == wo) return 'Pacific/Midway';
	if (-600 == so && -600 == wo) return 'Pacific/Tahiti';
	if (-570 == so && -570 == wo) return 'Pacific/Marquesas';
	if (-540 == so && -600 == wo) return 'America/Adak';
	if (-540 == so && -540 == wo) return 'Pacific/Gambier';
	if (-480 == so && -540 == wo) return 'US/Alaska';
	if (-480 == so && -480 == wo) return 'Pacific/Pitcairn';
	if (-420 == so && -480 == wo) return 'US/Pacific';
	if (-420 == so && -420 == wo) return 'US/Arizona';
	if (-360 == so && -420 == wo) return 'US/Mountain';
	if (-360 == so && -360 == wo) return 'America/Guatemala';
	if (-360 == so && -300 == wo) return 'Pacific/Easter';
	if (-300 == so && -360 == wo) return 'US/Central';
	if (-300 == so && -300 == wo) return 'America/Bogota';
	if (-240 == so && -300 == wo) return 'US/Eastern';
	if (-240 == so && -240 == wo) return 'America/Caracas';
	if (-240 == so && -180 == wo) return 'America/Santiago';
	if (-180 == so && -240 == wo) return 'Canada/Atlantic';
	if (-180 == so && -180 == wo) return 'America/Montevideo';
	if (-180 == so && -120 == wo) return 'America/Sao_Paulo';
	if (-150 == so && -210 == wo) return 'America/St_Johns';
	if (-120 == so && -180 == wo) return 'America/Godthab';
	if (-120 == so && -120 == wo) return 'America/Noronha';
	if (-60 == so && -60 == wo) return 'Atlantic/Cape_Verde';
	if (0 == so && -60 == wo) return 'Atlantic/Azores';
	if (0 == so && 0 == wo) return 'Africa/Casablanca';
	if (60 == so && 0 == wo) return 'Europe/London';
	if (60 == so && 60 == wo) return 'Africa/Algiers';
	if (60 == so && 120 == wo) return 'Africa/Windhoek';
	if (120 == so && 60 == wo) return 'Europe/Amsterdam';
	if (120 == so && 120 == wo) return 'Africa/Harare';
	if (180 == so && 120 == wo) return 'Europe/Athens';
	if (180 == so && 180 == wo) return 'Africa/Nairobi';
	if (240 == so && 180 == wo) return 'Europe/Moscow';
	if (240 == so && 240 == wo) return 'Asia/Dubai';
	if (270 == so && 210 == wo) return 'Asia/Tehran';
	if (270 == so && 270 == wo) return 'Asia/Kabul';
	if (300 == so && 240 == wo) return 'Asia/Baku';
	if (300 == so && 300 == wo) return 'Asia/Karachi';
	if (330 == so && 330 == wo) return 'Asia/Calcutta';
	if (345 == so && 345 == wo) return 'Asia/Katmandu';
	if (360 == so && 300 == wo) return 'Asia/Yekaterinburg';
	if (360 == so && 360 == wo) return 'Asia/Colombo';
	if (390 == so && 390 == wo) return 'Asia/Rangoon';
	if (420 == so && 360 == wo) return 'Asia/Almaty';
	if (420 == so && 420 == wo) return 'Asia/Bangkok';
	if (480 == so && 420 == wo) return 'Asia/Krasnoyarsk';
	if (480 == so && 480 == wo) return 'Australia/Perth';
	if (540 == so && 480 == wo) return 'Asia/Irkutsk';
	if (540 == so && 540 == wo) return 'Asia/Tokyo';
	if (570 == so && 570 == wo) return 'Australia/Darwin';
	if (570 == so && 630 == wo) return 'Australia/Adelaide';
	if (600 == so && 540 == wo) return 'Asia/Yakutsk';
	if (600 == so && 600 == wo) return 'Australia/Brisbane';
	if (600 == so && 660 == wo) return 'Australia/Sydney';
	if (630 == so && 660 == wo) return 'Australia/Lord_Howe';
	if (660 == so && 600 == wo) return 'Asia/Vladivostok';
	if (660 == so && 660 == wo) return 'Pacific/Guadalcanal';
	if (690 == so && 690 == wo) return 'Pacific/Norfolk';
	if (720 == so && 660 == wo) return 'Asia/Magadan';
	if (720 == so && 720 == wo) return 'Pacific/Fiji';
	if (720 == so && 780 == wo) return 'Pacific/Auckland';
	if (765 == so && 825 == wo) return 'Pacific/Chatham';
	if (780 == so && 780 == wo) return 'Pacific/Enderbury'
	if (840 == so && 840 == wo) return 'Pacific/Kiritimati';
	return 'US/Pacific';
}

function select_timezone(){
	var tz = get_timezone_name();
	var options = document.getElementById('timezone').options;
	for(var i=0; i<options.length; i++){
		if(options[i].value == tz)
			options[i].selected = true;
	}
}

/*
 * Question Table drag-drop
 */
 
DDApp = {
	init: function() {
		new YAHOO.util.DDTarget("questiontable");
		$('questiontable').select('tr').each(function(row,n){
			if(n>0)
				qrow_init(row);
		});
	}	
};

DDList = function(id, sGroup, config) {

	DDList.superclass.constructor.call(this, id, sGroup, config);

	var el = this.getDragEl();
	YAHOO.util.Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent

	this.goingUp = false;
	this.lastY = 0;
};

YAHOO.extend(DDList, YAHOO.util.DDProxy, {
	startDrag: function(x, y) {

		// make the proxy look like the source element
		var dragEl = this.getDragEl();
		var clickEl = this.getEl();
		YAHOO.util.Dom.setStyle(clickEl, "visibility", "hidden");

		var html = clickEl.innerHTML;
		html = html.replace(/<td>/i, '<td width="10%">');
		html = html.replace(/<td>/i, '<td width="80%">');
		html = html.replace(/<td>/i, '<td width="10%">');
		dragEl.innerHTML = '<table width="100%">'+html+'</table>';

		YAHOO.util.Dom.setStyle(dragEl, "color", YAHOO.util.Dom.getStyle(clickEl, "color"));
		YAHOO.util.Dom.setStyle(dragEl, "backgroundColor", YAHOO.util.Dom.getStyle(clickEl, "backgroundColor"));
		YAHOO.util.Dom.setStyle(dragEl, "border", "2px solid gray");
	},

	endDrag: function(e) {
		
		var srcEl = this.getEl();
		var proxy = this.getDragEl();

		// Show the proxy element and animate it to the src element's location
		YAHOO.util.Dom.setStyle(proxy, "visibility", "");
		var a = new YAHOO.util.Motion( 
			proxy, { 
				points: { 
					to: YAHOO.util.Dom.getXY(srcEl)
				}
			}, 
			0.2, 
			YAHOO.util.Easing.easeOut 
		)
		var proxyid = proxy.id;
		var thisid = this.id;

		// Hide the proxy and show the source element when finished with the animation
		a.onComplete.subscribe(function() {
				YAHOO.util.Dom.setStyle(proxyid, "visibility", "hidden");
				YAHOO.util.Dom.setStyle(thisid, "visibility", "");
			});
		a.animate();
	},

	onDrag: function(e) {

		// Keep track of the direction of the drag for use during onDragOver
		var y = YAHOO.util.Event.getPageY(e);

		if (y < this.lastY) {
			this.goingUp = true;
		} else if (y > this.lastY) {
			this.goingUp = false;
		}

		this.lastY = y;
	},

	onDragOver: function(e, id) {
	
		var srcEl = this.getEl();
		var destEl = YAHOO.util.Dom.get(id);

		// We are only concerned with tr items, we ignore the dragover
		// notifications for the table.
		if (destEl.nodeName.toLowerCase() == "tr") {
			var orig_p = srcEl.parentNode;
			var p = destEl.parentNode;

			if (this.goingUp) {
				p.insertBefore(srcEl, destEl); // insert above
			} else {
				p.insertBefore(srcEl, destEl.nextSibling); // insert below
			}

			YAHOO.util.DragDropMgr.refreshCache();
		}
	}
});
YAHOO.util.Event.onDOMReady(DDApp.init, DDApp, true);

/*
 * General Table Functions
 */
 
function delete_row(id, show_url, post_action){

	var r;
	if(id == 0){
		id = get_checked();
		if(!id)
			return;
		r=confirm("Are you sure you want to delete the selected items?");
	}
	else
		r=confirm("Are you sure you want to delete this item?");
	if(!r)
		return;
	
	new Ajax.Request(show_url, {
		method: 'post',
		parameters: {postaction: post_action, p0: id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}

function move_row(dir, id, show_url, post_action){
	new Ajax.Request(show_url, {
		method: 'post',
		parameters: {postaction: post_action, p0: dir, p1: id},
		onSuccess: function(transport) {
			var displaytable = $('displaytable');
			displaytable.update(transport.responseText);
		}
	});
}

function delete_rowitem(id, post_action, ts){

	if(id == 0){
		id = get_checked();
		if(!id)
			return;
		r=confirm("Are you sure you want to delete the selected items?");
	}
	else
		r=confirm("Are you sure you want to delete this item?");
	if(!r)
		return;
	
	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	ts.parentNode.appendChild(f); 
	f.method = 'POST'; 
	f.action = ts.href;
	insert_hidden_input(f, 'postaction', post_action);
	insert_hidden_input(f, 'p0', id);
	f.submit();	
}

function do_post(post_action){

	var f = document.createElement('form'); 
	f.style.display = 'none'; 
	document.body.appendChild(f);
	f.method = 'POST'; 
	f.action = "";
	insert_hidden_input(f, 'postaction', post_action);
	f.submit();
	return false;
}

function sb1(name){

	var f = $('mainform');
	if(f == null){
		var f = document.createElement('form'); 
		f.style.display = 'none'; 
		document.body.appendChild(f);
		f.method = 'POST'; 
		f.action = "";		
	}
	
	insert_hidden_input(f, name, 1);
	f.submit();
	return false;
}

function do_preview_change(url){
    
	var id = $('select_template').value;
	new Ajax.Request(url+id, {
		method: 'get',
		onSuccess: function(transport) {
			$('preview').update(transport.responseText);
		}
	});
}

function write_email(username, domain, display){
	var email = username + '@' + domain;
	if(display == null)
		display = email;
	document.write('<a href="mailto:' + email + '">' + display + '</a>');
}

function show_question_filter_box(){
    $j.modal.close();
    $j.post('/c/questionnaires/ajax_show_questionnaires', function(o){
        $j.modal(o, {containerCss:{height:450, width:300}});        
    });     
}

function show_questions(q_eid){
    $j.modal.close();
    $j.post('/c/questionnaires/ajax_show_questions', {p0: q_eid}, function(o){
        $j.modal(o, {containerCss:{height:450, width:500}});        
    });        
}

function add_question_to_form(q_id){
    $j.post('/c/questionnaires/ajax_add_question', {q_id: q_id}, function(o){
        $j('#filter_fields').append(o)        
    })
}

function remove_filter_field(q_id){
    $j('#field_' + q_id).remove();
    $j.post('/c/questionnaires/ajax_remove_question', {q_id: q_id});
}

