
// Common functionality object.

var common = {

	// Object proeprties / data.
	current_page: '',
	current_panel: null,
	open_panels: ':',
	tree_state: ':',
	table_toggle: false,
	table_state: ':',
	current_row: '',
	class_refs: new Array(),
	help_win: null,

	// Undefined function taken from HCF common library.
	undefined: function (item) { return typeof(item) == 'undefined'; },

	// Flexible parameter function taken from HCF common library.
	flexible_param: function (param, def) {

		// Check the deault.
		if (this.undefined(def) || def == null || typeof(def) != 'object' || def.constructor != Array) def = new Array();

		// Check if any param passed.
		if (this.undefined(param) || param == null) param = def;

		// Check if a string is passed.
		if (typeof(param) == 'string') {
			
			// Any value?
			if (param.replace(/\s*/gi, '') == '') param = def;
			
			// Or split into an array.
			else param = param.split(',');
		}

		// Check now a valid array.
		if (typeof(param) != 'object' || param.constructor != Array) param = def;

		// Finally trim any elements of the array.
		for (var index = 0; index < param.length; index++) param[index] = param[index].replace(/^\s*|\s*$/gi, '');
		
		// Return.
		return param;
	},

	// Creates a unique ID from the page query string (for use in cookie naming).
	page_uid: function () {
	
		// Check for saved version.
		if (this.current_page != '') return this.current_page;
		
		// Get the query string.
		var page = (document.location.search.split('?')[1] || '').replace(/\+/gi, '');

		// Replace the common terms and then & and =.
		page = page.replace(/([a-zA-Z])[a-zA-Z]*([a-zA-Z])/gi, '$1$2').replace(/[\+|&|=]/gi, '');

		// CHeck for home page.
		if (page == '') page = "home";

		// Cache.
		this.current_page = page;

		// Return.
		return page;
	},

	// Add class function taken from HCF DHTML library.
	add_class: function (elem, cn) {

		// Get the classname.
		var current = (elem.className) ? elem.className : '';

		// Create the 2 regexs to remove the classname.
		var regex1 = new RegExp('^'+cn+'$|^'+cn+' | '+cn+'$', 'gi');
		var regex2 = new RegExp(' '+cn+' ', 'gi');

		// First remove any current references.
		var apply = current.replace(regex1, '').replace(regex2, ' ');

		// Then add the reference.
		apply += ((apply.length > 0) ? ' ' : '') + cn;

		// And apply it.
		elem.className = apply;
	},

	// Remove class function taken from HCF DHTML library.
	remove_class: function (elem, cn) {

		// Get the classname.
		var current = (elem.className) ? elem.className : '';

		// No classes!
		if (current == '') return;

		// Create the 2 regexs to remove the classname.
		var regex1 = new RegExp('^'+cn+'$|^'+cn+' | '+cn+'$', 'gi');
		var regex2 = new RegExp(' '+cn+' ', 'gi');

		// Generate the new classname.
		var apply = current.replace(regex1, '').replace(regex2, ' ');

		// And apply it.
		elem.className = apply;
	},

	// Gets a reference to a class in the stylesheets object - caches references.
	get_class_ref: function (classname) {

		// Check for a cahed version.
		if (typeof(this.class_refs[classname]) != 'undefined' && this.class_refs[classname] != null) return this.class_refs[classname];
	
		// Otherwise - loop through sheets.
		for (sheet = 0; sheet < document.styleSheets.length; sheet++) {
			
			// Then ruleset 1.
			if(document.styleSheets[sheet].rules)
				for (rule = 0; rule < document.styleSheets[sheet].rules.length; rule++)
					if (document.styleSheets[sheet].rules[rule].selectorText == '.'+classname) {
						this.class_refs[classname] = document.styleSheets[sheet].rules[rule];
						return this.class_refs[classname];
					}
			
			// Or ruleset 2.
			else if(document.styleSheets[sheet].cssRules)
				for (rule = 0; rule < document.styleSheets[sheet].cssRules.length; rule++) {
						this.class_refs[classname] = document.styleSheets[sheet].cssRules[rule];
						return this.class_refs[classname];
					}
		}

		// Not found.
		this.class_refs[classname] = null;
		return this.class_refs[classname];

	},

	// Gets the state of a slection object.
	get_sel_state: function (select) {
	
		// Results array.
		var result = new Array();
		
		// Loop throigh the select options.
		for (var index = 0; index < select.options.length; index++) {
			result.push(select.options[index].selected);
		}

		// Return.
		return result;
	},

	// Gets the value of a radio button set.
	get_radio_value: function (radio) {
		
		// Loop through.
		for (var index = 0; index < radio.length; index ++)

			// Checked.
			if (radio[index].checked) return radio[index].value;
		
		// Return.
		return '';
	},

	// Function to automaticaly attach rollover styling.	
	set_roll_style: function (param) {
	
		// Check for a param.
		if (this.undefined(param) || param == null) return;

		// Is the obejct a string - if so try and locate the element.
		if (typeof(param) == 'string') var param = document.getElementById(param);

		// Check the param again.
		if (this.undefined(param) || param == null) return;

		// Do the rollover functionality.
		param.onmouseover = function () { common.add_class(this, 'ro'); }
		param.onmouseout = function () { common.remove_class(this, 'ro'); }
	},


	// Function to automaticaly attach focus functionality.	
	set_focus_style: function (param) {
	
		// Check for a param.
		if (this.undefined(param) || param == null) return;

		// Is the obejct a string - if so try and locate the element.
		if (typeof(param) == 'string') var param = document.getElementById(param);

		// Check the param again.
		if (this.undefined(param) || param == null) return;

		// Do the rollover functionality.
	//	param.onfocus = function () { common.add_class(this, 'fo'); }
	//	param.onblur = function () { common.remove_class(this, 'fo'); }
	},

	// Function which identifies any form elements and adds focus styling to them.
	identify_form_elements: function () {
	
		// Get any input elements.
		var elements = document.getElementsByTagName('input');
		// Loop through the elements.
		for (var index = 0; index < elements.length; index++){
			// Check that its text, not button.
			if (elements[index].className.toLowerCase().match(/^(text|password)$|^(text|password) | (text|password)$/gi)){
				// Set the functionality.
				this.set_focus_style(elements[index]);
			}
		}
		
		// Get any textarea elements.
		var elements = document.getElementsByTagName('textarea');

		// Loop through the elements.
		for (var index = 0; index < elements.length; index++){
			// Set the functionality.
			this.set_focus_style(elements[index]);
		}

		// Get any select elements.
		var elements = document.getElementsByTagName('select');

		// Loop through the elements.
		for (var index = 0; index < elements.length; index++){

			// Set the functionality.
			this.set_focus_style(elements[index]);
		}
	
	},

	// Function which identifies any form buttons and adds rollover styling to them.
	identify_form_buttons: function () {
	
		// Assume up to 5 sets of buttons and exit as soon as one fails.
		var b_set = 0; for (buttons = document.getElementById('buttons'+(++b_set)); buttons != null; buttons = document.getElementById('buttons'+(++b_set))) {
		
			// Get any actual buttons.
			var buttons = buttons.getElementsByTagName('input');

			// Loop through the buttons.
			for (var index = 0; index < buttons.length; index++) {

				// Set the rollover functionality.
				this.set_roll_style(buttons[index]);

				// Set the focus functionality.
				this.set_focus_style(buttons[index]);
			}
		}
	},

	// Groups all the form set-up functionality.
	identify_form: function () {
		
		// Elements.
		this.identify_form_elements();

		// Buttons.
		this.identify_form_buttons();

		// JJS - Pain in firefox.
		// Set the focus to the first element of the first form.
		try { document.forms[0].elements[0].focus(); } catch (error) {};
	},

	// Toggles a CSS based panel open or closed.
	toggle_panel: function (link, allow_multi) {
		
		// Check the params.
		allow_multi = allow_multi !== false ? true : false;

		// Closed panel?
		if (link.parentNode.className == "panelclosed") {

			// Open the panel.
			link.parentNode.className = "panelopen";

			// Are we allowing multi panels?
			if (!allow_multi) {

				// Close any currently open.
				if (this.current_panel != null) this.current_panel.className = "panelclosed";

				// Set the current panel.
				this.current_panel = link.parentNode;

				// And save to cookie.
				cookie.kd_set('PANELS', this.page_uid()+'_tgl', this.current_panel.id);
			
			// Multi-panels.
			} else {
				
				// Add to the open panels array.
				this.open_panels = this.open_panels.replace(new RegExp(':'+link.parentNode.id+':', 'gi'), ':') + link.parentNode.id + ':';

				// And save to cookie.
				cookie.kd_set('PANELS', this.page_uid(), this.open_panels);
			}

		// Open panel - so close.
		} else {

			// Close the panel.
			link.parentNode.className = "panelclosed";

			// Are we allowing multi panels?
			if (!allow_multi) {
			
				// Set the current panel.
				this.current_panel = null;

				// And remove cookie.
				cookie.kd_del('PANELS', this.page_uid()+'_tgl');

			// Multi-panels.
			} else {

				// Remove from the open panels array.
				this.open_panels = this.open_panels.replace(new RegExp(':'+link.parentNode.id+':', 'gi'), ':');

				// And save to cookie.
				cookie.kd_set('PANELS', this.page_uid(), this.open_panels);
			}
		}
	},

	// Processes any open/closed panels on the page (w.r.t. cookied data).
	process_panels: function () {
	
		// Get any toggle cookie data.
		var panel_data = cookie.kd_get('PANELS', this.page_uid()+'_tgl', '__NONE__');

		// Check it.
		if (panel_data != '__NONE__') {

			// Get the panel if it exists.
			var panel = document.getElementById(panel_data);

			// Check it.
			if (panel != null) {
				
				// Open the panel.
				panel.className = 'panelopen';

				// Set the object property.
				this.current_panel = panel;
			}
		}

		// Get any other panels data.
		var panel_data = cookie.kd_get('PANELS', this.page_uid(), '__NONE__');

		// Check it.
		if (panel_data != '__NONE__') {

			// Set the object property.
			this.open_panels = panel_data;

			// Create an array.
			var panels = panel_data.split(':');

			// Loop.
			for (var index = 0; index < panels.length; index++) {
			
				// Check for blank.
				if (panels[index] != '') {

					// Get the panel if it exists.
					var panel = document.getElementById(panels[index]);

					// Check it.
					if (panel != null) {
						
						// Open the panel.
						panel.className = 'panelopen';
					}
				}
			}
		}
	},

	// Simple tree show hide functionality.
	branch_click: function (link, page_processing) {
	
		// Check the params.
		page_processing = page_processing !== true ? false : true;

		// Check whether we are opening or closing.
		var action = (link.className.toLowerCase().match(/open/gi) ? '' : 'open');

		// Call any assigned function.
		if (!page_processing) this.branch_click_action(link, action);

		// Set the link class.
		if (action == 'open') this.add_class(link, 'open'); else this.remove_class(link, 'open');
				
		// Get the name of the link parent.
		var parent_id = link.parentNode.id;

		// Get the lists if they exist.
		var list1 = document.getElementById(parent_id.replace(/^a_/gi, "al_"));
		var list2 = document.getElementById(parent_id.replace(/^a_/gi, "cl_"));

		// Show hide it.
		if (list1 != null) list1.style.display = (action == 'open' ? 'block' : 'none');
		if (list2 != null) list2.style.display = (action == 'open' ? 'block' : 'none');

		// Update the tree state.
		if (action == 'open') {
		
			// Add the link name.
			this.tree_state = this.tree_state.replace(new RegExp(':'+link.id+':', 'gi'), ':') + link.id + ':';
		
		} else {

			// Remove the link.
			this.tree_state = this.tree_state.replace(new RegExp(':'+link.id+':', 'gi'), ':');
		}

		// Save the state to cookie.
		cookie.kd_set('TREES', this.page_uid(), this.tree_state);
	},

	// Simple tree show hide functionality.
	leaf_click: function (link, page_processing) {

		// Check the params.
		page_processing = page_processing !== true ? false : true;

		// Call any assigned function.
		if (!page_processing) this.leaf_click_action(link, null);
	},

	// Processes any open/closed trees on the page (w.r.t. cookied data).
	process_trees: function () {

		// Get tree data.
		var tree_data = cookie.kd_get('TREES', this.page_uid(), '__NONE__');

		// Check it.
		if (tree_data != '__NONE__') {

			// Set the object property.
			this.tree_state = tree_data;

			// Create an array.
			var branches = tree_data.split(':');

			// Loop.
			for (var index = 0; index < branches.length; index++) {
			
				// Check for blank.
				if (branches[index] != '') {

					// Get the panel if it exists.
					var branch = document.getElementById(branches[index]);

					// Check it.
					if (branch != null) {
						
						// Open the panel.
						this.branch_click(branch, true);
					}
				}
			}
		}

		// Double check any a_00s are open.
		var branch = document.getElementById('alk_00');
		if (branch != null && !branch.className.toLowerCase().match(/open/gi)) this.branch_click(branch, true);
	},

	// Tree click action stubs.
	branch_click_action: function (link, action) {},
	leaf_click_action: function (link, action) {},

	// Table plus / minus click.
	table_pm: function (id, page_processing) {
	
		// Check the params.
		page_processing = page_processing !== true ? false : true;

		// Get the elements.
		var pm_element = document.getElementById('pm_'+id);
		var ex_element = document.getElementById('ex_'+id);

		// Check them.
		if (pm_element == null || ex_element == null) return;

		// The operations.
		var action = (ex_element.className.toLowerCase().match(/open/gi) ? '' : 'open');

		// Switch.
		if (action == 'open') {

			// Change the two classes.
			this.remove_class(pm_element, 'plus');
			this.remove_class(ex_element, 'closed');
			this.add_class(pm_element, 'minus');
			this.add_class(ex_element, 'open');

			// Add the link name.
			if (!page_processing) this.table_state = this.table_state.replace(new RegExp(':'+id+':', 'gi'), ':') + id + ':';

			// Save the state to cookie.
			if (!page_processing) cookie.kd_set('TABLES', this.page_uid(), this.table_state);

			// Table toggle.
			if (this.table_toggle) {
			
				// Close the already open.
				if (this.current_row != '') this.table_pm(this.current_row);

				// Update flag.
				this.current_row = id;
			}

		} else {

			// Change the two classes.
			this.remove_class(pm_element, 'minus');
			this.remove_class(ex_element, 'open');
			this.add_class(pm_element, 'plus');
			this.add_class(ex_element, 'closed');

			// Remove the link.
			if (!page_processing) this.table_state = this.table_state.replace(new RegExp(':'+id+':', 'gi'), ':');

			// Save the state to cookie.
			if (!page_processing) cookie.kd_set('TABLES', this.page_uid(), this.table_state);

			// Table toggle.
			if (this.table_toggle) this.current_row = '';
		}
	},

	// Processes any open/closed trees on the page (w.r.t. cookied data).
	process_tables: function () {

		// Get tree data.
		var table_data = cookie.kd_get('TABLES', this.page_uid(), '__NONE__');

		// Check it.
		if (table_data != '__NONE__') {

			// Set the object property.
			this.table_state = table_data;

			// Create an array.
			var rows = table_data.split(':');

			// Loop.
			for (var index = 0; index < rows.length; index++) {
			
				// Check for blank.
				if (rows[index] != '') {

					// Open the row.
					this.table_pm(rows[index], true);
				}
			}
		}
	},

	// Paned windows delete relocate function.
	paned_delete: function () {
	
		// Delete any cookie.
		var last_page = cookie.kd_get('PANE', 'last_page', '__NONE__');
		if (last_page != '__NONE__') cookie.kd_del('PANE', last_page);
	},

	// Search form submit function.
	searchform: function () {
		// Reload the location changing the search term.
		window.location = window.location.toString().replace(/&search=[^&$]*/gi, '')+'&search='+document.getElementById('search').value;
	},

	// Opens a pop-up window.
	popup: function (filename, title, w, h, x, y, scrollbars, statusbar, resize, toolbar) {

		// Check the w and h parameters.
		if (!w || isNaN(parseInt(w))) w = 200;
		if (!h || isNaN(parseInt(h))) h = 300;
		
		// Check x and y parameters, allow and default to be (c)entered.	
		if (!x || isNaN(parseInt(x)) || x == 'c') x = Math.round((screen.width/2) - (parseInt(w)/2));
		if (!y || isNaN(parseInt(y)) || y == 'c') y = Math.round((screen.height/2) - (parseInt(h)/2));

		// Set the popup window options and defaults.
		if (scrollbars == null) var scrollbars = 1;
		if (statusbar == null) var statusbar = 0;
		if (resize == null) var resize = 0;
		if (toolbar == null) var toolbar = 0;

		// Open the popup.
		new_window = window.open(filename, title, 'status=' + statusbar + ',scrollbars=' + scrollbars + ',resizable=' + resize + ',toolbar=' + toolbar + ',menubar=' + toolbar + ',width=' + w + ',height=' + h + ',left=' + x + ',top=' + y);

		// Set the opener - browser dependent.
		if(!new_window.opener && navigator.appVersion.indexOf('MSIE 5') == -1) new_window.opener = self;

		// Return.
		return new_window;
	},
		
	// Opens the form help popup.
	form_help: function (ref) {
	
		// The base url.
		var url = 'form_help.php'

		// The anchor.
		if (ref != null && ref != '') url += '?id='+ref;

		// Open the window if necessary.
		this.help_win = this.popup(url, 'form_help', 300, 400, 'c', 'c', 1, 0, 1,0);
	},

	// Set field value
	set_field: function(id, value){
		if(o = document.getElementById(id)){
			o.value = value;
		}
	}

}

