// Set variables
rowClassName = new Array();
checkedRows = new Array();
grid_columns = new Array();

var SuggestList = null;
var SuggestItem = null;
var SuggestFunction = '';
var form_error_count = 0;

function submitForm() { 
	if (form_error_count > 0) { 
		alert("There are still errors within the form.  Please correct all shown errors before continuing.");
		return false;
	} else { 
		return true;
	}
}

/////////////////////////////////////////////////
// Add data grid row
/////////////////////////////////////////////////

function addGridRow(grid_alias) { 

	// Parse XML response
	var response = document.getElementById('xmlDataIsland').innerHTML;
	try {
		var xml = (new DOMParser()).parseFromString(response, "text/xml");
	} catch (e) {
		try {
			var xml = new ActiveXObject("Microsoft.XMLDOM");
			xml.loadXML(response);
		} catch (e) {
			alert("Unable to parse XML response from server.");
		}
	}

	var id = xml.createElement("ID");
	id.appendChild(xml.createTextNode("55"));
	var user = xml.createElement("username");
	user.appendChild(xml.createTextNode("jshaw"));
	var name = xml.createElement("full_name");
	name.appendChild(xml.createTextNode("James Shaw"));
	var email = xml.createElement("email");
	email.appendChild(xml.createTextNode("james@aol.com"));

	var newnode = xml.createElement("record");
	newnode.appendChild(id);
	newnode.appendChild(user);
	newnode.appendChild(name);
	newnode.appendChild(email);

	xml.getElementsByTagName("admin")[0].appendChild(newnode);

	// Add row
	var length = obj.getRowCount();
	obj.addRow(1);
	
	//obj.setCellText(0, 1, "55");
	//obj.setCellValue(1, 0, "james");
	//obj.setCellValue(2, 0, "James Pot");
	//obj.setCellValue(3, 0, "james@aol.com");
	
}

/////////////////////////////////////////////////
// Update grid row
/////////////////////////////////////////////////

function updateGridRow(grid_alias, text, col, row) { 

	// Set variables
	var record_id = obj.getCellText(0, row);
	var col_name = grid_columns[col];
	var data = 'grid_alias=' + grid_alias + '&record_id=' + record_id + '&field_alias=' + col_name + '&value=' + text;
	
	// Send AJAX
	ajax_send('datagrid_update_cell', data, 1);

}

/////////////////////////////////////////////////
// Initialize page
/////////////////////////////////////////////////

function initializePage() { 

	// Initialize components
	init_SmartTables();
	init_TabControls();
	init_AutoSuggest();

}

/////////////////////////////////////////////////
// Initialize tables
/////////////////////////////////////////////////

function init_SmartTables() { 

	// Go though tags
	for (t=0; t < smart_tables.length; t++) { 
		var tag_name = smart_tables[t] + '_DataTable';

		// Get tables
		tables = getElementsByClassName(tag_name, 'table', document);
		for (x=0; x < tables.length; x++) {
			
			// Get table and rows
			var table = tables[x];			
			rows = table.getElementsByTagName('tr');
			
			// Set table ID
			if (!table.id) { table.id = 'table' + x; }

			// Go through rows
			var class_num = 2;
			for (y=0; y < rows.length; y++) { 
				var row = rows[y];
				if (row.className == 'headerrow') { continue; }
				if (row.id == 'search_row') { continue; }
				if (row.id == 'tbl_navRow') { continue; }

				// Get class nun
				class_num = class_num == 2 ? 1 : 2;
				row.className = 'row' + class_num;
	
				// Set row ID and variables
				row_id = 'row' + table.id + '_' + y;
				rows[y].id = row_id;
				rowClassName[row_id] = 'row' + class_num;

				// Set javascript functions
				row.onmouseover = dataTable_rowOver;
				row.onmouseout = dataTable_rowOut;
				
				// Go throuh cells, and add onclicks
				for (c = 0; c < row.cells.length; c++) { 
					if (!row.cells[c]) { continue; }					
					if (row.cells[c].align != 'left') { row.cells[c].style.paddingLeft = 0; }

					if (row.cells[c].onclick != "function onclick(event) {\n}") { continue; }
					row.cells[c].onclick = dataTable_rowClick;
				}
			}
		}
	}
}

