/**
* Knots Content Management System (Hyper CMS)
* Copyright 2008
*	Author: Jason T. Stiles
*	Website: http://jason.sycodesigns.com/
*
*	Purpose:
*		Hyper JavaScript Framework and Library
*/

/******************************************************************************\
* Pre-Defined Object Extensions
*/

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
};

/**
* Method: isAlphaNumeric
*	Purpose: Checks a String to see if it is Alpha Numeric
*	@return true if it is, false otherwise
*/
String.prototype.isAlphaNumeric = function() {
	return /^[a-z\d]+$/.test (this);
};

/**
* Method: isNumeric
*	Purpose: Checks a String to see if it is Numeric
*	@return true if it is, false otherwise
*/
String.prototype.isNumeric = function() {
	return /^[0-9\d]+$/.test (this);
};

/**
* Method: trim
*	Purpose: Trims whitespace from the Beginning and End of a String
*	@return the trimmed String
*/
String.prototype.trim = function() {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

/******************************************************************************\
* Object Functions
*/

var editor = window.editor = function(id) {
	return Editor.init(id);
};

var list = window.list = function(id) {
	return knotsList.init(id);
};

var knots = window.knots = window.o = function(id) {
	return knots.init(id);
};

var popup = window.popup = function(id) {
	return MessageBox.init(id)
};

/******************************************************************************\ 
* Knots Object
*/

var knots = knots.prototype = {
	obj: null,
	
	//Initializes the Object
	init: function(id) {
		this.obj = document.getElementById(id);
		return this;
	},
	
	//Adds an option to a Drop-down or Multi-Selection field
	addOption: function(text,value) {
		var length = this.obj.options.length;
		this.obj.options[length] = new Option(text,value);
		this.obj.options[length].selected = true;
		return this;
	},
	
	//Adds a series of options to a Drop-down or Multi-Selection field
	addOptions: function(options,selected) {
		var options = options.split(';');
		for(i = 0; i < options.length; i++) {
			var length = this.obj.options.length;
			var option = options[i].split(',');
			if(option[1]) {
				this.obj.options[length] = new Option(option[1],option[0]);
			} else {
				this.obj.options[length] = new Option(option[0],option[0]);
			}
			
			this.obj.options[length].selected = selected;
		}
		
		return this;
	},
	
	//Causes this object to lose focus
	blur: function() {
		this.obj.blur();
		return this;
	},
	
	//Checks the object with the specified boolean value, 
	// or toggles if the value is null or omitted
	check: function(value) {
		if(value) {
			this.obj.checked = value;
		} else {
			this.obj.checked = !this.obj.checked;
		}
		
		return this;
	},
	
	//Returns true if object is checked, false otherwise
	checked: function() {
		return this.obj.checked;
	},
	
	//Causes this object to gain focus
	focus: function() {
		this.obj.focus();
		return this;
	},
	
	//Hides the Object from being displayed
	hide: function() {
		this.obj.style.display = 'none';
		return this;
	},
	
	//Gets the innerHTML of this Object
	html: function() {
		return this.obj.innerHTML;
	},
	
	//Inserts an Object after another
	insertAfter: function(parent, referenceNode) {
		parent.insertBefore(this.obj, referenceNode.nextSibling);
		return this;
	},
	
	//Returns all selected items in a Multi-Selection list
	items: function(delimiter) {
		var length = this.obj.options.length;
		var items = new Array();
		for(i = 0; i < length; i++) {
			if(this.obj.options[i].selected) {
				items.push(this.obj.options[i].value);
			}
		}
		
		delimiter = delimiter ? delimiter : ';';
		
		return items.join(delimiter);
	},
	
	//Moves all options (selected or not)
	moveAllOptions: function(to) {
		to = document.getElementById(to);
		to.options.length = 0;
		for(i = 0; i < this.obj.options.length; i++) {
			var value = this.obj.options[i].value;
			var text = this.obj.options[i].text;
			to.options[i] = new Option(text,value);
			to.options[i].selected = true;
		}
		
		return this;
	},
	
	//Moves selected options down one position in this Drop-Down or Multi-Selection list
	moveOptionsDown: function() {
		for(i = this.obj.options.length-2; i >= 0; i--) {
			var option = this.obj.options[i];
			if(option.selected) {
				var nextOption = this.obj.options[i+1];
				option = this.obj.removeChild(option);
				nextOption = this.obj.replaceChild(option,nextOption);
				this.obj.insertBefore(nextOption,option);
			}
		}
		
		 return this;
	},
	
	//Moves options from this Drop-Down or Multi-Selection list to the object specified
	moveOptionsTo: function(to,context) {
		var to = document.getElementById(to);
		for(i = 0; i < this.obj.options.length; i++) {
			if(this.obj.options[i].selected) {
				var value = this.obj.options[i].value;
				var text = this.obj.options[i].text;
				var length = to.options.length;
				to.options[length] = new Option(text,value);
				to.options[length].selected = true;
				//this.obj.options[i] = null;
				//i--;
			}
		}
		
		return this;
	},
	
	//Moves selected options up one position in this Drop-Down or Multi-Selection list
	moveOptionsUp: function() {
		for(i = 1; i < this.obj.options.length; i++) {
			var option = this.obj.options[i];
			if(option.selected) {
				this.obj.removeChild(option);
				this.obj.insertBefore(option,this.obj.options[i-1]);
			}
		}
		
		 return this;
	},
	
	//Removes all selected options from this Drop-down or Multi-Selection list
	removeOptions: function() {
		for(i = this.obj.options.length-1; i >= 0; i--) {
			if(this.obj.options[i].selected) {
				this.obj.remove(i);
			}
		}
		
		return this;
	},
	
	//Removes 1 or more options from this Drop-down or Multi-Selection list
	removeAllOptions: function() {
		this.obj.options.length = 0;
		return this;
	},
	
	//Selects all items in this Multi-Selection list
	selectAll: function(value) {
		for(i = 0; i < this.obj.options.length; i++) {			
			this.obj.options[i].selected = value;
		}
		
		return this;
	},
	
	//Selects only specific items if they exist in this Multi-Selection list
	selectItems: function(items,delimiter) {
		for(i = 0; i < this.obj.options.length; i++) {
			if(items.split(delimiter).inArray(this.obj.options[i].value)) {
				this.obj.options[i].selected = true;
			} else {
				this.obj.options[i].selected = false;
			}
		}
		
		return this;
	},
	
	//Changes the CSS class
	setClass: function(newClass) {
		this.obj.className = newClass;
		return this;
	},
	
	//Sets the HTML for this Object
	setHTML: function(html) {
		this.obj.innerHTML = html;
		return this;
	},
	
	//Makes the Object visible
	show: function(type) {
		if(type) {
			this.obj.style.display = type;
		} else {
			this.obj.style.display = '';
		}
		
		return this;
	},
	
	//Sorts a Table
	sortTable: function(col,order) {
		
	},
	
	//Switches the Display from visible to invisible and vice-versa
	toggle: function() {
		if(this.obj.style.display == '') {
			this.hide();
		} else if(this.obj.style.display == 'none') {
			this.show();
		}
		
		return this;
	},
	
	//Returns the value of this object
	val: function(v) {
		if(v) {
			this.obj.value = v;
			return this;
		} else {
			return this.obj.value;
		}
	}
		
};

/******************************************************************************\
* Knots Object List
*/

var knotsList = {
	id: null,
	objs: null,
	
	//Initializes the list object
	init: function(id) {
		this.id = id;
		this.objs = document.getElementsByName(id);
		return this;
	},
	
	//Checks or Unchecks this list of Objects
	checkAll: function(value) {
		for(i = 0; i < this.objs.length; i++) {
			this.objs[i].checked = value;
		}
		
		return this;
	},
	
	//Retrieves the currently active Tab of this Tabbed List
	getActiveTab: function(active_class) {
		var elements = document.getElementsByTagName("div");
		var arr = new Array();
		for(i = 0; i < elements.length; i++) {
			var obj = elements[i];
			if(obj.getAttribute("name") == this.id) {
				if(obj.className == active_class) {
					return obj.id;
				}
			}
		}
		
		return false;
	},
	
	//Retrieves the position of the currently active Tab of this Tabbed List
	getActiveTabPos: function(active_class) {
		var elements = document.getElementsByTagName("div");
		var arr = new Array();
		var pos = 0;
		for(i = 0; i < elements.length; i++) {
			var obj = elements[i];
			if(obj.getAttribute("name") == this.id) {
				if(obj.className == active_class) {
					return pos;
				}
				pos++;
			}
		}
		
		return false;
	},
	
	//Makes the data submittable via a form or URL
	serialize: function() {
		var data = new Array();
		
		for(i = 0; i < this.objs.length; i++) {
			var val = this.objs[i].value;
			data.push(val);
		}
		
		return data.join(';');
	},
	
	//Sets the Active Tab of this Tabbed List
	setActiveTab: function(tab, active_class, inactive_class) {
		var elements = document.getElementsByTagName("div");
		var arr = new Array();
		var pos = 0;
		for(i = 0; i < elements.length; i++) {
			var obj = elements[i];
			if(obj.getAttribute("name") == this.id) {
				if(obj.id == tab || pos == tab) {
					obj.className = active_class;
					var id = obj.id.replace("_tab","_div");
					$('#'+id).fadeIn('normal');
				} else {
					obj.className = inactive_class;
					var id = obj.id.replace("_tab","_div");
					$('#'+id).hide();
				}
				pos++;
			}
		}
		
		return this;
	}
};

/******************************************************************************\
* Message Box Implementation
*/

var layer_zindex = 100;

var MessageBox = popup.prototype = {
	id: null,
	onClose: null,
	url: 'AJAX.php',
	
	//Initializes the Message Box
	init: function(id) {
		this.id = id.replace(" ","_");
		return this;
	},
	
	//Loads the MessageBox window
	load: function(data, onLoad, onClose, url) {
		this.onClose = onClose;
		var id = this.id;
		
		if(url) {
			this.url = url;
		} else {
			var url = this.url;
		}
		
		$.ajax({type:'GET',url:url,data:data+'&title='+id,cache:false,success:function(response) {
			//Create Popup Division
			var div = document.createElement('div');
			div.id = "PopupDiv_".layer_zindex;
			div.style.position = "absolute";
			div.style.top = "0px";
			div.style.left = "0px";
			div.style.width = "100%";
			div.style.height = "100%";
			
			div.innerHTML = response;				
			document.body.appendChild(div);
			
			//Raise the Z-Index layout
			popup(id).show();
			popup(id).raise(layer_zindex);
			
			//Register Escape Key to hide Popup
			keyman.register(id,'27',function() {
				popup(id).hide();
			});
			
			//Make Popup draggable
			$('#'+id+'_box').draggable({
					handle: '#'+id+'_hdr'
			}).resizable({handles:"all",autoHide:true,animate:true,ghost:true});
			
			//Call OnLoad event when Popup is loaded
			if(onLoad) {
				onLoad();
			}
		}});
		
		return this;
	},
	
	//Hide the Message Box Division
	hide: function() {
		$('#'+this.id+'_div').slideUp('fast',function() {
			$(this).parent().remove();	
			var onclose = popup(this.id).onClose;
			if(onclose) {
				onclose();
			}
		});
		
		$('#'+this.id+'_grayOut').fadeOut('fast');
		
		keyman.unregister(this.id,'27');
		
		return this;
	},
	
	//Raise the Z-Index of the Message Box
	raise: function(val) {
		var zindex = parseInt($('#'+this.id+'_div').css('z-index'));
		
		if(val) {
			layer_zindex = layer_zindex+val;
			$('#'+this.id+'_div').css('z-index',zindex+val);
			$('#'+this.id+'_grayOut').css('z-index',zindex+val);
		} else {
			$('#'+this.id+'_div').css('z-index',zindex+10);
			$('#'+this.id+'_grayOut').css('z-index',zindex+10);
		}
		
		return this;
	},
	
	//Show the Message Box Division
	show: function() {
		$('#'+this.id+'_div').fadeIn('normal');
		
		if(typeof (window.pageYOffset) == 'number') {
			var doc_height = window.innerHeight+window.scrollMaxY;
			
			$('#'+this.id+'_grayOut').css('height',doc_height+'px');
			$('#'+this.id+'_div').css('top',window.pageYOffset);
		} else {			
			$('#'+this.id+'_grayOut').css('height',document.documentElement.scrollHeight+'px');
			$('#'+this.id+'_div').css('top',document.documentElement.scrollTop);
		}
		
		return this;
	}
};

var MessageNotifier = {
	//Initialize the MessageNotifier
	init: function() {
		setTimeout("MessageNotifier.checkMessages();",1000*60);
	},
	
	//Check for new Messages 
	checkMessages: function() {
		$.ajax({type:'GET',url:'AJAX.php',data:'r=CheckMessages',cache:false,success:function(response) {
				if(response != '0') {
					
				}
		}});
	}
};

/******************************************************************************\
* Handler Functions
*/

var FormPreview = {
	divs: [],
	
	//Initializes the FormPreview with the Divisions of the Layout
	init: function(layout_id) {		
		this.divs = new Array();
		
		$.ajax({async:false,type:'GET',url:'AJAX.php',data:'r=GetDivisions&layout='+layout_id,cache:false,success:function(response) {
				var divs = response.split(',');
				for(i = 0; i < divs.length; i++) {
					FormPreview.divs[i] = new Array();
					
					/*divs[i] = divs[i].trim();
					
					while(divs[i].indexOf(" ") != -1) {
						divs[i] = divs[i].replace(/ /,"_");
					}*/
					
					FormPreview.divs[i][0] = divs[i];
					FormPreview.divs[i][1] = new Array();
				}
		}});
		
		return this;
	},
	
	//Updates the Divs array to keep track of the position of the 
	//elements on the form
	drop: function(div, element) {
		for(i = 0; i < this.divs.length; i++) {
			var divs_arr = this.divs[i];
			if(div == divs_arr[0]) {
				if(!divs_arr[1].inArray(element)) {
					this.divs[i][1].push(element);
				}
			} else {
				var index = divs_arr[1].indexOf(element);
				if(index != -1) {
					this.divs[i][1].splice(index,1);
				}
			}
		}
		
		return this;
	},
	
	//Updates the Divs array - drops the specified element
	//Element is placed into a Temporary Division
	dropTemp: function(element) {
		for(i = 0; i < this.divs.length; i++) {
			var divs_arr = this.divs[i];
			var index = divs_arr[1].indexOf(element);
			if(index != -1) {
				this.divs[i][1].splice(index,1);
			}
		}	
		
		return this;
	},
	
	//Returns Field Placement Information for saving the Form
	getData: function() {
		var arr = new Array();
		for(i = 0; i < this.divs.length; i++) {
			var divs_arr = this.divs[i];
			var div = divs_arr[0];
			arr.push(div + ";" + divs_arr[1].join(','));
		}
		
		return arr.join("\n");
	},
	
	//Returns the total # of fields currently on this Form
	getTotalFields: function() {
		var count = 0;
		for(i = 0; i < this.divs.length; i++) {
			var divs_arr = this.divs[i];
			var div = divs_arr[0];
			count += divs_arr[1].length;
		}
		
		return count;
	},
	
	//Moves an element down 1 spot
	moveDown: function(element) {
		if(!this.divs) return;
		
		for(i = 0; i < this.divs.length; i++) {
			var divs_arr = this.divs[i];
			if(divs_arr[1].inArray(element)) {
				var index = divs_arr[1].indexOf(element);
				if(index != (divs_arr[1].length-1)) {
					var elementAfter = divs_arr[1][index+1];
					this.divs[i][1][index] = elementAfter;
					this.divs[i][1][index+1] = element;
					$('#'+element).insertAfter('#'+elementAfter);
				}
			}
		}
		
		return this;
	},
	
	//Moves all fields to the Temporary division
	moveFields: function() {
		$('#FormPreview .drop').appendTo('#TempHold_div');
		
		return this;
	},
	
	//Moves an element up 1 spot
	moveUp: function(element) {
		for(i = 0; i < this.divs.length; i++) {
			var divs_arr = this.divs[i];
			if(divs_arr[1].inArray(element)) {
				var index = divs_arr[1].indexOf(element);
				if(index != 0) {
					var elementBefore = divs_arr[1][index-1];
					this.divs[i][1][index] = elementBefore;
					this.divs[i][1][index-1] = element;
					$('#'+element).insertBefore('#'+elementBefore);
				}
			}
		}
		
		return this;
	},
	
	//Displays the order of the elements for each division
	print: function() {
		var arr = new Array();
		for(i = 0; i < this.divs.length; i++) {
			var divs_arr = this.divs[i];
			var div = divs_arr[0];
			arr.push("Div: " + div + " has elements: " + divs_arr[1].join(','));
		}
		
		alert(arr.join("\n"));
		
		return this;
	},
	
	//Deletes a Field
	remove: function(element) {
		$('#'+element).remove(); 
		
		for(i = 0; i < this.divs.length; i++) {
			var divs_arr = this.divs[i];
			var index = divs_arr[1].indexOf(element);
			if(index != -1) {
				this.divs[i][1].splice(index,1);
			}
		}
		
		element = element.replace("_field_div","");
		$.ajax({type:'POST',url:'AJAX.php',data:'r=SaveField&field_name='+element,cache:false,success:function(response) {
			$('#af_Result').slideUp('normal').html(response).slideDown('normal');
		}});
		
		return this;
	}
};

var LayoutManager = {
	cur_div: null,
	cur_div_id: null,
	div_count: 0,
	table: null,
	
	//Adds a new Division to the Database and the Layout
	addDivision: function(id,title,type,code,divs) {
		this.div_count++;
		
		var table = o(this.table).obj;
		var row = table.insertRow(table.rows.length);
		row.id = this.div_count+'_div';
		
		var editimg = "<img class='cursor' src='./images/pencil_small.gif' alt='Edit this Division' title='Edit this Division' onclick=\"MessageBox.init('EditDivision','AJAX.php','r=MessageBox&page=DivisionEdit&id="+id+"&div="+this.div_count+"_div&table="+this.table+"');\" />";
		var delimg = "<img class='cursor' src='./images/x_small.gif' alt='Remove from Layout' title='Remove from Layout' onclick=\"LayoutManager.table='"+this.table+"'; LayoutManager.removeDivision('"+this.div_count+"_div');\" />";
		var upimg = "<img class='cursor' src='./images/up_box.gif' alt='Move Division Up' title='Move Division Up' onclick=\"LayoutManager.table='"+this.table+"'; LayoutManager.moveDivisionUp('"+this.div_count+"_div');\" />";
		var downimg = "<img class='cursor' src='./images/down_box.gif' alt='Move Division Down' title='Move Division Down' onclick=\"LayoutManager.table='"+this.table+"'; LayoutManager.moveDivisionDown('"+this.div_count+"_div');\" />";

		var cell0 = row.insertCell(0);
		cell0.innerHTML = editimg + delimg + upimg + downimg;
		
		row.insertCell(1).innerHTML = title;
		row.insertCell(2).innerHTML = type;
		row.insertCell(3).innerHTML = code;
		row.insertCell(4).innerHTML = divs;
	},
	
	//Edits a Division on the Layout Manager
	editDivision: function(div,title,type,code,divs) {
		if(div == "") return;
		
		var row = o(div).obj;
		var cells = row.cells;
		
		cells[1].innerHTML = title;
		cells[2].innerHTML = type;
		cells[3].innerHTML = code;
		cells[4].innerHTML = divs;
	},
	
	//Moves the Division down one position
	moveDivisionDown: function(div) {
		var table = o(this.table).obj;
		var rows = table.rows;
		
		var rowPosToMove = null;
		
		for(i = 0; i < rows.length; i++) {
			var row = rows[i];
			
			if(row.id == div) {
				//This is the row we want to move
				rowPosToMove = i;
				break;
			}
		}
		
		if(rowPosToMove == (table.rows.length-1)) {
			//This is the last row, can't move it down any further
		} else {
			var row = rows[rowPosToMove];
			var rowID = row.id;
			var rowHTML = row.innerHTML;
			var rowBelow = rows[rowPosToMove+1];
			var rowBelowID = rowBelow.id;
			var rowBelowHTML = rowBelow.innerHTML;
			
			row.innerHTML = rowBelowHTML;  //This line breaks in IE
			row.id = rowBelowID;
			rowBelow.innerHTML = rowHTML;
			rowBelow.id = rowID;
		}
	},
	
	//Moves the Division up one position
	moveDivisionUp: function(div) {
		var table = o(this.table).obj;
		var rows = table.rows;
		
		var rowPosToMove = null;
		
		for(i = 0; i < rows.length; i++) {
			var row = rows[i];
			
			if(row.id == div) {
				//This is the row we want to move
				rowPosToMove = i;
				break;
			}
		}
		
		if(rowPosToMove == 1) {
			//This is the first row, can't move it up any further
		} else {
			var row = rows[rowPosToMove];
			var rowID = row.id;
			var rowHTML = row.innerHTML;
			var rowAbove = rows[rowPosToMove-1];
			var rowAboveID = rowAbove.id;
			var rowAboveHTML = rowAbove.innerHTML;
			
			row.innerHTML = rowAboveHTML;
			row.id = rowAboveID;
			rowAbove.innerHTML = rowHTML;
			rowAbove.id = rowID;
		}
	},
	
	//Saves the Layout to the Database
	saveEdit: function() {		
		var table = o(this.table).obj;
		var rows = table.rows;
		
		var divs = new Array();
		for(i = 0; i < rows.length; i++) {
			var row = rows[i];
			var cells = row.cells;
			
			divs.push(cells[1].innerHTML);
		}
		
		divs = divs.join(',');
		
		$.ajax({type:'POST',url:'AJAX.php',data:'r=SaveLayout&divs='+divs+'&'+$('#LayoutEdit_form').serialize(),cache:false,success:function(response) {
				$('#LayoutEdit_Result').slideUp('normal').html(response).slideDown('normal');
				$.ajax({type:'GET',url:'AJAX.php',data:'r=ViewPage&page=LayoutView',cache:false,success:function(response) {
					$('#View_Layouts_div').html(response);
				}});
		}}); 
	},
	
	//Saves a new Layout to the Database
	saveNew: function() {		
		if(!o(this.table).obj) {
			alert('Cannot save Layout with no divisions.');
			return;
		}
		
		var table = o(this.table).obj;
		var rows = table.rows;
		
		var divs = new Array();
		for(i = 0; i < rows.length; i++) {
			var row = rows[i];
			var cells = row.cells;
			
			divs.push(cells[1].innerHTML);
		}
		
		divs = divs.join(',');
		
		$.ajax({type:'POST',url:'AJAX.php',data:'r=SaveLayout&divs='+divs+'&'+$('#LayoutNew_form').serialize(),cache:false,success:function(response) {
				$('#LayoutNew_Result').slideUp('normal').html(response).slideDown('normal');
				$.ajax({type:'GET',url:'AJAX.php',data:'r=ViewPage&page=LayoutView',cache:false,success:function(response) {
					$('#View_Layouts_div').html(response);
				}});
		}}); 
	},
	
	//Removes the Division from the Layout
	removeDivision: function(div) {
		$('#'+div).remove();
		this.div_count--;
	}
};

var PollManager = {
	total: 4,
	
	//Adds a new answer field
	addItem: function(id,prefix) {
		this.total += 1;
		
		var item = document.createElement("li");
		item.id = prefix + this.total;
		
		var input = document.createElement("input");
		input.type = "text";
		input.name = "answers[]";
		input.size = "60";
		
		var img = "&nbsp;<img src='./images/x.gif' class='cursor' title='Remove Answer' alt='Remove Answer' onclick=\"$('#"+prefix+this.total+"').remove();\" />";
		
		item.appendChild(input);
		item.innerHTML += img;
		
		$('#'+id).append(item);
	}
};

var TimeClock = {
	timer: null,
	
	//Submits a punch to the system
	punch: function(type,ssn) {
		$.ajax({type:'POST',url:'AJAX.php',data:'r=SavePunch&type='+type+'&ssn='+ssn,cache:false,success:function(response) {
				if(response.indexOf('Success') != -1) {
					alert(response);
					MessageBox.hide();
				} else {
					alert(response);
				}
		}});
	},
	
	//Displays the current Time on the TimeClock
	show: function() {
		var now = new Date();
		var hours = now.getHours();
		var mins = now.getMinutes();
		var secs = now.getSeconds();
		
		var time = ((hours > 12) ? hours-12 : hours);
		time += ((mins < 10) ? ":0" : ":") + mins;
		time += ((secs < 10) ? ":0" : ":") + secs;
		time += (hours >= 12) ? " PM" : " AM";
		
		$('#timeclock_time').html(time);
		$('#tc_ssn').focus();
		
		this.timer = setTimeout("TimeClock.show()",1000);
	}
};

/******************************************************************************\
* Keyboard Shortcut Implementation
*/

var keyman = {
	registry: [],
	
	//Returns the code of the key pressed
	getCode: function(e) {
		var e = window.event || e;
		var code = e.keyCode || e.which;
		return code;
	},
	
	//Returns the name of the key pressed
	getKey: function(e) {
		var e = window.event || e;
		var code = e.keyCode || e.which;
		var key = String.fromCharCode(code);
		return key;
	},
	
	//Returns the Target element that the event occurred on
	getTarget: function(e) {
		var e = window.event || e;
		var target = e.target || e.srcElement;
		return target;
	},
	
	//Called when a keyboard key is pressed and released
	press: function(e) {
		var code = this.getCode(e);
		var key = this.getKey(e);		
		var target = this.getTarget(e);
		
		if(target.tagName == "INPUT" || target.tagName == "SELECT" || target.tagName == "TEXTAREA") {
			//If on a form field, ask before closing
			for(i = this.registry.length-1; i >= 0 ; i--) {
				var r_id = this.registry[i][0]; 
				var r_key = this.registry[i][1];
				var r_action = this.registry[i][2];
				
				if(key == r_key || code == r_key) {
					if(r_key == 27) {
						//User pressed Escape
						if(confirm("Are you sure you want to close this window?")) {
							r_action();
							break;
						}
					}
				}
			}
		} else {			
			for(i = this.registry.length-1; i >= 0 ; i--) {
				var r_id = this.registry[i][0]; 
				var r_key = this.registry[i][1];
				var r_action = this.registry[i][2];
				
				if(key == r_key || code == r_key) {
					r_action();
					break;
				}
			}
		}
		
		return this;
	},
	
	//Registers a key press event
	register: function(id, key, action) {
		this.registry[this.registry.length] = [id, key, action];
		return this;
	},
	
	//Unregisters a key press event
	unregister: function(id, key) {
		var pos = 0;
		var found = false;
		for(i = 0; i < this.registry.length; i++) {
			if(this.registry[i][0] == id && this.registry[i][1] == key) {
				found = true;
				break;
			}
			pos++;
		}
		
		if(found) {
			this.registry.splice(pos,1);
		}
	}
};

/******************************************************************************\
* Text Editor Functions
*/

var Editor = {
	id: null,	
	current_view: "design",
	
	//Initialize the Editor
	init: function(id) {
		if(o(id).obj) {
			o(id).obj.contentWindow.document.designMode = "On";
			this.id = id;
		}
		
		return this;
	},
	
	//Execute a Command on the Editor
	exec: function(command,value) {
		o(this.id).obj.contentWindow.focus();
		o(this.id).obj.contentWindow.document.execCommand(command,"",value);
		
		return this;
	},
	
	//Appends Text or HTML to the end of the Editor
	append: function(text) {
		o(this.id).obj.contentWindow.document.body.appendChild(text);
		
		return this;
	},
	
	//Clears the Content in the Editor
	clear: function() {
		o(this.id).obj.contentWindow.document.body.innerHTML = "";
		this.focus();
		
		return this;
	},
	
	//Creates and Inserts a Link into the Editor
	createLink: function(text,url) {
		var link = "<a href='"+url+"'>"+text+"</a>";
		var html = this.getHTML() + link;
		this.setHTML(html);
		
		return this;
	},
	
	//Creates and Inserts a Table into the Editor
	createTable: function(rows,cols,border,padding,spacing) {
		var table = o(this.id).obj.contentWindow.document.createElement("Table");
		for(i = 0; i < rows; i++) {
			var tr = table.insertRow(i);
			for(j = 0; j < cols; j++) {
				var td = tr.insertCell(j);
				td.innerHTML = "&nbsp;";
			}
		}
		table.cellPadding=padding;
		table.cellSpacing=spacing;
		table.border="1px solid black";
		this.append(table);
		
		return this;
	},
	
	//This Fixes IE for Menu Based Editor Functions
	fixIE: function() {
		//queryCommandValue(o(this.id).obj.contentWindow.document.selection.createRange());
		
		return this;
	},
	
	//Focuses the Window to the Editor Control
	focus: function() {		
		o(this.id).obj.contentWindow.focus();
		
		return this;
	},
	
	//Retrieves the Source HTML of the Editor
	getHTML: function() {
		return o(this.id).obj.contentWindow.document.body.innerHTML;
		
		return this;
	},
	
	//Opens the Print Dialog to Print the Output in the Editor frame
	print: function() {
		o(this.id).obj.contentWindow.print();
		
		return this;
	},
	
	//Retrieves the current selection on the Editor
	selection: function() {
		return o(this.id).obj.contentWindow.document.selection.createRange();
	},
	
	//This sets the Editor's Initial Content if any exists from the Server
	setContent: function() {
		o(this.id).obj.contentWindow.document.write($('#'+this.id+"_source").val());
		
		return this;
	},
	
	//This saves the Editor's content into a hidden field
	setHidden: function() {
		o(this.id+"_source").obj.value = this.getHTML();
		return this;
	},
	
	//Sets the Source HTML of the Editor
	setHTML: function(html) {
		html = cleanHTML(html);
		o(this.id).obj.contentWindow.document.body.innerHTML = html;
		
		return this;
	},
	
	//Sets the Status Message on the Status Bar
	setStatus: function(status) {
		o(this.id+"_status").obj.innerHTML = status;
		
		return this;
	},
	
	//Switches the Editor view between Design and Source
	switchView: function(view) {
		if(view) {
			if(view == "design") {
				this.current_view = "design";
				cDisplay(this.id+"_source","none");
				cDisplay(this.id,"");
				this.setHTML(o(this.id+"_source").val());
			} else {
				this.current_view = "source";
				cDisplay(this.id,"none");
				cDisplay(this.id+"_source","");
				o(this.id+"_source").obj.value = this.getHTML();
			}
		} else {
			if(this.current_view == "design") {
				this.current_view = "source";
				cDisplay(this.id,"none");
				cDisplay(this.id+"_source","");
				o(this.id+"_source").obj.value = this.getHTML();
			} else {
				this.current_view = "design";
				cDisplay(this.id+"_source","none");
				cDisplay(this.id,"");
				this.setHTML(o(this.id+"_source").obj.value);
			}
		}
		
		return this;
	},
	
	//Returns the current # of Words and Characters
	wordCount: function() {
		var words = o(this.id).obj.contentWindow.document.body.innerHTML.replace(/<[^>]+>/g,"").trim();
		var chars = words.length;
		
		if(chars == 0) {
			words = "";
		} else {
			words = words.split(" ");
		}
		
		alert("# of Words: " + words.length + "\n# of Characters: " + chars);
		
		return this;
	}
};

/******************************************************************************\
* Dynamic Changes Functions
*/

var cur_file_id = 1;

/**
* Method: cAddFileField
*	Purpose: Adds a File Field to a Container
*/
function cAddFileField(container,text,name) {
	cur_file_id++;	
	o(container).setHTML(o(container).html() + "<br />"+text+" <input type='file' id='file"+cur_file_id+"' name='"+name+"' value='' />");
}

/**
* Method: cCheckAll
*	Purpose: Checks or Unchecks a list of Checkbox Elements
*	@param trigger - the ID of the on/off switch
*	@param list - the ID of the list of Elements
*	@param value - true to check, false otherwise
*/
function cCheckAll(list,value,trigger) {
	if(trigger) {
		if(o(trigger).obj.checked) {
			var elements = document.getElementsByName(list);
			for(i = 0; i < elements.length; i++) {
				elements[i].obj.checked = true;
			}
		} else {
			var elements = document.getElementsByName(list);
			for(i = 0; i < elements.length; i++) {
				elements[i].obj.checked = false;
			}
		}
	} else {
		var elements = document.getElementsByName(list);
		for(i = 0; i < elements.length; i++) {
			elements[i].obj.checked = value;
		}
	}
}

/**
* Method: cClass
*	Purpose: Changes 1 or more objects' Class
*	@param elements - a comma-separated list of Object Id's
*	@param toClass - the Class Name to change each element to
*/
function cClass(elements,toClass) {
	elements = elements.split(",");
	for(i = 0; i < elements.length; i++) {
		var element = o(elements[i]).setClass(toClass);
	}
}

/**
* Method: cDisplay
*	Purpose: Changes the Display
*	@param elements - a comma-separated list of element ID's
*	@param type - the type of display ('',block,inline,none, or 'switch' to switch from show/hide)
*/
function cDisplay(elements,type) {
	elements = elements.split(",");
	for(i = 0; i < elements.length; i++) {
		if(type == "switch") {
			o(elements[i]).toggle();
		} else {
			o(elements[i]).show(type);
		}
	}
}

/**
* Method: cleanHTML
*	Purpose: Cleans any crazy characters like Quotes
*/
function cleanHTML(text) {
	while(text.indexOf("[dquote]") != -1) {
		text = text.replace("[dquote]",'"');
	}
	
	while(text.indexOf("[squote]") != -1) {
		text = text.replace("[squote]","'");
	}
	
	return text;
}

/**
* Method: InitFieldTabs
*	Purpose: Initializes Tabs for the Field Creator
*	@param value - the value of the current Field Type
*/
function InitFieldTabs(value) {
	$('#Values_div > div,#Format_div > div').hide();
	
	if(value == "Address") {
		cDisplay('NoValues,NoFormat','block');
	} else if(value == "DataTable") {
		cDisplay('DataTableV,NoFormat','block');
	} else if(value == "Date") {
		cDisplay('DateV,DateF','block');
	} else if(value == "DateTime") {
		cDisplay('DateV,DateF,TimeF','block');
	} else if(value == "File Upload") {
		cDisplay('FileUploadV,NoFormat','block');
	} else if(value == "Full Name") {
		cDisplay('NoValues,NoFormat','block');
	} else if(value == "Label") {
		cDisplay('LabelV,NoFormat','block');
	} else if(value == "LinkLabel") {
		cDisplay('LinkLabelV,NoFormat','block');
	} else if(value == "List") {
		cDisplay('ListV,ListF','block');
	} else if(value == "Lookup") {
		cDisplay('LookupV,NoFormat','block');
	} else if(value == "Password") {
		cDisplay('PasswordV,PasswordF','block');
	} else if(value == "Permissions") {
		cDisplay('NoValues,NoFormat','block');
	} else if(value == "Phone #") {
		cDisplay('NoValues,NoFormat','block');
	} else if(value == "Price") {
		cDisplay('NoValues,NoFormat','block');
	} else if(value == "Section Break") {
		cDisplay('NoValues,NoFormat','block');
	} else if(value == "Social Security #") {
		cDisplay('NoValues,NoFormat','block');
	} else if(value=="TabPane") {
		cDisplay('TabPaneV,NoFormat','block');
	} else if(value == "Text Area") {
		cDisplay('TextAreaV,TextAreaF','block');
	} else if(value == "Text Editor") {
		cDisplay('NoValues,TextEditorF','block');
	} else if(value == "Text Field") {
		cDisplay('TextFieldV,TextFieldF','block');
	} else if(value == "Time") {
		cDisplay('NoValues,TimeF','block');
	} else if(value == "TransferField") {
		cDisplay('TransferFieldV,TransferFieldF','block');
	} else {
		
	}
}
