var FIELD_NORMAL = 0;
var FIELD_REQUIRED = 1;
var FIELD_CORRECT = 2;
var FIELD_ERROR = 3;

var ERROR_REQUIRED = 'Field required';
var ERROR_PASSWORDCONFIRM = 'Passwords don\'t match';
var ERROR_EMAILCONFIRM = 'Email doesn\'t match';
var ERROR_INVALID = 'Malformed or invalid';

var TOGGLE_CLICK = true;
var TOGGLE_EDIT = true;

var status_list = Array (	"field_normal", "field_required", "field_correct", "field_error");

//	AJAX related values
var selected_element = null;

var cal_obj2 = null;
var cal_format = '%Y-%m-%d';
var cal_current_focus = null;
var TAB_CUSTOM = false;
var TAB_CYCLE = true;

function field_status(field, index, err_msg)
{
	var form_error = document.getElementById('form_error');
	var parent = field.parentElement || field.parentNode;
	
	form_error.innerHTML = (typeof err_msg == 'string' ? err_msg : '');
	
	field.className = status_list[index];
	
	if (typeof err_msg == 'string')
	{
		insertAfter(form_error, field);
		form_error.style.display = 'inline';
		field.focus();
	}
	else
		form_error.style.display = 'none';
}

//	Verify a users choice
function verify_action()
{
	if (!confirm('Are you sure?'))	
	{
		//	Check whether its IE compatible or not
		if (window.event)
			window.event.returnValue=false;	

		return false;
	}
	else
		return true;
}

function row_click(row, url)
{
	if (TOGGLE_CLICK)
	{
		var page = '/control/ajax_modules/current_item.php?ITEM_ID='+row.getAttribute('id')+'&TYPE='+row.getAttribute('type');
		xmlHttp=GetXmlHttpObject()
		xmlHttp.onreadystatechange=function()	{
			if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
		 		document.location=url;
		}
		ajax_call(page);
	}
}

function edit_cell(cell)
{
	if (TOGGLE_EDIT)	{
		cell.children[0].style.display = 'block';
		cell.children[1].style.display = 'none';
	
		cell.children[0].focus();
	}
}

function save_cell(cell, custom_drop)
{
	//	Get the table
	var source = cell.parentNode.parentNode.parentNode.parentNode.getAttribute('source');
	//	Get the row ID
	var unique_ID = cell.parentNode.parentNode.id;
	//	Get the field name
	var field = cell.getAttribute('name');
	var field_class = cell.getAttribute('class');
	var value = cell.value;

	if (custom_drop==undefined) 
		custom_drop = Array(	'Positive', 'Neutral', 'Negative');

	//	Check whether field has been left blank
	if ((field_class=='field_required' || field_class=='field_error') && value=='')
	{
		alert ('This field is required. Please enter a value.');
		cell.focus();
		//field_status(cell, FIELD_ERROR, ERROR_REQUIRED);
		TOGGLE_EDIT = false;
		return false;
	}
	
	var page = '/control/ajax_modules/update_cell.php?source='+source+'&unique_ID='+unique_ID+'&field='+field+'&value='+value;

	xmlHttp=GetXmlHttpObject()

	xmlHttp.onreadystatechange=function()	{
		
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
		{
			if (xmlHttp.responseText=='')
			{
				if (field_class=='field_required' || field_class=='field_error')
					field_status(cell, FIELD_REQUIRED);
				
				cell.style.display = 'none';	
				if (field=='response_answer')
					cell.parentNode.children[1].innerHTML = custom_drop[value-1];	
				else
					cell.parentNode.children[1].innerHTML = value;	
				cell.parentNode.children[1].style.display = 'block';	
				TOGGLE_EDIT = true;
			}
			else
			{
				alert('Could not save field. Please ensure you have entered a valid entry.');
				cell.focus();
				//field_status(cell, FIELD_ERROR, ERROR_INVALID);
				TOGGLE_EDIT = false;
			}
			
		}
	}
	
	ajax_call(page);
}

function form_events()
{
	//	Browser independant element capture
	var all = document.all || document.getElementsByTagName('*');	
	
	for (count=0;count<all.length;count++)
	{	
		obj_ref = all[count];
		class_ref = all[count].className;
		custom = all[count].getAttribute('custom');
		default_text = (typeof all[count].getAttribute('default') == 'string' ? all[count].getAttribute('default') : '');
		
		//	-------------------------------------------------------------------
		//	Handle row highlighting
		if ((class_ref=='row_alternate' || class_ref=='row_normal') && custom != 'ignore')
			obj_ref.onmouseover=function()	{
				this.className='row_selected';
			}
		
		if (class_ref=='row_alternate')
			obj_ref.onmouseout=function()	{
				this.className='row_alternate';
			}

		if (class_ref=='row_normal')
			obj_ref.onmouseout=function()	{
				this.className='row_normal';
			}
				
		//	Handle form field blur on required fields
		if (class_ref=='field_required')
		{
			obj_ref.onblur=function()	{
				field_status(this, FIELD_REQUIRED);
				default_text = (typeof this.getAttribute('default') == 'string' ? this.getAttribute('default') : '');
				if (default_text!='' && this.value=='')
					this.value=default_text;
			}
		}

		if (default_text!='' && obj_ref.value=='')
		{
			obj_ref.value=default_text;
			
			obj_ref.onfocus=function()	{
				if (this.value==this.getAttribute('default'))
					this.value='';
			}
									
		}

		//	Add the anchor click toggle for embedded rows
		if (obj_ref.tagName=='A' && (typeof obj_ref.getAttribute('href') == 'string'))
		{
			obj_ref.onmouseover=function()	{
				TOGGLE_CLICK=false;
			}
				
			obj_ref.onmouseout=function()	{
				TOGGLE_CLICK=true;
			}
		}
		
		//	CUSTOM FORM ELEMENTS
		if (custom=='cell_edit')
		{
			obj_ref.style.display='none';
			
			obj_ref.onblur=function()	{
				save_cell(this);
				if (typeof this.getAttribute('refresh') == 'string')
					window.location.reload();
			}
		}
		
		if (custom=='datetime')
		{
			obj_ref.id=obj_ref.getAttribute('name');
			obj_ref.readOnly = true;
			//obj_ref.style.width='195px';
			$(obj_ref).datetimepicker({ dateFormat: 'yy-mm-dd' });
			
			var datePicker = document.createElement('img');
			datePicker.setAttribute('src', '/images/date.png');
			datePicker.setAttribute('alt', 'Pick a date');
			datePicker.setAttribute('align', 'absmiddle');
			datePicker.className = 'mouse';
			datePicker.onclick=function(){
				//show_cal(this, this.previousSibling.id);
				this.previousSibling.focus();
			}
			
			insertAfter(datePicker, obj_ref);
		}
	}
}