function dataTable_rowOver(e) {

	// Get row
	if (!e) var e = window.event;
	var row = e.target ? e.target : e.srcElement;
	row = row.parentNode;

	// Set class name
	if (row.className == 'row1' || row.className == 'row2') { 
		rowClassName[row.id] = row.className;
		row.className = 'activerow';
	}
}

function dataTable_rowOut(e) {

	// Get row
	if (!e) var e = window.event;
	var row = e.target ? e.target : e.srcElement;
	row = row.parentNode;

	// Check for checkbox
	elements = row.getElementsByTagName('input');
	for (x=0; x < elements.length; x++) {
		var element = elements[x];
		if (elements[x].type == 'checkbox' && elements[x].checked === true) {
			return;
		}
	}

	// Set class name
	row.className = rowClassName[row.id];

}

function dataTable_rowClick(e) {

	// Get row
	if (!e) var e = window.event;
	var row = e.target ? e.target : e.srcElement;
	row = row.parentNode;
	
	// Check for checkbox
	elements = row.getElementsByTagName('input');
	for (x=0; x < elements.length; x++) {

		if (elements[x].type == 'checkbox') {

			if (checkedRows[row.id] == 1) {
				row.className = rowClassName[row.id];
				elements[x].checked = false;
				checkedRows[row.id] = 0;

			} else {
				row.className = 'activerow';
				elements[x].checked = true;
				checkedRows[row.id] = 1;
			}
		}
	}
}

/////////////////////////////////////////////////
// Check all table rows
/////////////////////////////////////////////////

function checkAllTableRows(table_alias) {

	// Go through rows
	var table = document.getElementById('tbl_' + table_alias);
	for (x = 0; x < table.rows.length; x++) {
		if (!table.rows[x]) { continue; }
		var row = table.rows[x];

		// Skip, if needed
		if (row.className == 'headerrow') { continue; }
		if (row.id == 'search_row') { continue; }
		if (row.id == 'tbl_navRow') { continue; }

		// Check for checkbox
		elements = row.getElementsByTagName('input');
		for (y=0; y < elements.length; y++) {
			if (elements[y].type == 'checkbox') {
				row.className = 'activerow';
				elements[y].checked = true;
				checkedRows[row.id] = 1;
			}
		}
	}
}

/////////////////////////////////////////////////
// Uncheck all table rows
/////////////////////////////////////////////////

function uncheckAllTableRows(table_alias) {

	// Go through rows
	var table = document.getElementById('tbl_' + table_alias);
	for (x = 0; x < table.rows.length; x++) {
		if (!table.rows[x]) { continue; }
		var row = table.rows[x];

		// Skip, if needed
		if (row.className == 'headerrow') { continue; }
		if (row.id == 'search_row') { continue; }
		if (row.id == 'tbl_navRow') { continue; }

		// Check for checkbox
		elements = row.getElementsByTagName('input');
		for (y=0; y < elements.length; y++) {
			if (elements[y].type == 'checkbox') {
				row.className = rowClassName[row.id];
				elements[y].checked = false;
				checkedRows[row.id] = 0;
			}
		}
	}
}

/////////////////////////////////////////////////
// Initialize tab controls
/////////////////////////////////////////////////

function init_TabControls() {

	// Go through tags
	var tabcontrol_id = 0;
	for (t=0; t < tab_controls.length; t++) { 
		var tag_name = tab_controls[t] + '_TabControl';

		// Get tabs
		tabControls = getElementsByClassName(tag_name, 'div', document);
		for (x=0; x < tabControls.length; x++) { 
			tabcontrol_id++;

			// Set variables
			var tabControl = tabControls[x];
			tabControl.setAttribute('css_style', tag_name);
			tabs = getElementsByClassName(tag_name + '_tab', 'span', tabControl);
			pages = getElementsByClassName(tag_name + '_page', 'div', tabControl);
		
			// Assign ID to tab control
			tabControl.id = 'tabControl' + tabcontrol_id;
		
			// Go though all tabs
			var first_page = 1;
			for (y=0; y < tabs.length; y++) { 
			
				// Check parent node
				var temp = tabs[y].parentNode.parentNode.id;
				if (temp != tabControl.id) { continue; }
		
				// Set javascript functions
				tabs[y].onmouseover = tabPage_mouseOver;
				tabs[y].onmouseout = tabPage_mouseOut;
				tabs[y].onclick = tabPage_mouseClick;
		
				// Set ID
				var tab_id = 'tab' + tabcontrol_id + '_' + tabs[y].id;

				// Go through pages
				for (z=0; z < pages.length; z++) { 
					if (pages[z].id != tabs[y].id) { continue; }
					pages[z].id = 'tabPage' + tabcontrol_id + '_' + tabs[y].id;

					if (first_page == 1) { 
						pages[z].style.display = 'block';
						tabs[y].className = tag_name + '_activetab';
						first_page = 0;
					}
				
				}
				tabs[y].id = tab_id;
			}
		}
	}
}

