	
	// Utilities
	
	function GetTarget(e)
	{
		if(e.target)
		{
			var event_target = e.target;
		}
		else if(e.srcElement)
		{
			var event_target = e.srcElement;
		}
		
		if(event_target.nodeType == 3) // defeat Safari bug
   		{
   			var event_target = event_target.parentNode
   		}
   		
   		return event_target;
	}
	
	// Construction
	
	function AddCriteria()
	{	
		// add a li to the criteria ol:
		var criteria_ol = document.getElementById('criteria_list');
		var new_item = document.createElement('li');
		
		// set up the criteria box
		
		// line break to keep index in right place
		new_item.appendChild(MakeTitleBar('Criteria'));
		
		
		// question textarea
		var question_textarea = MakeTextArea(40, 6);
		new_item.appendChild(question_textarea);
		
		// delete button
		var delete_input = MakeButton("\u2715 Delete criteria", DeleteItem);
		new_item.appendChild(delete_input);
		
		// the options ul:
		var options_ul = document.createElement('ul');
		new_item.appendChild(options_ul);
		
		// the add option link
		var options_input = MakeButton('+ Add option', AddOption);
		new_item.appendChild(options_input);
		
		// append the item to the list
		criteria_ol.appendChild(new_item);
		
		// refresh the table
		RefreshTable();
	}
	
	function MakeTitleBar(title)
	{
		var title_bar = document.createElement('div');
		SetClass(title_bar, 'drag_bar');
		
		var up_button = CreateElement(title_bar, 'a');
		up_button.innerHTML = "&#9650;";
		up_button.setAttribute('onclick', 'moveUp(this)');
		
		var down_button = CreateElement(title_bar, 'a');
		down_button.innerHTML = "&#9660;";
		down_button.setAttribute('onclick', 'moveDown(this)');
		
		title_bar.innerHTML += title;
		
		return title_bar;
	}
	
	function MakeBR()
	{
		var my_br = document.createElement('br');
		return my_br;
	}
	
	function MakeTextArea(cols, rows)
	{
		var my_textarea = document.createElement('textarea');
		my_textarea.setAttribute('cols', cols);
		my_textarea.setAttribute('rows', rows);
		return my_textarea;
	}
	
	function MakeButton(title, function_call)
	{
		var my_button = document.createElement('input');
		my_button.setAttribute('type', 'button');
		my_button.setAttribute('value', title);
		my_button.onclick = eval(function_call);
		
		return my_button;
	}
	
	function MakeSelect()
	{
		var my_select = document.createElement('select');
		
		// arguments are in pairs (key, value)
		for(var i = 0; i < arguments.length; i += 2)
		{
			var option_key = arguments[i];
			var option_value = arguments[i + 1];
			
			var my_option = document.createElement('option');
			my_option.setAttribute('value', option_key);
			my_option.innerHTML = option_value;
			my_select.appendChild(my_option);
		}
		return my_select;
	}
	
	function RefreshTable()
	{
		// stupid browsers
		var table = document.getElementById('form_details');
		table.insertRow(0);
		table.deleteRow(0);
	}
	
	// Pretty Dialog
	
	function SetClass(item, css_class)
	{
		item.className = css_class;
		item.setAttribute('class', css_class);
	}
	
	function CreateElement(parent_node, tagname, css_class)
	{
		var new_element = document.createElement(tagname);
		
		if(css_class) SetClass(new_element, css_class);
		
		parent_node.appendChild(new_element);
		return new_element;
	}
	
	function ShowModalDialog(message, options)
	{
		// options is an associative array with format:
		// ('function': "display as")
		
		var modal_dialog = CreateElement(document.body, 'div', 'modal_dialog');
		modal_dialog.setAttribute('id', 'modal_dialog');
		
		var dialog_text = CreateElement(modal_dialog, 'p', 'dialog_text');
		dialog_text.innerHTML = message;
		
		for(var function_name in options)
		{
			var each_button = MakeButton(options[function_name], function_name);
			SetClass(each_button, 'button_like');
			modal_dialog.appendChild(each_button);
		}
	}
	
	function CloseDialog()
	{
		var modal_dialog = document.getElementById('modal_dialog');
		modal_dialog.parentNode.removeChild(modal_dialog);
	}
	
	
	
	// Actions
	
	function AddOption(e)
	{
		if(!e) var e = window.event;
		
		// find the options ul
		var source = GetTarget(e);
		var uls = source.parentNode.getElementsByTagName('ul');
		var options_ul = uls[0];
		
		// make a new li
		var new_li = document.createElement('li');
		new_li.appendChild(MakeTitleBar('Option'));
		
		// now add an appropriate text entry form
		var option_text = MakeTextArea(35, 4);
		new_li.appendChild(option_text);
		
		
		// add the option type input
		var type_select = MakeSelect('option', "&#9633; Checkbox",
									 'option_array', "&#9633; Options separated by | pipes",
									 'bullet_array', "&#9679; Bullets separated by | pipes",
									 'yes_no', "&#9633; Yes &#9633; No", 
									 'yes_no_na', "&#9633; Yes &#9633; No &#9633; NA", 
									 'specify', "&#9633; (specify)_____", 
									 'bullet', "&#9679; Informative text");
		new_li.appendChild(type_select);
		
		// offer a delete button
		var delete_button = MakeButton("\u2715 Delete option", DeleteItem);
		new_li.appendChild(delete_button);
		
		// put the li into the ul
		options_ul.appendChild(new_li);
		
		// refresh the table
		RefreshTable();
	}
	
	function DeleteItem(e)
	{
		if(!e) var e = window.event;
		
		// get the li that spawned this:
		var source = GetTarget(e);
		var li = source.parentNode;
		
		// delete it
		li.parentNode.removeChild(li);
	}
	
	
	// Submit
	
	function SubmitForm()
	{
		// go through the form and figure out names for everything
		var criteria_ol = document.getElementById('criteria_list');
		var criteria = criteria_ol.childNodes;
		
		for(var i = 0; i < criteria.length; i++)
		{
			if(criteria[i].nodeName == 'LI')
			{
				var criteria_textarea = criteria[i].getElementsByTagName('textarea')[0];
				criteria_textarea.setAttribute('name', 'criteria[' + i + ']');
				
				// now process the options
				var options = criteria[i].getElementsByTagName('li');
				var num_options = options.length;
				
				for(var j = 0; j < num_options; j++)
				{
					// textarea
					var options_textarea = options[j].getElementsByTagName('textarea')[0];
					options_textarea.setAttribute('name', 'options[' + i + '][' + j + ']');
					
					// option type select
					var options_select = options[j].getElementsByTagName('select')[0];
					options_select.setAttribute('name', 'type[' + i + '][' + j + ']');
				}
			}
		}
		
		// now make the form submit
		var form = document.getElementById('pdf_form');
		form.submit();
	}
	
	function SaveAsForm()
	{
		// mark a flag in the form and then submit it
		var save_flag = document.getElementById('SaveMode');
		save_flag.value = 'SaveAs';
		
		SubmitForm();
	}
	
	function DeleteForm()
	{
		var options = {	'Form_ConfirmDelete':	"Yes",
						'CloseDialog':			"No" };
		ShowModalDialog("Are you sure you want to delete this form?", options);
	}
	
	function Form_ConfirmDelete(e)
	{
		CloseDialog();
		var save_flag = document.getElementById('SaveMode');
		save_flag.value = 'Delete';
		
		SubmitForm();
	}
	
	function CancelForm()
	{
		var options = {	'Form_ConfirmCancel':	"Yes",
						'CloseDialog':			"No" };
		ShowModalDialog("Are you sure you want to close this form without saving?", options);
	}
	
	function Form_ConfirmCancel(e)
	{
		CloseDialog();
		
		// go to the form list
		document.location = root + 'forms';
	}
	
	// Move items
	
	function moveDown(calling_link)
	{
		var chosen_li = calling_link.parentNode.parentNode;
		var to_swap = chosen_li.nextSibling;
		
		if(to_swap)
		{
			var the_list = chosen_li.parentNode;
			the_list.removeChild(to_swap);
			the_list.insertBefore(to_swap, chosen_li);
		}
		
		return true;
	}
	
	function moveUp(calling_link)
	{
		var chosen_li = calling_link.parentNode.parentNode;
		var to_swap = chosen_li.previousSibling;
		
		if(to_swap)
		{
			var the_list = chosen_li.parentNode;
			the_list.removeChild(chosen_li);
			the_list.insertBefore(chosen_li, to_swap);
		}
		
		return true;
	}
	
	// External
	
	function ExecRegisterEventHandler(name, call)
	{
		var inputs = document.getElementsByName(name);
		
		for(var i = 0; i < inputs.length; i++)
		{
			inputs[i].onclick = call;
		}
	}
	
	function RegisterEventHandlers()
	{
		ExecRegisterEventHandler('add_option', AddOption);
		ExecRegisterEventHandler('delete_item', DeleteItem);
	}
	
	
	// --- BELOW: For Fax PDF Lookup Things
	
   function lookupMember() {
      member_id = document.getElementById('member_id').value;
      status = document.getElementById('patient_status');
      
      status.innerHTML = 'Loading...';
      
      getData(root  + 'Ajax/getMember', 'member_id=' + member_id, displayData);
   }
   
   function lookupPharmacy() {
      ncpdp = document.getElementById('ncpdp').value;
      status = document.getElementById('pharmacy_status');
      
      status.innerHTML = 'Loading...';
      
      getData(root  + 'Ajax/getPharmacy', 'ncpdp=' + ncpdp, displayData);
   }
   
   function lookupPhysician() {
      dea = document.getElementById('dea').value;
      status = document.getElementById('physician_status');
      
      status.innerHTML = 'Loading...';
      
      getData(root  + 'Ajax/getPhysician', 'dea=' + dea, displayData);
   }
   
   function displayData(data) {
      if (data == 1) {
         status.innerHTML = 'Not found.';
         return;
      }
      
      pairs = data.split('|');
      
      for (var i = 0; i < pairs.length; i++) {
         value = pairs[i];
         datum = value.split(':');
         key = document.getElementById(datum[0]);
         if (key) {
            key.value = datum[1];
         }
      }
      
      status.innerHTML = '';
   }

	function saveRow(id)
	{
		id = document.getElementById('id_' + id).value;
		pa = document.getElementById('pa_form_' + id).value;
		qvt = document.getElementById('qvt_form_' + id).value;
		// TODO: Add new forms 
		
		var opts = 'id=' + id + '&pa_form=' + pa + '&qvt_form=' + qvt;
		
		getData(root + 'Ajax/UpdateLink', opts,  showUpdateFeedback);
		
	}
	
	function deleteRow(id)
	{
		id = document.getElementById('id_' + id).value;
		
		var opts = 'id=' + id;
		
		getData(root + 'Ajax/DeleteLink', opts);
		
		var row = document.getElementById('row_' + id);
		row.parentNode.removeChild(row);
	}
	
	function showUpdateFeedback(data)
	{
		peices = data.split('|');
		
		if (peices[0] != 0 || !peices[0]) {
			return;
		}
		
		Fat.fade_element('drug_' + peices[1], 30, 3000, '#00FF00');
		
	}
	