function select_tab(index)
{
	for (tab_count=1;tab_count<=TABS_MAX;tab_count++)
	{
		if (document.getElementById("tab_"+tab_count))
			document.getElementById("tab_"+tab_count).className = (index==tab_count) ? (TAB_CUSTOM?TAB_STYLES[tab_count-1]+'_active':'active_tab') : (TAB_CUSTOM?TAB_STYLES[tab_count-1]+'_normal':'normal_tab');
		
		document.getElementById(SECTIONS[tab_count-1]).style.display = (index==tab_count) ? 'block' : 'none';
	}	
}



//	Drop down a element
function drop_down(object)
{
	var f = document.getElementById(object);
	
	if (TOGGLE_CLICK)
	{
		if (f.style.display == 'none')
			f.style.display = '';
		else
			f.style.display = 'none';
	}
}


function validateForm(current_form)
{
	for (count=0;count<current_form.length;count++)
	{	
		obj_ref = current_form[count];

		required = (typeof current_form[count].getAttribute('required') == 'string' ? current_form[count].getAttribute('required') : '');
		alert_msg = (typeof current_form[count].getAttribute('alert') == 'string' ? current_form[count].getAttribute('alert') : '');
		default_text = (typeof current_form[count].getAttribute('default') == 'string' ? current_form[count].getAttribute('default') : '');
		match_field = (typeof current_form[count].getAttribute('match') == 'string' ? current_form[count].getAttribute('match') : '');
		file_types = (typeof current_form[count].getAttribute('filetypes') == 'string' ? current_form[count].getAttribute('filetypes') : '');

		//	Handle form field blur on required fields
		if (required=='true' && (obj_ref.value=='' || obj_ref.value == 0 || obj_ref.value==default_text))
		{
			if (alert_msg=='')
				field_status(obj_ref, FIELD_ERROR, ERROR_REQUIRED);
			else
			{
				if (alert_msg=='true')
					alert('This field is required.');
				else
					alert(alert_msg);
					
				obj_ref.focus();
			}
				
			return false;
		}

		if (obj_ref.value==default_text)
			obj_ref.value='';
		
		if (match_field!='')
		{
			var second_field = document.getElementById(match_field);
			if (obj_ref.value!=second_field.value)
			{
				field_status(obj_ref, FIELD_ERROR, ERROR_PASSWORDCONFIRM);			
				return false;
			}
		}
		
		//	Handle file types
		if (file_types!='')
		{
			var type_array = file_types.toUpperCase();
			var file_type = obj_ref.value.substring(obj_ref.value.indexOf('.')+1).toUpperCase();

			if (type_array.indexOf(file_type)==-1 || file_type=='')
			{
				alert('Please ensure you have selected a file of the following type: '+file_types.toUpperCase());
				obj_ref.focus();
				return false;
			}
		}

	}
}

function insertAfter(new_node, existing_node) {
// if the existing node has a following sibling, insert the current
// node before it. otherwise appending it to the parent node
// will correctly place it just after the existing node.

if (existing_node.nextSibling) {
// there is a next sibling. insert before it using the mutual
// parent's insertBefore() method.
existing_node.parentNode.insertBefore(new_node, existing_node.nextSibling);
} else {
// there is no next sibling. append to the end of the parent's
// node list.
existing_node.parentNode.appendChild(new_node);
}

} // insertAfter()

// show calendar
function show_cal(el, field) {

	if (cal_obj2) return;

	cal_current_focus = document.getElementById(field);

	cal_obj2 = new RichCalendar();
	cal_obj2.start_week_day = 2;
	cal_obj2.show_time = false;
	cal_obj2.language = 'en';
	cal_obj2.user_onchange_handler = cal2_on_change;
	cal_obj2.user_onclose_handler = cal2_on_close;
	cal_obj2.user_onautoclose_handler = cal2_on_autoclose;

	cal_obj2.parse_date(cal_current_focus.value, cal_format);

	cal_obj2.show_at_element(cal_current_focus, "adj_left-bottom");
	//cal_obj2.change_skin('alt');
}

// user defined onchange handler
function cal2_on_change(cal, object_code) {
	if (object_code == 'day') {
		cal_current_focus.value = cal.get_formatted_date(cal_format);
		//field_save(cal_current_focus);
		cal.hide();
		cal_obj2 = null;
	}
}

// user defined onclose handler (used in pop-up mode - when auto_close is true)
function cal2_on_close(cal) {
		cal.hide();
		cal_obj2 = null;
}

// user defined onautoclose handler
function cal2_on_autoclose(cal) {
	cal_obj2 = null;
}