/////////////////////////////////////////////////
// Tab mouse controls
/////////////////////////////////////////////////

function tabPage_mouseOver(e) { 

	// Get tab
	if (!e) var e = window.event;
	var tab = e.target ? e.target : e.srcElement;
	var tab_control = tab.parentNode.parentNode;
	var css_style = tab_control.getAttribute('css_style');
	
	// Set class name
	tab.className = css_style + '_activetab';	
}

function tabPage_mouseOut(e) { 

	// Get tab
	if (!e) var e = window.event;
	var tab = e.target ? e.target : e.srcElement;
	var tab_control = tab.parentNode.parentNode;
	var css_style = tab_control.getAttribute('css_style');
	
	// Check if tab is selected
	var page_id = tab.id.replace("tab", "tabPage");
	var page = document.getElementById(page_id);
	if (page.style.display == 'block') { return; }
	
	// Set class name
	tab.className = css_style + '_tab';	
}

function tabPage_mouseClick(e) { 

	// Get tab
	if (!e) var e = window.event;
	var tab = e.target ? e.target : e.srcElement;
	var page_id = tab.id.replace("tab", "tabPage");
	var tab_control = tab.parentNode.parentNode;
	var css_style = tab_control.getAttribute('css_style');

	// Get pages
	var pages = getElementsByClassName(css_style + '_page', 'div', tab_control);
	for (x=0; x < pages.length; x++) { 	
		var temp_page = document.getElementById(pages[x].id);
		
		if (pages[x].id == page_id) { 
			temp_page.style.display = 'block';
		} else if (pages[x].style.display == 'block' && pages[x].id != page_id) { 
			temp_page.style.display = 'none';
			
			var tab_id = pages[x].id.replace('tabPage', 'tab');
			var temp_tab = document.getElementById(tab_id);
			temp_tab.className = css_style + '_tab';			
		}
	}	
}

////////////////////////////////////////////
// Initialize autosuggest boxes
////////////////////////////////////////////

function init_AutoSuggest() {

	for (t=0; t < auto_suggests.length; t++) {
		var tag_name = auto_suggests[t] + '_AutoSuggest';

		// Go through boxes
		boxes = getElementsByClassName(tag_name, 'input', document);
		for (x=0; x < boxes.length; x++) {

			// Get box
			var box = document.forms[0].autosuggest;
			SuggestFunction = box.getAttribute('alias');

			// Set events
			box.onkeydown = AutoSuggest_KeyDown;
			box.onkeyup = AutoSuggest_KeyUp;

			// Get position
			var pos = getPosition(box);
			var height = parseInt(box.offsetHeight);
			var width = parseInt(box.offsetWidth);

			// Create new layer
			var layer = document.createElement("div");
			layer.style.position = 'absolute';
			layer.className = tag_name;
			layer.style.top = (pos.y + height);
			layer.style.left = pos.x;
			layer.style.width = width + 'px';

			// Add layer
			document.body.appendChild(layer);

			var list = document.createElement("ul");
			list.style.display = 'none';
			layer.appendChild(list);
			SuggestList = list;
		}
	}
}

function AutoSuggest_MouseOver(e) {

	// Get item
	if (!e) var e = window.event;
	SuggestItem = e.target ? e.target : e.srcElement;

	// Highlight
	AutoSuggest_Highlight();
}

function AutoSuggest_MouseOut(e) {

	// Get item
	if (!e) var e = window.event;
	SuggestItem = e.target ? e.target : e.srcElement;

	// Highlight
	AutoSuggest_Highlight();
}

function AutoSuggest_MouseDown(e) {

	// Get item
	if (!e) var e = window.event;
	SuggestItem = e.target ? e.target : e.srcElement;

	// Highlight
	AutoSuggest_Highlight();

	// Update form fields
	document.forms[0].autosuggest.value = SuggestItem.innerHTML;
	document.forms[0].autosuggest_id.value = SuggestItem.id;

	// Clear items
	AutoSuggest_Clear();
}

function AutoSuggest_KeyUp(e) {

	if (e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13) {
		AutoSuggest_GetSuggestions(SuggestFunction, document.forms[0].autosuggest.value);
	}

}

function AutoSuggest_KeyDown(e) {

	// Make sure nodes exist
	if (!SuggestList.childNodes[0]) {
		SuggestItem = null;
		return;
	}

	// Key up
	if (e.keyCode == 38) {

		if (SuggestItem == SuggestList.childNodes[0]) {
			SuggestItem = null;
			SuggestNum = 0;
		} else {

			var prevNode;
			for (x=0; x < SuggestList.childNodes.length; x++) {
				if (SuggestItem == SuggestList.childNodes[x]) {
					SuggestItem = prevNode;
					break;
				} else { prevNode = SuggestList.childNodes[x]; }
			}
		}

	// Key down
	} else if (e.keyCode == 40) {

		if (SuggestItem == null) {
			SuggestItem = SuggestList.childNodes[0];
			SuggestNum = 0;
		} else {

			for (x=0; x < SuggestList.childNodes.length; x++) {
				if (SuggestItem == SuggestList.childNodes[x]) {
					x++;
					SuggestItem = SuggestList.childNodes[x];
					break;
				}
			}
		}

	// Enter key
	} else if (e.keyCode == 13) {
		AutoSuggest_Clear();
		document.forms[0].search.value = SuggestItem.innerHTML;
		return false;

	// Tab key
	} else if (e.keyCode == 9) {
		AutoSuggest_Clear();
		document.forms[0].search.value = SuggestItem.innerHTML;
		return false;
	}

	// Update form fields
	if (SuggestItem != null) {
		document.forms[0].autosuggest.value = SuggestItem.innerHTML;
		document.forms[0].autosuggest_id.value = SuggestItem.id;
	}

	// Highlight item
	AutoSuggest_Highlight();

}

function AutoSuggest_Highlight() {

	for (x=0; x < SuggestList.childNodes.length; x++) {
		var item = SuggestList.childNodes[x];

		if (item == SuggestItem) {
			item.className = 'itemover';
		} else {
			item.className = 'item';
		}
	}
}

function AutoSuggest_GetSuggestions(alias, text) {

	// Send AJAX
	var data = 'combo_alias=' + alias + '&text=' + text;
	ajax_send('autosuggest_search', data, 1);

}

function AutoSuggest_Clear() {
	SuggestList.style.display = 'none';
	for (var x = SuggestList.childNodes.length; x >= 0; x--) {
		if (!SuggestList.childNodes[x]) { continue; }
		SuggestList.removeChild(SuggestList.childNodes[x]);
	}
}

/////////////////////////////////////////////////
// Validate text box
/////////////////////////////////////////////////

function validateTextBox(box, format, required, min_length, max_length, regular_expression, validation_id, form_name) { 

	// Set variables
	var ok;
	var value = box.value;

	// Check value
	if (format == 'ajax') { 
		var data = 'field_name=' + box.name + '&form_name=' + form_name + '&validation_id=' + validation_id + '&field_value=' + value;
		ajax_send('validate_form_field', data, 1);
		return;
	} else { 
		ok = checkTextValue(value, box.name, format, required, min_length, max_length, regular_expression);
	}

	// Check result
	var html = document.getElementById(validation_id);
	if (ok == "OK") { 
		if (box.style.background != '') { form_error_count--; }
		box.style.background = '';
		html.innerHTML = '';
	} else { 
		if (box.style.background != '#CB9393') { form_error_count++; }
		box.style.background = '#CB9393';
		html.innerHTML = '<font color="#984747">' + ok + '</font>';
	}
	
}

/////////////////////////////////////////////////
// Check text value
/////////////////////////////////////////////////

function checkTextValue(value, field_name, format, required, min_length, max_length, regular_expression) {

	// Check form field
	if (required == 1 && value == '') {
		return "Field required";
	} else if (min_length > 0 && value.length < min_length) {
		return "Must be at least " + min_length + " characters";
	} else if (max_length > 0 && value.length > max_length) {
		return "Can not be more than " + max_length + " characters";
	} else if (format == 'integer') {
		var regex = /\D/;
		if (regex.test(value)) { return "Integers only" }
	} else if (format == 'decimal') {
		var regex = /\D&!\./;
		if (regex.test(value)) { return "Amounts only"; }
	} else if (format == 'alpha-numeric') {
		var regex = /[\W\s]/;
		if (regex.test(value)) { return "No special characters allowed"; }
	} else if (format == 'email') {
		apos = value.indexOf("@");
		dotpos = value.lastIndexOf(".");
		if (apos < 1 || dotpos - apos < 2) { return "Invalid e-mail address"; }
	} else if (format == 'regex') {
		var regex = /regular_expression/;
		if (!regex.test(value)) { return "Invalid value"; }
	}

	// Return
	return "OK";

}

/////////////////////////////////////////////////
// Open panel
/////////////////////////////////////////////////

function openPanel(panel_data) { 
	ajax_send('open_panel', panel_data);
}

/////////////////////////////////////////////////
// Close panel
/////////////////////////////////////////////////

function closePanel() { 
	
	var panel = document.getElementById('hidden_panel');
	panel.style.display = 'none';
	panel.innerHTML = '';
	
	var wrapper = document.getElementById('wrapper');
	wrapper.className = '';

}

/////////////////////////////////////////////////
// Redirect user to URL
/////////////////////////////////////////////////

function redirect(location) { 

	if (location.match(/^http/)) { 
		window.document.location = location;
	} else {
		window.document.location = SITE_URL + location;
	}
}

/////////////////////////////////////////////////
// Get query string
/////////////////////////////////////////////////

function getQueryString() {
	var args = new Array();
	var location = window.location.href;
	var q = location.indexOf("?");
	location = location.substring(q+1);
		
	var pairs = location.split("&");
	for (var x = 0; x < pairs.length; x++) {
		var keyval = pairs[x].split("=");
		args[keyval[0]] = unescape(keyval[1]);
	}

	return args;
}


/////////////////////////////////////////////////
// Get elements by class name
/////////////////////////////////////////////////

function getElementsByClassName(strClassName, strTagName, oElm) {
	var arrElements = (strTagName == "*" && document.all) ? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;

	for(var i=0; i < arrElements.length; i++){
		oElement = arrElements[i];      
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}   
	}

	return (arrReturnElements)
}

/////////////////////////////////////////////////
// Get position of element
/////////////////////////////////////////////////

function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}

/////////////////////////////////////////////////
// Center an element
/////////////////////////////////////////////////

function showDeadCenter(Xwidth, Yheight, divid) {

	// Initialize
	var scrolledX, scrolledY;
	var centerX, centerY;

	// Check for scrolling
	if (self.pageYoffset) {
		scrolledX = self.pageXoffset;
		scrolledY = self.pageYoffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		scrolledX = document.documentElement.scrollLeft;
		scrolledY = document.documentElement.scrollTop;
	} else if (document.body) {
		scrolledX = document.body.scrollLeft;
		scrolledY = document.body.scrollTop;
	}

	// Get center of browser window
	if (self.innerHeight) {
		centerX = self.innerWidth;
		centerY = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		centerX = document.documentElement.clientWidth;
		centerY = document.documentElement.clientHeight;
	} else if (document.body) {
		centerX = document.body.clientWidth;
		centerY = document.body.clientHeight;
	}

	// Get offsets
	var leftoffset = scrolledX + (centerX - Xwidth) / 2;
	var topoffset = scrolledY + (centerY - Yheight) / 2;

	// Display duv
	var o = document.getElementById(divid);
	var r = o.style;
	r.position='absolute';
	r.top = topoffset + 'px';
	r.left = leftoffset + 'px';
	r.display = "block";
}
