/**
 * @author Brooks
 */

function getArg(args,field,alt){
	if(args[field]==undefined) return alt;
	return args[field];
}

/*-- Browser Check ----------------*/
function browserCheck(){
	var browser_name = navigator.appCodeName;
	var browser_version = navigator.appVersion;
	var message = "";
	if(browser_name=="IE"){
		if(browser_version<8){
			message = "Hold on!\nYou are running a REALLY old version of Internet Explorer so you may have"+
			"some trouble viewing this site. You are also vulnerable to all kinds of viruses that newer versions"+
			"of IE protect you from. We recommend that you get the latest version.\n"+
			"OR! You could get Firefox, a well-known, free browser that is faster and safer than IE.";
		}
	}
}

/*--$_GET[]---------------------------------------------------*/
var get_params = new Array();

function processGetParameters() {
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			get_params[key] = val;
		}
	}
} 

/*--XML HTTP---------------------------------------------------*/
function GetXmlHttpObject(){
	if("window.XMLHttpRequest");{
		return new XMLHttpRequest();
	}
	if("window.ActiveXObject"){
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

function getHtml(filename){
	var xml_http=GetXmlHttpObject();
	xml_http.open("GET",filename,false);
	xml_http.send(null);
	return xml_http.responseText;
}

/**
 * Ajax.Request.abort
 * extend the prototype.js Ajax.Request object so that it supports an abort method
 */
Ajax.Request.prototype.abort = function() {
    // prevent and state change callbacks from being issued
    this.transport.onreadystatechange = Prototype.emptyFunction;
    // abort the XHR
    this.transport.abort();
    // update the request counter
    Ajax.activeRequestCount--;
};


/*--Swap Image---------------------------------------------------*/
function swap_img(eid,filename){
	
	try {
		var target = document.getElementById(eid);
		target.src = filename;
	}
	catch(e){
		report("error swaping image: "+e);
		
	}
}

function setSelectOptions(name,options,values){
	var select_el = document.getElementById(name);
	//var selected = select_el.selectedIndex;
	var selected = select_el.value;
	var i,tmp_option;
	while(select_el.options.length>0){
		select_el.remove(0);
	}
	for(i=0;i<options.length;i++){
		tmp_option = new Option(options[i],values[i]);
		select_el.options[i]=tmp_option;
	}
	//select_el.selectedIndex = Math.min(selected,select_el.options.length);
	select_el.value=selected;
}
/*--Scroll---------------------------------------------------*/

var TimeToScroll = 200.0;
var LOOP_DELAY = 10.0;

function scroll(eid,dx,dy){
	var element = document.getElementById(eid);
	//if((element.scrollTop+dy)>=0 && (element.scrollTop+dy+element.style.height<=element.scrollHeight)) 
	element.scrollTop+=dy;
	//if((element.scrollLeft+dx)>=0 && (element.scrollLeft+dx+element.style.width<=element.scrollWidth)) 
	element.scrollLeft+=dx;
}

function zeroScroll(eid){
	var element = document.getElementById(eid);
	element.scrollTop=0;
	element.scrollLeft=0;
}

function animateScroll(eid,dx,dy){
	
	try {
		var current_time = new Date().getTime();
		var element = document.getElementById(eid);
		element.startScrollLeft = element.scrollLeft;
		element.startScrollTop = element.scrollTop;
		element.startScrollTime = current_time;
		setTimeout("animateScrollInternal('" + eid + "'," + dx + "," + dy + ")", LOOP_DELAY);
	}
	catch(e){
		report(e);
	}
}

function animateScrollInternal(eid,dx,dy){
	try {
		var cur_time = new Date().getTime();
		var element = document.getElementById(eid);
		var scroll = Math.min((cur_time - element.startScrollTime) / TimeToScroll,1);
		element.scrollTop = Math.max(element.startScrollTop + dy * scroll,0.0);
		element.scrollLeft = Math.max(element.startScrollLeft + dx * scroll,0.0);
		if (cur_time < (element.startScrollTime + TimeToScroll)) 
			setTimeout("animateScrollInternal('" + eid + "'," + dx + "," + dy + ")", LOOP_DELAY);
		else {
			if(typeof(element.animateScrollComplete)=='function') element.animateScrollComplete();
		}
	}
	catch(e){
		report(e);
	}
}

/*--DOM---------------------------------------------------*/
function cancelParentEvent(eid,event){
	var parent = $(eid);
	while(parent=parent.parentNode){
		parent.setAttribute(event,null);
	}
}

function lfCreateElement(tag,attributes){
	tag = new String(tag);
	tag = tag.toLowerCase();
	try{
		var elstr = "<"+tag;
		for (var field in attributes){
			field = new String(field);
			field2 = field.toLowerCase();
			switch(field2){
				case "checked":
					if(attributes['checked']==true) elstr += " checked=\"checked\"";
					break;
				case "selected":
					if(attributes['selected']==true) elstr += " selected=\"selected\"";
					break;
				default:
					if(Object.isString(attributes[field])) elstr += " "+field2+"=\""+attributes[field]+"\"";
					else elstr += " "+field2 +"="+attributes[field];
					break;
			}
		}
		
		switch(tag){
			case 'img':
			case 'input':
				elstr += " />";
				break;
			default:
				elstr +="></"+tag+">";
				break;
		}
		var el = document.createElement(elstr);
		return el;
	}
	catch(e){
		try {
			var el = document.createElement(tag);
			for (var field in attributes){
				if(field=="checked" && attributes[field]!=true) continue;
				if(field=="checked" && attributes[field]==true) attributes[field]="checked";
				if(field=="selected" && attributes[field]!=true) continue;
				if(field=="selected" && attributes[field]==true) attributes[field]="selected";
				el.setAttribute(field,attributes[field]);
			}
			return el;
		}
		catch(f){
			report("lfCreateElement (ie block): "+e+"\nlfCreateElement (other block): "+f);
		}
	}
}

function removeAllChildren(el){
	for(i=el.childNodes.length-1;i>=0;i--){
		el.removeChild(el.childNodes[i]);
	}
}

function getHighestZIndex(){	
	var all_elements = document.getElementsByTagName?
	document.getElementsByTagName("*"):
	document.all; // or test for that too
	var max_z_index = 0;
	for(var i=0;i<all_elements.length;i++) {
		var elem = all_elements[i];
		var cStyle = null;
		if (elem.currentStyle) {cStyle = elem.currentStyle;}
		else if (document.defaultView && document.defaultView.getComputedStyle) {
			cStyle = document.defaultView.getComputedStyle(elem,"");
		}
		var sNum;
		if (cStyle) { sNum = Number(cStyle.zIndex);} 
		else { sNum = Number(elem.style.zIndex);}
		if (!isNaN(sNum)) { max_z_index = Math.max(max_z_index,sNum);}
	}
	return max_z_index;
}

function getStyle(oElm, strCssRule){
	var strValue = "";
	if(strCssRule=="zIndex" || strCssRule=="z_index") strCssRule="z-index";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}


/*--Error Handling---------------------------------------------------*/
function report(message){
	var message = new String(message);
	var message = message.replace(/<br>/gi,"\n");
	alert(message);
	/*
	alert("Javascript Error: this site requires javascript be enabled."+
	" If problems persist, please make sure you are running the latest version of you browser."+
	" If you are using Internet Explorer you should consider switching to Firefox which is faster, safer, easier and FREE.");
	*/
}

function debugDecode(message){
	message = new String(message);
	message = message.replace(/<br>/gi,"\n");
	message = new String(html_entity_decode(message));
	//message = message.replace(/>/gi,"&gt;");
	
	return "<pre style=\"white-space:pre-wrap;\">"+message+"</pre>";
	//return message;
}

/*--XML---------------------------------------------------*/
function createXMLTag(tag,value){
	return "<"+tag+">"+value+"</"+tag+">";
}

function getXMLTagValue(tag_name,xml){
	try{
		if(xml==null) return null;
		var xml_str = new String(xml);
		var open_tag = "<"+tag_name+">";
		var close_tag = "</"+tag_name+">";
		var start_index = xml_str.indexOf(open_tag)+open_tag.length;
		var end_index = xml_str.indexOf(close_tag);
		
		if(start_index < Math.max(open_tag.length,0) || end_index < Math.max(start_index,0)){
			//report("Tag: "+tag_name+" Not Found In:"+xml);
			return null;	//Value not found
		} 
		var value =  xml_str.substring(start_index,end_index);
		
		//report("Tag: "+tag_name+" With Value: "+value+" Extracted From:"+xml);
		return value;
	}
	catch(e){
		report("Error Extracting XML Value:"+e);
		return null;
	}
}

function getXMLTagValueArray(tag_name,xml_raw){
	try {
		var xml = new String(xml_raw);
		var values = new Array();
		var tmp_value;
		var index = 0;
		
		var split_tag = new String("</" + tag_name + ">");
		var xml_split = xml.split(split_tag);
		var n = xml_split.length;
		for(var i=0;i<n;i++){
			xml = new String(xml_split[i]+split_tag);
			tmp_value = getXMLTagValue(tag_name,xml);
			if(tmp_value!=null){
				values[index] = tmp_value;
				index++;
			}
		}
	}
	catch(e){
		report("Error Extracting XML Array:"+e);
	}
	
	return values;
}

function html_entity_decode(str) {
  return str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
}

function zeroPad(number,zeros){
	var order;
	var padded = number;
	for(i=0;i<zeros;i++){
		order = Math.pow(10,i);
		if(number<order && !(i==0 && number==0)) padded = "0"+padded;
	}
	return padded;
}

/*--URL Encoding---------------------------------------------------*/
var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

/*-- STUFF -----------*/
function stripAlphaChars(str_src) { 
	var str_out = new String(str_src); 
    str_out = str_out.replace(/[^0-9]/g, ''); 
    return str_out; 
}

function enforceCash(input_el){
	try {
		/* 0123
		 * 1.12
		 */
		var str = new String(input_el.value);
		var str2 = str.replace(/[^0-9.]/g, '');
		var dot_index = str2.indexOf(".");
		if (dot_index < 1){
			str2 = str2 + ".00";
			dot_index = str2.indexOf(".");
		}
		if(dot_index==0){
			str2 = "0"+str2;
			dot_index++;
		}
		if (str2.length > (dot_index + 3)) 
			str2 = str2.substr(0, dot_index + 2);
		while (str2.length < dot_index + 3) 
			str2 += "0";
		input_el.value = "$"+str2;
	}
	catch(e){
		report("enforceCash: "+e);
	}
}

/*-- SELECTION --*/
function setSelectionRange(input, selectionStart, selectionEnd) {
	if (input.setSelectionRange) {
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	}
	else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
}

function replaceSelection (input, replaceString) {
	if (input.setSelectionRange) {
		var selectionStart = input.selectionStart;
		var selectionEnd = input.selectionEnd;
		input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);
		
		if (selectionStart != selectionEnd){ 
			setSelectionRange(input, selectionStart, selectionStart + 	replaceString.length);
		}else{
			setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
		}
	
	}else if (document.selection) {
		var range = document.selection.createRange();
	
		if (range.parentElement() == input) {
			var isCollapsed = range.text == '';
			range.text = replaceString;
			
			if (!isCollapsed)  {
			range.moveStart('character', -replaceString.length);
			range.select();
			}
		}
	}	
}
 /**
 * @author Brooks
 */
/*--Variables--------------------------------*/
var autosave_timer_id=null;
var upload_timer_id = null;
var upload_start_time;
var listRowClicked;
var listRowCheckboxChanged;
var echoListRow;
var ajax_search_request = null;
var window_handle = null;
var new_window_close_function = null;

var AUTOSAVE_INTERVAL = 500;
/*--Functions------------------------------*/
function refresh(no_cache){
	if(no_cache==undefined) no_cache = true;
	window.location.reload(no_cache);
}

function href(url){
	url = new String(url);
	var index = url.search("http://") + url.search("https://");
	if(index==-2) url = "http://"+url;
	window.location = url;
}

function mailto(url){
	document.location="mailto:"+url;
}

function callto(url){
	document.location="callto:"+url;
}

function go_to(arg_group_id,arg_function,arg_id,other_params){
	try {

		var needs_q = true;
		var destination = "index.php";
		
		//Group
		if(arg_group_id==null){ //If Null, Use Current Group;
			processGetParameters();
			if(get_params['group_id']!=undefined) arg_group_id = get_params['group_id'];
		}
		if(!isNaN(arg_group_id) && arg_group_id > 1){
			destination += "?group_id=" + arg_group_id;
			needs_q = false;
		}
		
		//Function and Id
		if (!(arg_function == null)) {
			destination += ((needs_q)?"?":"&");
			destination += "function=" + arg_function;
			if (!(arg_id == null)) {
				destination += "&id=" + arg_id;
			}
		}
		
		//Other Parameters
		if(other_params!=undefined){
			destination+="&"+other_params;
		}
		
		//report(destination);
		window.location = destination;
	}
	catch(e){
		report(e);
	}
}

function submit(){
	document.current_form.submit();
}

function login(arg_group_id,arg_function,arg_id,in_out){
	try {
		var needs_q = true;
		var destination = "index.php";
		
		if(!isNaN(arg_group_id) && arg_group_id > 1){
			destination += "?group_id=" + arg_group_id;
			needs_q = false;
		}
		if (!(arg_function == null)) {
			destination += ((needs_q)?"?":"&");
			destination += "function=" + arg_function;
			if (!(arg_id == null)) {
				destination += "&id=" + arg_id;
			}
		}
		destination+= in_out?"&login=true":"&logout=true";
		//report(destination);
		window.location = destination;
	}
	catch(e){
		alert(e);
		report(e);
	}
}

function smartPrint(what,ids){
	//Transactions (receipts and invoices)
	//News
	window.open("action.php?method=transaction_print&ids="+(ids.join(",")),"_blank","width=800,resizable=no,toolbar=no,menubar=no,directory=no");
}

function payNow(){
	var url = "action.php?method=transaction_processing";
	var ajax_search_request = new Ajax.Request(url, {
		method: 'post',
		onComplete: 'ajaxAlert',
		onFail: 'ajaxAlert',
		parameters: $('paypal').serialize(true)
		});
	document.paypal.submit();
}

function ajaxAlert(transport){
	report(transport.responseText);
}

function exportCSV(){
	try {
		var selected_str = new String(document.search_form.search_selected.value);
		if (selected_str.length > 0) {
			document.export_form.ids.value = selected_str;
			document.export_form.submit();
		}
		else{
			alert("Oops! Don't forget to select which items you want to export.");
		}
	}
	catch(e){
		report("exportCSV: "+e);
	}
}

/*-- SELECT ALL / NONE ----------------------*/
function existsInArrayString(id,str){
	str = new String(str);
	if(str.include(" "+id+" ")) return true;
	str_array = str.split(" ");
	if(str_array[0]==id) return true;
	if(str_array[str_array.length-1]==id) return true;
}

function trim(str){
	str = new String(str);
	for(var i=0;i<str.length;i++){
		if(str[i]==" ") str = str.substr(1,str.length-1);
		else break;
	}
	for(var i=str.length-1;i>=0;i++){
		if(str[i]==" ") str = str.substr(0,str.length-2);
		else break;
	}
	return str;
}

function selectAll(){
	try {
		var search_matches_str = new String($("search_matches").value);
		var search_matches_array = search_matches_str.split(" ");
		
		for(i=0;i<search_matches_array.length;i++){
			addToSelected(search_matches_array[i]);
		}
	}
	catch(e){
		report("selectAll:"+e);
	}
	
}

function isSelected(id){
	return existsInArrayString(id,$("search_selected").value);
}

function addToSelected(id){
	try {
		if (!isSelected(id)) {
			var ssv = new String($("search_selected").value);
			ssv += " "+id;
			$("search_selected").value = trim(ssv);
		}
		if($("search_row_"+id)!=undefined) $("search_row_"+id).checked = true;	
	}
	catch(e){
		report("addToSelected:"+e);
	}
}

function removeFromSelected(id){
	try{
		//Remove ID
		var search_selected_str = new String($("search_selected").value);
		var search_selected_array = search_selected_str.split(" ");
		search_selected_str = "";
		for(i=0;i<search_selected_array.length;i++){
			if(search_selected_array[i]!=id) search_selected_str += " "+search_selected_array[i];
		}
		
		search_selected_str = trim(search_selected_str);
		
		$("search_selected").value = search_selected_str;
		
		//Turn Off
		if($("search_row_"+id)!=undefined) $("search_row_"+id).checked = false;
		
		
	}
	catch(e){
		report("removeFromSelected:"+e);
	}
}

function toggleSelected(id){
	try {
		var checkbox_el = $("search_row_" + id);
		
		if (checkbox_el != undefined) {
			if (checkbox_el.checked) 
				addToSelected(id);
			else 
				removeFromSelected(id);
		}
	}
	catch(e){
		report("toggleSelected: "+e);
	}
}

function selectNone(){
	//Clear Selected
	var search_selected_str = new String($("search_selected").value);
	$("search_selected").value = "";
	
	//Uncheck
	var search_selected_array = search_selected_str.split(" ");
	for(i=0;i<search_selected_array.length;i++){
		if($("search_row_"+search_selected_array[i])!=undefined) $("search_row_"+search_selected_array[i]).checked=false;
	}
}


/*-- SEARCH -------------------------------*/
function search(method){
	try {
		if(ajax_search_request != null){
			ajax_search_request.abort();
			ajax_search_request = null;
		}
		
		var search_form = document.forms["search_form"];
		if (search_form != undefined) {
			var url = "action.php?method=" + method;
			ajax_search_request = new Ajax.Request(url, {
			method: 'post',
			onComplete: searchComplete,
			parameters: $('search_form').serialize(true),
			onFail: searchFailed
			});
		
			clearPageContent();
			var el = document.getElementById("page_content");
			el.innerHTML = "Searching...";//html_entity_decode(xml);
			var search_status = $("search_status");
			search_status.innerHTML = "Searching...";
			
		}
	}
	catch(e){
		report("Search Error:"+e);
	}
	
}

function searchComplete(transport){
	//report(transport.responseText);
	var debug = false;
	try {
		
		var page_content_el = document.getElementById("page_content");
		var search_status = $("search_status")
		page_content_el.innerHTML = "search complete...<br>";
		
		
		var i;
		var xml = transport.responseText;
		
		if(search_status!= undefined) search_status.innerHTML = "Showing "+getXMLTagValue("n_showing", xml)+" out of "+getXMLTagValue("n_matches", xml);
		var outcome = getXMLTagValue("outcome", xml);
		
		ajax_search_request = null;
		
		
		if (outcome > 0) {
			list_xml = getXMLTagValueArray("list_row", xml);
			if (list_xml != null) {
				//Determine Number Of Rows To Show
				var n = list_xml.length; //Maxlength DTD in php
				
				//Set Showing Hidden Value
				$("search_matches").setAttribute("value",getXMLTagValue("search_matches",xml));
				
				
				//Clear Page
				clearPageContent();
				
				if(n>0){
					//Echo Rows
					for (i = 0; i < n; i++) echoListRow(list_xml[i]);
					
					//Report Response
					if(debug) page_content_el.innerHTML += debugDecode(xml);
					//page_content_el.innerHTML += xml;
				}
				else{
					page_content_el.innerHTML = "No Matches Found<br>";
					if(debug)page_content_el.innerHTML += debugDecode(xml);
				}
				
				
			}
			else {
				report("No Results");
			}
		}
		else {
			page_content_el.innerHTML = "Request Failed<br>";
			//if(debug) 
			page_content_el.innerHTML += debugDecode(xml);
		}
		
	}
	catch(e){
		report("searchComplete:"+e);
	}
}

function searchFailed(transport){
	ajax_search_request = null;
	
	var el = document.getElementById("page_content");
	el.innerHTML = "Request Failed<br>\n"+debugDecode(transport.responseText);
	report("Search Failed:\n"+transport.responseText);
}

function addToShowing(id){
	try {
		var search_showing_el = document.getElementsByName("search_showing")[0];
		var search_showing_str = new String(search_showing_el.value);
		if(search_showing_str.length<1) search_showing_str = " ";
		if(!isShowing(id)) search_showing_str += id + " ";
		search_showing_el.value = search_showing_str;
	}
	catch(e){
		report("addToShowing:"+e);
	}
}

function isShowing(id){
	var search_showing_el = document.getElementsByName("search_showing")[0];
	var search_showing_str = new String(search_showing_el.value);
	var rv = search_showing_str.include((" "+id+" "));
	return rv;
}


/*-- WINDOWS -------------------------*/
function queueWindow(protocol,params){
	//Password Reset
	//Owner Select
	//Property Select
	//Import
	//Export
	//Select File
	try {
		if(window_handle != null) return;
		
		processGetParameters();
		var domain = get_params['function'];
		
		url = "action.php?method=" + protocol;
		/*if(params != undefined){
			for (var key in params) {
				url += "&"+key+"="+params[key];
			}
		}*/
		if(params==undefined) params = {};
		if (domain != undefined) 
			url += "&domain=" + domain;
		
		var my_ajax = new Ajax.Request(url, {
			method: 'post',
			onComplete: openSelectWindow,
			parameters: params,
			onFail: openWindowFail
		});
	}
	catch(e){
		report("queueWindow:"+e);
	}
}

function openSelectWindow(transport){
	try {
		
		window_handle = new Window({
			className: "alphacube",
			title: "",
			width: 680,
			height: 300,
			destroyOnClose: true,
			onClose: onWindowClose,
			recenterAuto: false
		});
		
		window_handle.getContent().update(transport.responseText);
		window_handle.showCenter();
	}
	catch(e){
		report("openSelectWindow:"+e);
	}
}

function openWindowFail(transport){
	report("openWindowFail: "+transport.responseText);
}

function onWindowClose(){
	window_handle = null;
	if (new_window_close_function != null) {
		new_window_close_function();
		new_window_close_function = null;
	}
}

/*-- AUTOSAVE -------------------------*/
function applyFormChanges(xml){
	try {
		//Clear Errors
		var elements = $("current_form").elements;
		var bg_color,tag_name;
		for (i = (elements.length - 1); i >= 0; i--) {
			//alert(elements[i].style.backgroundColor);
			tag_name = elements[i].tagName.toLowerCase();
			if(elements[i].style.backgroundColor != "transparent" && tag_name!="select" && tag_name!="option") elements[i].style.backgroundColor = "transparent";
			//elements[i].setAttribute("style", "background-color:transparent;");
		}
		
		//Apply New Errors
		elements = getXMLTagValueArray("error", xml);
		var tmp_element;
		for (i = (elements.length - 1); i >= 0; i--) {
			tmp_element = document.getElementsByName(elements[i]);
			if(tmp_element[0] != undefined) tmp_element[0].setAttribute("style", "background-color:"+BACKGROUND_COLOR_FAIL+";");
		}
		
		var errors =  (elements.length == 0);
		
		//Apply Changes
		var update_code = getXMLTagValue("update", xml);
		eval(update_code);
		
		return errors;
	}
	catch(e){
		report("applyFormErrors:"+e);
	}
}

function queueAutosave(){
	try {
		setAutosave("Editing", AUTOSAVE_COLOR_CHANGED);
		
		clearInterval(autosave_timer_id);
		var interval = AUTOSAVE_INTERVAL; //500 for release
		var action = "autosave();";
		autosave_timer_id = setInterval(action,interval);
	}
	catch(e){
		report("queueAutosave: "+e);
	}
}

function autosave(){
	try {
		processGetParameters();
		protocol = get_params['function'];
		
		clearInterval(autosave_timer_id);
		setAutosave("Saving", AUTOSAVE_COLOR_SAVING);
		
		var url = "action.php?method="+protocol;
		
		var my_ajax = new Ajax.Request(url, {
			method: 'post',
			onComplete: autosaveComplete,
			parameters: $('current_form').serialize(true),
			onFail: autosaveFail
		});
	}
	catch(e){
		report("autosave: "+e);
	}
}

function autosaveFail(transport){
	report(transport.responseText);
	setAutosave("Fail",AUTOSAVE_COLOR_FAILED);
}

function autosaveComplete(transport){
	try {
		//report(transport.responseText);
		if (applyFormChanges(transport.responseText)) 
			setAutosave("Autosaved", AUTOSAVE_COLOR_SAVED);
		else 
			setAutosave("Error", AUTOSAVE_COLOR_FAILED);
			
		//$('preview').innerHTML=debugDecode(transport.responseText);
	}
	catch(e){
		report("autosaveComplete:"+e);
	}
}

/*--Form Functions -------------------*/
function valueTypeListChanged(list_name){
	//Go through and see if a new row needs to be added
	//queue autosave
	try{
		var email_addresses = $(list_name+"_list");
		var n = email_addresses.getElementsByTagName("tr").length-1;
		var all_full = (n>0);
		var tmp_value;
		for(var i=0;i<n;i++){
			tmp_value = new String(document.getElementsByName(list_name+"_value_"+i)[0].value);
			if(tmp_value.length<1) all_full = false;
		}
		if(all_full) addValueTypeRow(list_name,n);
	}
	catch(e){
		report("emailChanged: "+e);
	}
}

function checkPassword(){
	try {
		var p1 = (document.getElementsByName('password_1'))[0];
		var p2 = (document.getElementsByName('password_2'))[0];
		p1str = new String(p1.value);
		p2str = new String(p1.value);
		
		if(p1str.length<4 || p2str.length<4){
			p1.setAttribute("style", "background-color:"+BACKGROUND_COLOR_FAIL+";");
			p2.setAttribute("style", "background-color:"+BACKGROUND_COLOR_FAIL+";");
		}
		else{
			p1.setAttribute("style", "background-color:transparent;");
			if (p1.value != p2.value) 
				p2.setAttribute("style", "background-color:"+BACKGROUND_COLOR_FAIL+";");
			else 
				p2.setAttribute("style", "background-color:transparent;");
		}
		
		
	}
	catch(e){
		report("checkPassword: "+e);
	}
}

function setPassword(){
	try {
		var p0 = (document.getElementsByName('password'))[0];
		var p1 = (document.getElementsByName('password_1'))[0];
		var p2 = (document.getElementsByName('password_2'))[0];
		var pstr = new String(p1.value);
		if (p1.value == p2.value && pstr.length >= 4) 
			p0.value = p1.value;
		Windows.closeAll();
		queueAutosave();
	}
	catch(e){
		report("setPassword: "+e);
	}
}

function codeChanged(item,e){
	var scroll = $(item.id).scrollTop;
	if(navigator.userAgent.match("Gecko")){
		c=e.which;
	}else{
		c=e.keyCode;
	}
	if(c==9){
		replaceSelection(item,String.fromCharCode(9));
		
		e.returnValue = false;
		setTimeout("$('"+item.id+"').focus();$('"+item.id+"').scrollTop="+scroll+";",10);	
	}
	queueAutosave();
	if(c==9) return false;
}
/*-- ADMIN -----------------------------*/
function setAccess(user_id,access,target_id,target_domain){
	try {
		var my_ajax = new Ajax.Request("action.php", {
			method: 'post',
			onComplete: setAccessComplete,
			parameters: {method: "admin_set",user_id: user_id, access: access, target_id: target_id, target_domain: target_domain},
			onFail: setAccessFail
		});
		
	}
	catch(e){
		report("setAdmin: "+e);
	}
}

function setAccessComplete(transport){
	//report("Response:\n"+transport.responseText);
	search('admin_search');
}

function setAccessFail(transport){
	report(transport.responseText);
}

/*-- SUBSCRIPTION --------------*/
function setSubscription(user_id,value,target_id,target_domain){
	try {
		var my_ajax = new Ajax.Request("action.php", {
			method: 'post',
			onComplete: setSubscriptionComplete,
			parameters: {method: "subscription_set",user_id: user_id, value: value, target_id: target_id, target_domain: target_domain},
			onFail: setAccessFail
		});
		
	}
	catch(e){
		report("setAdmin: "+e);
	}
}

function setSubscriptionComplete(transport){
	//report("Response:\n"+transport.responseText);
	search('subscription_search');
}

function setSubscriptionFail(transport){
	report(transport.responseText);
}

/*-- UPLOAD ---------------------------*/
function uploadBegin(doc_id){
	try{
		setUploadStatus("Initiating...",null,null,false);
		document.upload_form.submit();
		
		clearInterval(upload_timer_id);
		upload_timer_id = setInterval("requestUploadStatus("+doc_id+");",250);
		upload_start_time = new Date();
		
	}
	catch(e){
		report("uploadBegin:"+e);
	}
	
}

function uploadComplete(transport){
	try{
		clearInterval(upload_timer_id);
		
		var size = getXMLTagValue("size",transport.responseText);
		var total = getXMLTagValue("total",transport.responseText);
		if(size!=null && total!=null){
			size = parseInt(size);
			total = parseInt(total);
		}
		setUploadStatus("Upload Successful",size,total,false);
		var progress_el = $("upload_progress");
		progress_el.style.width = "100%";
	}
	catch(e){
		report("uploadComplete:"+e);
	}
}

function uploadFail(transport){
	clearInterval(upload_timer_id);
	setUploadStatus("Upload Failed",null,null,true);
	report(transport.responseText);
}

function requestUploadStatus(doc_id){
	try{
		
		window.test_call++;
		var url = "action.php?method=upload_status&id="+doc_id+"&test_call="+window.test_call;
		var my_ajax = new Ajax.Request(url, {
			method: 'post',
			onComplete: requestUploadStatusComplete,
			onFail: requestUploadStatusFailed
		});
	}
	catch(e){
		report("requestUploadStatus:"+e);
	}
}

function requestUploadStatusComplete(transport){
	try {
		var size = getXMLTagValue("size",transport.responseText);
		var total = getXMLTagValue("total",transport.responseText);
		var error = getXMLTagValue("error",transport.responseText);
		var complete = getXMLTagValue("complete",transport.responseText);
		var note_el = $("upload_note");
		
		var message = "Initializing";
		if (error != null) {
			message = error;
			clearInterval(upload_timer_id);
			setUploadStatus("Upload Error! Please Try Again.", null, null, true);//+"<br>"+ debugDecode(transport.responseText));
			//note_el.innerHTML = transport.responseText;
			note_el.innerHTML = error;
		}
		else {
			if (size != null && total != null) {
				message = "Uploading";
				size = parseInt(size);
				total = parseInt(total);
				setUploadStatus(message, size, total, false);//+"<br>"+ debugDecode(transport.responseText));
			}
			if (complete != null) {
				uploadComplete(transport);
			}
		}
		//note_el.innerHTML = debugDecode(transport.responseText);
	}
	catch(e){
		clearInterval(upload_timer_id);
		report("requestUploadStatusComplete:"+e);
	}
}

function requestUploadStatusFailed(transport){
	try {
		clearInterval(upload_timer_id);
		setUploadStatus("Status Request Failed");
		report(transport.responseText);
	}
	catch(e){
		report("requestUploadStatusFailed:"+e);
	}
}

function setUploadStatus(message,size,total,button_visible){
	try {
		if (size != undefined && total != undefined && size!=null && total != null) {
			var time_remaining = new Date();
			if(size>=total){
				time_remaining.setTime(new Date() - upload_start_time);
				message = "Upload Successful. ";//+total+" Bytes in "+ time_remaining.getMinutes() + ":" + zeroPad(time_remaining.getSeconds(), 2)
				$("upload_progress").style.width = "100%";
			}else{
				time_remaining.setTime(Math.ceil((((new Date()) - upload_start_time) / size) * (total - size)));
				message += " " + size + "/" + total + " Bytes, Time remaining: " + time_remaining.getMinutes() + ":" + zeroPad(time_remaining.getSeconds(), 2);
				var progress_el = $("upload_progress");
				progress_el.style.width = Math.min(Math.ceil(size / total * 100), 100) + "%";
			}
			
		}
		//Set Message
		var status_el = $("upload_status");
		if (status_el != undefined) 
			status_el.innerHTML = message;
			
		//Hide Button
		var upload_button_el = $("upload_button");
		upload_button_el.style.visibility=button_visible?"visible":"hidden";
	}
	catch(e){
		report(e);
	}
}

/*-- DOWNLOAD ------*/
function download(document_id,version){
	window.open("file.php?id="+document_id+"&version="+version);
}

/*-- News & Events Functions -----*/
function setMainImage(div_id,id){
	try {
		var main_image_el = $("main_image");
		var w = 500;
		//main_image_el.style.backgroundImage = "url(action.php?method=document_preview&id=" + id + "&width=" + w + "&height=" + (w * 3 / 4) + ")";
		main_image_el.src = ("action.php?method=document_preview&id=" + id + "&width=" + w + "&height=" + (w * 3 / 4));
		
		var main_image_container = $("story_image_main_image");
		main_image_container.setAttribute("onclick", "download("+id+",1);");
		
		
		
		//Get Note
		var url = "action.php?method=document_note&id="+id;


		new Ajax.Request(url, {
			method: 'post',
			onComplete: fetchDocumentNoteComplete,
			onFail: fetchDocumentNoteFailed
			});
		
		//Set All up
		var image_list_el = $("story_image_list_scroll_area");
		var list_items = image_list_el.childNodes;
		var list_item;
		var i, tmp_id;
		
		//Sub Images
		w=140;
		for (i = 0; i < list_items.length; i++) {
			if(list_items[i].tagName=="DIV"){
				//list_item = list_items[i].getElementsByTagName("div");
				list_item = list_items[i].getElementsByTagName("img");
				list_item = list_item[0];
				tmp_id = new String(list_item.style.width);
				w = tmp_id.substring(0,tmp_id.length-2);
				tmp_id = new String(list_item.id);
				//image_xx
				tmp_id = tmp_id.substring(6);
				//list_item.style.backgroundImage="url(action.php?method=document_preview&id=" + tmp_id + "&width=" + w + "&height=" + (w * 3 / 4) + "&crop=true&radius=5)";
				list_item.src=("action.php?method=document_preview&id=" + tmp_id + "&width=" + w + "&height=" + (w * 3 / 4) + "&crop=true&radius=5");
				list_item.style.cursor = "pointer";
			}
			
		}
		
		
		var this_el = $(div_id);
		//this_el.style.backgroundImage="url(action.php?method=document_preview&id=" + id + "&width=" + w + "&height=" + (w * 3 / 4) + "&fade=200&crop=true&radius=5)";
		this_el.src=("action.php?method=document_preview&id=" + id + "&width=" + w + "&height=" + (w * 3 / 4) + "&fade=200&crop=true&radius=5");
		this_el.style.cursor = "default";
	}
	catch(e){
		report("setMainImage:"+e);
	}
	
}

function fetchDocumentNoteComplete(transport){
	try {
		var image_text_target = $("story_image_main_note");
		if (image_text_target == undefined) 
			image_text_target = $("story_text");
		image_text_target.innerHTML = transport.responseText;
	}
	catch(e){
		report("fetchDocumentNoteComplete:"+e);
	}
}
function fetchDocumentNoteFailed(){
	var image_text_target = $("story_image_main_note");
	if(image_target_text==undefined) image_text_target=$("story_text");
	image_text_target.innerHTML="";//transport.responseText;
}

function imageListScrollUp(){
	try{
		var list_area_el = $("story_image_list_scroll_area");
		var divs = list_area_el.getElementsByTagName("div");
		divs = divs.length/2;
		var dy = list_area_el.scrollHeight/divs;
		list_area_el.animateScrollComplete=imageListScrollBarReset;
		animateScroll("story_image_list_scroll_area",0,-dy);
	}
	catch(e){
		report("imageListScrollDown:"+e);
	}
	
}

function imageListScrollDown(){
	try {
		var list_area_el = $("story_image_list_scroll_area");
		var divs = list_area_el.getElementsByTagName("div");
		divs = divs.length/2;
		var dy = Math.round(list_area_el.scrollHeight/divs);
		list_area_el.animateScrollComplete=imageListScrollBarReset;
		animateScroll("story_image_list_scroll_area", 0, dy);
	}
	catch(e){
		report("imageListScrollDown:"+e);
	}
	
}

function imageListScrollBarReset(){
	try {
		var list_area_el = $("story_image_list_scroll_area");
		var height = 335;//list_area_down_el.style.height;//list_area_el.getAttribute("height");
		var divs = list_area_el.getElementsByTagName("div");
		var dy = list_area_el.scrollHeight/divs.length;
		
		if((list_area_el.scrollHeight-(list_area_el.scrollTop+height))<dy) list_area_el.scrollTop=list_area_el.scrollHeight-height;
		if(list_area_el.scrollTop<dy) list_area_el.scrollTop=0;
		
		
		var list_area_up_el = $("story_image_list_scroll_up");
		
		if (list_area_el.scrollTop >=dy) {
			list_area_up_el.setAttribute("class", "story_image_list_scroll_up");
		}
		else {
			list_area_up_el.setAttribute("class", "story_image_list_scroll_disabled");
		}
		
		
		var list_area_down_el = $("story_image_list_scroll_down");

		if ((list_area_el.scrollHeight-(list_area_el.scrollTop+height))>=dy) {
			list_area_down_el.setAttribute("class", "story_image_list_scroll_down");
		}
		else {
			list_area_down_el.setAttribute("class", "story_image_list_scroll_disabled");
		}

		//var monitor = $("story_image_main_note");
		//monitor.innerHTML=("Scroll Height:"+list_area_el.scrollHeight+"<br>\nHeight:"+height+"<br>\nscrollTop:"+list_area_el.scrollTop);
		
	}
	catch(e){
		report("imageListScrollBarReset: "+e);
	}
}

function submitComment(){
	var comment_form_submit_el = $("comment_form_submit");
	comment_form_submit_el.parentNode.removeChild(comment_form_submit_el);
	var url = "action.php?method=comment_submit";
	new Ajax.Request(url, {
			method: 'post',
			parameters: $('comment_form').serialize(true),
			onComplete: submitCommentComplete,
			onFail: submitCommentFail
			});
}

function submitCommentComplete(transport){
	report(transport.responseText);
	refresh();
}

function submitCommentFail(){
	report(transport.responseText);
}

function flagComment(id){
	var url = "action.php?method=comment_flag&id="+id;
	new Ajax.Request(url, {
			method: 'post',
			onComplete: flagCommentComplete,
			onFail: flagCommentFail
			});
}

function flagCommentComplete(transport){
	//report(transport.responseText);
	refresh(false);
	
}

function flagCommentFail(){
	report(transport.responseText);
}

/*-- TREE OPEN / CLOSE / TOGGLE ----------------------------------*/
window.openTreeNode = function(node){
	var child_nodes = node.childNodes;
	for (i in child_nodes) {
		child_node = child_nodes[i];
		if (child_node instanceof Element && child_node.getAttribute("class") == "tree_node") {
			child_node.style.display = 'block';
		}
		if(child_node instanceof Element && child_node.getAttribute("class") == "tree_node_bullet_closed"){
			element.setAttribute("class","tree_node_bullet_open");
		}
	}
}

window.closeTreeNode = function(node){
	var child_nodes = node.childNodes;
	for (i in child_nodes) {
		child_node = child_nodes[i];
		if (child_node instanceof Element && child_node.getAttribute("class") == "tree_node") {
			child_node.style.display = 'none';
		}
		if(child_node instanceof Element && child_node.getAttribute("class") == "tree_node_bullet_open"){
			element.setAttribute("class","tree_node_bullet_closed");
		}
	}
}

window.toggleTreeNode = function(element){
	try {
		var parent_node = element.parentNode.parentNode;
		var i, node_class, child_node, did_open, n_nodes=0;
		var child_nodes = parent_node.childNodes;
		for (i in child_nodes) {
			child_node = child_nodes[i];
			if (child_node instanceof Element && child_node.getAttribute("class") == "tree_node") {
				if(child_node.style.display=='none'){
					child_node.style.display = 'block';
					did_open = true;
				}
				else{
					child_node.style.display = 'none';
					did_open = false;
				}
				n_nodes ++;
			}
		}
		if(n_nodes>0){
			element.setAttribute("class",(did_open?"tree_node_bullet_open":"tree_node_bullet_closed"));
		}			
	}
	catch(e){
		report("toggleTreeNode: "+e);
	}
}


/*-- Prioritize ----------------------------------*/
			
function prioritize(domain,id,action,search,scope){
	try {
		window.priority_search = search;
		var url = "action.php?method=prioritize&domain="+domain+"&id="+id+"&action="+action;
		if(scope!=undefined) url = url + "&scope="+scope;
		
		var my_ajax = new Ajax.Request(url, {
			method: 'get',
			onComplete: prioritizeComplete,
			onFail: prioritizeFail
		});
	}
	catch(e){
		report("prioritize: "+e);
	}
}

function prioritizeFail(transport){
	report(transport.responseText);
}

function prioritizeComplete(transport){
	try {
		xml = transport.responseText;
		//report(transport.responseText);
		var outcome = getXMLTagValue("outcome", xml);
		if(outcome=="1") search(window.priority_search);
		else alert(xml);//alert("Prioritization Failed");
	}
	catch(e){
		report("prioritizeComplete:"+e);
	}
}

/*-- Store --------------------------------------*/
function invoice(){
	try{
		var search_selected_el = document.getElementsByName("search_selected")[0];
		var sse_val = new String(search_selected_el.value);
		sse_val = sse_val.replace(" ","");
		if(sse_val.length<1) alert("Oops. No items selected.");
		else{
			//alert(sse_val);
			var args = new Object();
			args.search_selected = search_selected_el.value;
			queueWindow('invoice_form',args);
		}
	}
	catch(e){
		report("invoice:"+e);
	}
}/**
 * Copyright 2010 Lunatic Fringe Product Design, LLC
 * This file or the individual contents thereof may not be redistributed without permission.
 * Send Inquiries to info@lunaticfringedesign.com
 */
var BULLET_TYPE_BULLET = 0;
var BULLET_TYPE_CHECKBOX = 1;
var BULLET_TYPE_RADIO = 2;

var AUTOSAVE_COLOR_FAILED = "#FF0000";//"#FF0000";
var AUTOSAVE_COLOR_CHANGED = "#FFFF00";// "#FFFF00";
var AUTOSAVE_COLOR_SAVING = "#DDFF00";
var AUTOSAVE_COLOR_SAVED = "#0F0";// "#00FF00";
var BACKGROUND_COLOR_FAIL = "#FFCCCC";

var BULLET_PUBLICATION_URL = "images/default/bullet_news.png";
var BULLET_SECTION_URL = BULLET_PUBLICATION_URL;
var BULLET_STORY_URL = BULLET_SECTION_URL;
var BULLET_CALENDAR_URL = "images/default/bullet_calendars.png";
var BULLET_EVENT_URL = BULLET_CALENDAR_URL;


var list_protocol = 0; // [0 link to item , 1 select item ];

/*-- Tag Creation ------------------------------------------------*/
function createDiv(style_class,html,parent,on_click){
	try {
		var attributes = new Object();
		if (style_class != null) 
			attributes['CLASS'] = style_class;
		if (on_click != null) 
			attributes['onclick'] = on_click;
		
		var new_div = lfCreateElement("div",attributes);	
		if (html != null) 
			new_div.innerHTML = html;
		if(parent != null) {
			parent.appendChild(new_div);
		}
		
		return new_div;
	}catch(e){
		report("createDiv("+style_class+","+html+","+kids+","+on_click+"): "+e);
	}
}
function createDiv2(args){
	var attributes = new Object();
	for(key in args){
		if(key!="innerHTML" && key!="parent") attributes[key] = args[key];
	}
	var instance = lfCreateElement("div",args.attributes);
	
	if(args.innerHTML!=undefined && args.innerHTML!=null) instance.innerHTML = args.innerHTML;
	if(args.parent!=undefined && args.innerHTML!=null) args.parent.appendChild(instance);
	return instance;
}

function createTextInput(parent,css_class,name,value,size,maxlength,onkeyup,onblur){
	try {
		var attributes = new Array();
		attributes['name'] = name;
		attributes['type'] = "text";
		
		if (css_class != null) attributes['CLASS'] = css_class;
			
		if (value != null) attributes['value'] = value;
		
		if (size != null) attributes['size'] = isNaN(size)?parseInt(size):size;

		if (maxlength != null) attributes['maxlength'] = isNaN(maxlength)?parseInt(maxlength):maxlength;

		if (onkeyup != null) attributes['onkeyup'] = onkeyup;
			
		if (onblur != null) attributes['onblur'] = onblur;
			
		var instance = lfCreateElement("input",attributes);
		parent.appendChild(instance);
		return instance;
		
	}
	catch(e){
		report("createTextInput: "+e);
	}
}

function createRadioInput(parent,name,value,checked,onchange){
	try {
		var attributes = new Array();
		attributes['name'] = name;
		attributes['type'] = "radio";
		
		if (value != null) attributes['value'] = value;
		if (onchange != null) attributes['onchange'] = onchange;
		if (checked) attributes['checked'] = onchange;
			
		var instance = lfCreateElement("input",attributes);
		parent.appendChild(instance);
		return instance;
		
	}
	catch(e){
		report("createRadioInput: "+e);
	}
}

/*-- Custom Elements ---------------------------------------------*/

function createBullet(type,name,value,checked,parent,onclick){
	try {
		if (type == BULLET_TYPE_BULLET) {
			var bullet = document.createElement("img");
			bullet.setAttribute("src","themes/bha/images/bullet.png");
		}
		else {
			var attributes = new Object();
			attributes['name'] = name;
			attributes['id'] = name;
			attributes['CLASS'] = "list_bullet";
			switch (type) {
				default:
					//report(type);
					break;
				case BULLET_TYPE_CHECKBOX:
				case "BULLET_TYPE_CHECKBOX":
					attributes['type']="checkbox";
					break;
				case BULLET_TYPE_RADIO:
				case "BULLET_TYPE_RADIO":
					attributes['type']="radio";
					break;
			}
			
			if (value != null) attributes['value'] = value;
			if (onclick != null) attributes['onclick'] = onclick;
			if (checked) attributes['checked'] = true;
				
			var instance = lfCreateElement("input",attributes);
		}
		
		
		parent.appendChild(instance);
		return instance;
	}
	catch(e){
		report("createBullet: "+e);
	}
}

function createButton(title,type,action,parent){
	try {
		var prefix;
		switch (type) {
			default:
				prefix = "button_general";
				break;
		}
		var components = new Array();
		components['left'] = createDiv(prefix + "_left", "&nbsp;", null, null);
		components['center'] = createDiv(prefix + "_center", title, null, null);
		components['right'] = createDiv(prefix + "_right", "&nbsp;", null, null);
		var button = createDiv(prefix, null, components, action);
		
		if(parent!=null) parent.appendChild(button);
		return button;
	}
	catch(e){
		report("createButton: "+e);
	}
}

/*-- Search ------------------------------------------------------*/

function clearPageContent(){

	try {
		var pc = document.getElementById("page_content");
		var n_children = pc.childNodes.length;
		if(n_children>0){
			for (var i = (n_children-1); i >= 0; i--) {
				pc.removeChild(pc.childNodes[i]);
			}
		}
		
	}
	catch(e){
		report("clearPageContent:"+e);
	}
}

function echoListBreak(title){
	var container = document.getElementById("page_content");
	var list_row = createDiv("list_row_break", null, container,null);
	list_row.innerHTML = title;
}

function echoBasicListRow(bullet_el,row_onclick,title,subtitle,info,content_onclick,menu_options){
	try {
		
		if(title==null || title.length<1) title = "&nbsp;";
		if(info==null || info.length<1) info = "&nbsp;";
		
		var container = document.getElementById("page_content");
		
		var list_row = createDiv("list_row"+((row_onclick!=null)?" clickable":""), null, container, row_onclick);
			var list_row_top = createDiv("list_row_top", null, list_row, null);
			var list_row_middle = createDiv("list_row_middle", null, list_row, null);
			var list_row_bottom = createDiv("list_row_bottom", null, list_row, null);
			
			var list_row_content = createDiv("list_row_content", null, list_row, null);
				if (bullet_el != null) list_row_content.appendChild(bullet_el);
				var list_row_content_content = createDiv("list_row_content_content"+((content_onclick!=null)?" clickable":""), null, list_row_content, content_onclick);
					var list_row_content_title_section = createDiv("list_row_content_title_section", null, list_row_content_content, null);
						var list_row_content_title_section_left = createDiv("list_row_content_title_section_left", null, list_row_content_title_section, null);
								var list_row_content_title_section_title = createDiv("list_row_content_title_section_title",title,list_row_content_title_section_left,null);
								var list_row_content_title_section_subtitle = createDiv("list_row_content_title_section_subtitle",subtitle,list_row_content_title_section_left,null);
						var list_row_content_title_section_right = createDiv("list_row_content_title_section_right", null, list_row_content_title_section, null);
					var list_row_content_info = createDiv("list_row_content_info_section", info, list_row_content_content, null);
		
		if(menu_options!=undefined){
			createListRowMenu(list_row_content_title_section_right,menu_options);
		}
		return list_row_content;
	}
	catch(e){
		report("echoBasicListRow:"+e);
	}

}

function echoBasicListRow2(args){
	try {
		var title = getArg(args,"title","&nbsp;"); title = title.length<1?"&nbsp;":title;
		var subtitle = getArg(args,"subtitle","&nbsp;"); subtitle = subtitle.length<1?"&nbsp;":subtitle;
		var info = getArg(args,"info","&nbsp;"); info = info.length<1?"&nbsp;":info;
		var menu = getArg(args,"menu",null);
		var row_onclick = getArg(args,"onclick",getArg(args,"row_onclick",null));
		var content_onclick = getArg(args,"content_onclick",null);
		var title_class = getArg(args,"title_class","list_row_content_title_section_title");
		var subtitle_class = getArg(args,"subtitle_class","list_row_content_title_section_subtitle");
		var info_class = getArg(args,"info_class","list_row_content_info_section");
		var bullet_el = getArg(args,"bullet",null);
		
		var container = document.getElementById("page_content");
		
		var list_row = createDiv("list_row"+((row_onclick!=null)?" clickable":""), null, container, row_onclick);
			var list_row_top = createDiv("list_row_top", null, list_row, null);
			var list_row_middle = createDiv("list_row_middle", null, list_row, null);
			var list_row_bottom = createDiv("list_row_bottom", null, list_row, null);
			
			var list_row_content = createDiv("list_row_content", null, list_row, null);
				if (bullet_el != null) list_row_content.appendChild(bullet_el);
				var list_row_content_content = createDiv("list_row_content_content"+((content_onclick!=null)?" clickable":""), null, list_row_content, content_onclick);
					var list_row_content_title_section = createDiv("list_row_content_title_section", null, list_row_content_content, null);
						var list_row_content_title_section_left = createDiv("list_row_content_title_section_left", null, list_row_content_title_section, null);
								var list_row_content_title_section_title = createDiv(title_class,title,list_row_content_title_section_left,null);
								var list_row_content_title_section_subtitle = createDiv(subtitle_class,subtitle,list_row_content_title_section_left,null);
						var list_row_content_title_section_right = createDiv("list_row_content_title_section_right", null, list_row_content_title_section, null);
					var list_row_content_info = createDiv("list_row_content_info_section", info, list_row_content_content, null);
		
		if(menu!=null){
			createListRowMenu(list_row_content_title_section_right,menu);
		}
		return list_row_content;
	}
	catch(e){
		report("echoBasicListRow2:"+e);
	}
}

function echoGridRow(args){
	/*
	 * args.id
	 * args.no_bullet
	 * args.columns
	 * args.classes
	 * args.onclicks
	 */
	try {
		var n_columns = args.columns.length;
		
		//Attributes
		var link_out_attributes = new Object();
		link_out_attributes.CLASS = "clickable";
		var attributes = new Object();
		attributes.CLASS = "grid";
		
		//Row
		var tr = lfCreateElement("tr", new Object());
		
		//Bullet Column
		if (args.no_bullet == undefined) {
			var td = lfCreateElement("td", attributes);
			tr.appendChild(td);
			
			var input_attributes = new Object();
			input_attributes.id = "search_row_" + args.id;
			input_attributes.name = "search_row_" + args.id;
			input_attributes.type = "checkbox";
			input_attributes.checked = isSelected(args.id);
			input_attributes.value = "search_row_" + args.id;
			input_attributes.onclick = "toggleSelected(" + args.id + ");";
			var input_box = lfCreateElement("input", input_attributes);
			td.appendChild(input_box);
		}
		
		
		//Columns
		for (var i = 0; i < n_columns; i++) {
			if (args.classes != undefined) 
				attributes.CLASS = args.classes[i];
			
			td = lfCreateElement("td", attributes);
			
			if (args.onclicks != undefined && args.onclicks[i] != null) {
				link_out_attributes.onclick = args.onclicks[i];
				var link_out = lfCreateElement("span", link_out_attributes);
				link_out.innerHTML = args.columns[i];
				td.appendChild(link_out);
			}
			else {
				td = lfCreateElement("td", attributes);
				td.innerHTML = args.columns[i];
			}
			
			tr.appendChild(td);
		}
		
		//Menu
		if(args.menu!=undefined){
			td = lfCreateElement("td",attributes);
			tr.appendChild(td);
			var div_args = new Object();
			div_args.CLASS = "container";
			div_args.style="top:0px;width:100%;height:10px;";
			var div = lfCreateElement("div",div_args);
			td.appendChild(div);
			args.menu.grid_mode = true;
			createListRowMenu(div,args.menu);
		}
		
		var parent = args.parent == undefined ? $("page_content") : args.parent;
		parent.appendChild(tr);
	}
	catch(e){
		report("echoGridRow:"+e);
	}
}

function createListRowMenu(parent,options){
	/*
	 * options.id
	 * options.options
	 * options.actions
	 */
	try {
		var n_items = Math.min(options.options.length,options.actions.length);
		if(n_items<1) return;
		
		var grid_mode = (options.grid_mode!=undefined && options.grid_mode==true)?1:0;
		var attributes = new Object();
		attributes['onmouseover'] = "expandListRowMenu('"+options.id+"',"+grid_mode+");";
		attributes['onmouseout'] = "collapseListRowMenu('"+options.id+"',"+grid_mode+");";
		
		attributes['id'] = "list_row_menu_" + options.id;
		attributes['CLASS'] = "list_row_menu";
							  
		var menu_el = lfCreateElement("table", attributes);
		parent.appendChild(menu_el);
		
		var tbody_attributes = new Object();
		tbody_attributes.id = "list_row_menu_body_"+options.id;
		var menu_body = lfCreateElement("tbody",tbody_attributes);
		menu_el.appendChild(menu_body);
		
		var menu_items = new Array('menu');
		var actions = new Array('null');
	
		for(i=0;i<n_items;i++){
			menu_items.push(options.options[i]);
			actions.push(options.actions[i]);
		}
		
		attributes = new Object();
		attributes['CLASS'] = "clickable";
		
		var tmp_row,tmp_col,tmp_div;
		for(var i=0;i<menu_items.length;i++){
			var row_attributes = new Object();
			if(i>0) row_attributes['style'] = "display: none; white-space:nowrap;";
			else row_attributes['style'] = "white-space:nowrap;";
			
			tmp_row = lfCreateElement("tr",row_attributes);
			menu_body.appendChild(tmp_row);
			
			tmp_col = lfCreateElement("td",new Object());
			tmp_row.appendChild(tmp_col);
			
			attributes['onclick'] = actions[i]+"event.cancelBubble=true;";
			tmp_div = lfCreateElement("div",attributes);
			tmp_div.innerHTML = menu_items[i];
			tmp_col.appendChild(tmp_div);
		}
	}
	catch(e){
		report("createListRowMenu: "+e);
	}
}

function expandListRowMenu(id,grid_mode){
	try {
		var tbody = $('list_row_menu_body_' + id);
		
		for(var i=0;i<tbody.childNodes.length;i++){
			tbody.childNodes[i].style.display="table-row";
		}
		
		if(grid_mode!=undefined && grid_mode==true){ tbody.parentNode.style.zIndex=5;}
		else{
									//   table      lrctsr	   lrcts      lrcc       lrc
			var list_row_content = tbody.parentNode.parentNode.parentNode.parentNode.parentNode;
			list_row_content.style.zIndex=5;
		}
		
	}
	catch(e){
		report("expandListRowMenu("+id+"): "+e);
	}
}

function collapseListRowMenu(id,grid_mode){
	try{
		var tbody = $('list_row_menu_body_' + id);
		
		for(var i=0;i<tbody.childNodes.length;i++){
			tbody.childNodes[i].style.display="none";
		}
		tbody.childNodes[0].style.display="table-row";
		
		if(grid_mode!=undefined && grid_mode==true){ tbody.parentNode.style.zIndex=2;}
		else{
									//   table      lrctsr	   lrcts      lrcc       lrc
			var list_row_content = tbody.parentNode.parentNode.parentNode.parentNode.parentNode;
			list_row_content.style.zIndex=2;
		}
	}
	catch(e){
		report("colapseListRowMenu: "+e);
	}
}

function echoStoryListRow(xml){
	try {
		var id = getXMLTagValue("id", xml);
		var image_id = getXMLTagValue("image_id", xml);
		var handling = getXMLTagValue("handling",xml);
		var lr_args = new Object();
		lr_args.title = getXMLTagValue("title", xml);
		lr_args.subtitle = getXMLTagValue("subtitle",xml);
		lr_args.info = getXMLTagValue("info",xml);
		lr_args.onclick = "go_to(null,'story_view',"+id+");";
		if(getXMLTagValue("published",xml)!="1") lr_args.title_class="list_row_content_title_section_title_alt";
		
		if(image_id=="default") var url = handling=="story"?BULLET_STORY_URL:BULLET_EVENT_URL;
		else var url = "action.php?method=document_preview&id="+image_id+"&width=50&height=38&radius=2&crop=true";
		
		var bullet_args = new Object();
		bullet_args['CLASS'] = "list_row_content_bullet";
		bullet_args['STYLE'] = "right:60px;width:60px;background:url("+url+") no-repeat top left;";
		lr_args.bullet = lfCreateElement("div",bullet_args);
				 
		if(edit_access){
			lr_args.menu = new Object();
			lr_args.menu.id = id;
			lr_args.menu.options = new Array("view","edit");
			lr_args.menu.actions = new Array("go_to("+group+",'"+handling+"_view',"+id+");","go_to("+group+",'"+handling+"_edit',"+id+");");
			
			if($("sort").value==0 && handling=="story"){
				lr_args.menu.options.push("move to top");
				lr_args.menu.options.push("move up");
				lr_args.menu.options.push("move down");
				
				lr_args.menu.actions.push("prioritize('"+priority_domain+"',"+id+","+prioritize_to_top+" ,'stories','"+priority_group+"');");
				lr_args.menu.actions.push("prioritize('"+priority_domain+"',"+id+","+prioritize_up+" ,'stories','"+priority_group+"');");
				lr_args.menu.actions.push("prioritize('"+priority_domain+"',"+id+","+prioritize_down+",'stories','"+priority_group+"');");
			}
		}
		echoBasicListRow2(lr_args);
	}
	catch(e){
		report("echoListRow:"+e);
	}
}
/*-- Lists -------------------------------------------------------*/

function refreshPropertyRows(ids){
	if(ids==undefined) var ids = $("search_selected").value;
	else $("properties_selected").value = ids;
	
	var url = "action.php?method=property_mini_list"+
			  "&ids="+document.forms['current_form'].elements['properties_selected'].value+
			  "&owner="+document.forms['current_form'].elements['properties_owner'].value;
	

	var my_ajax = new Ajax.Request( url, {
									method: 'post',
									onComplete: refreshPropertyRowsComplete,
									onFail: refreshPropertyRowsFailed
									});
	
}

function refreshPropertyRowsComplete(transport){
	var name,id,fields,radios,checked,value,is_billing,is_mailing,onclick;
	try {
		//Clear Old Data
		clearStaticRows("properties");
		
		//Get New Data
		var rows = getXMLTagValueArray("row",transport.responseText);
		
		//Display Variables
		var classes = ["view_text_parcel","view_text_lot","view_text_street"];
		var name = null;
		//Display Rows
		for(var i=0;i<rows.length;i++){
			fields = [getXMLTagValue("parcel_number",rows[i]),getXMLTagValue("lot_number",rows[i]),getXMLTagValue("street",rows[i])]
			
			is_billing = (getXMLTagValue("is_billing",rows[i]));
			is_mailing = (getXMLTagValue("is_mailing",rows[i]));
			
			is_billing = (getXMLTagValue("is_billing",rows[i])=="true");
			is_mailing = (getXMLTagValue("is_mailing",rows[i])=="true");
			
			radios = ["address_billing","address_mailing"];
			values = ["property_"+i,"property_"+i];
			
			checked = [is_billing,is_mailing];
			onclick = "go_to(null,'property_view',"+getXMLTagValue("id",rows[i])+");";
			
			addStaticRow("properties_list",name,classes,fields,radios,checked,values,onclick);
		}
	}
	catch(e){
		report("refreshPropertyRowsComplete:"+e);
	}
	
}

function refreshPropertyRowsFailed(transport){
	report("refreshPropertyRowsFailed:"+ transport.responseText);
}

function refreshOwnerRows(ids){
	if(ids==undefined) var ids = $("people_selected").value;
	else $("people_selected").value = ids;
	
	var url = "action.php?method=directory_mini_list"+
			  "&ids="+ids;
	var my_ajax = new Ajax.Request( url, {
									method: 'post',
									onComplete: refreshOwnerRowsComplete,
									onFail: refreshOwnerRowsFailed
									});
}

function refreshOwnerRowsComplete(transport){
	var i,fields,radios,values,checked,phone,email,onclick;
	try {
		//Clear Rows
		clearStaticRows("person");
		
		//Get New Data
		var rows = getXMLTagValueArray("row",transport.responseText);
		
		//Display Variables
		var classes = ["view_owner_last","view_owner_first","view_owner_email"];
		var name = null;
		
		//Produce Rows
		for(var i=0;i<rows.length;i++){
			//phone = getXMLTagValue("value",getXMLTagValue("phone_number_primary",rows[i]));
			email = getXMLTagValue("value",getXMLTagValue("email_address_primary",rows[i]));
			fields = [getXMLTagValue("name_last",rows[i]),getXMLTagValue("name_first",rows[i]),email];
			radios = new Array();
			values = new Array();
			checked = new Array();
			onclick = "go_to(null,'person_view',"+getXMLTagValue("id",rows[i])+");"
			
			addStaticRow("person_list",name,classes,fields,radios,checked,values,onclick);
		}
	}
	catch(e){
		report("refreshOwnerRowsComplete:"+e);
	}
	
}

function refreshOwnerRowsFailed(transport){
	report("refreshOwnerRowsFailed: "+ transport.responseText);
}

function addStaticRow(container_eid,name,classes,fields,radios,checked,values,onclick){
	var i,col;
	try {
	
		var parent = document.getElementById(container_eid).getElementsByTagName("tbody")[0];
		var row = document.createElement("tr");
		parent.appendChild(row);
		if (onclick != null) {
			row.setAttribute("class",classes[i]+" clickable");
		}
		
		for(i=0;i<fields.length;i++){
			col = document.createElement("td");
			col.innerHTML = fields[i];
			col.setAttribute("class",classes[i]);
			if (onclick != null) {
				col.setAttribute("onclick", onclick);
			}
			row.appendChild(col);
		}
		
		//Create Radios
		for (i = 0; i < radios.length; i++) {
			td = document.createElement("td");
			row.appendChild(td);
			createRadioInput(td,radios[i], values[i],checked[i], "queueAutosave();");
		}
	}
	catch(e){
		report("addStaticRow: "+e);
	}
}

function clearStaticRows(container_eid){
	try {
		var parent = document.getElementById(container_eid + "_list").getElementsByTagName("tbody")[0];
		var elements = parent.getElementsByTagName("tr");
		for (i = (elements.length - 1); i > 0; i--) {
			parent.removeChild(elements[i]);
		}
	}
	catch(e){
		report("clearStaticRows("+container_eid+"): "+e);
	}
}

/*-- Autosave ----------------------------------------------------*/

function setAutosave(text,color){
	var el = document.getElementById("autosave");
	if(el != undefined){
		el.innerHTML = text;
		el.setAttribute("style","background-color:"+color+";");
	}
}

/*-- Dynamic Rows -------------------------------------------------*/

//Email Address
function dynamicEmailAddressRowChanged(name){
	try {
		addDynamicEmailAddressRow(name);
		queueAutosave();
	}
	catch(e){
		report("dynamicEmailAddressRowChanged: "+e);
	}
}

function addDynamicEmailAddressRow(name){
	var fields = ["value","type"];
	var classes = ["input_text_value","input_text_type"];
	var sizes = [null,null];
	var maxlengths = [100,50];
	var radios = [name+"_primary"];
	var onchange = "dynamicEmailAddressRowChanged('"+name+"');";
	var deres_prefix = "consolidateDynamicEmailAddressRow";
	addDynamicInputRow(name,fields,classes,sizes,maxlengths,radios,onchange,deres_prefix);
}

function consolidateDynamicEmailAddressRow(name,row_index){
	var fields = ["value","type"];
	var critical_field_indices = [0];
	var radios = [name+"_primary"];
	var deres_prefix = "consolidateDynamicEmailAddressRow";
	consolidateDynamicInputRow(name,fields,critical_field_indices,radios,row_index,deres_prefix);
}

//Address
function dynamicAddressRowChanged(name){
	addDynamicAddressRow(name);
	queueAutosave();
}

function addDynamicAddressRow(name){
	var fields = ["street","city","state","zip"];
	var classes = ["input_text_street","input_text_city","input_text_state","input_text_zip"];
	var sizes = [null,null,null,null];
	var maxlengths = [100,100,2,5];
	var radios = ["address_billing","address_mailing"];
	var onchange = "dynamicAddressRowChanged('"+name+"');";
	var deres_prefix = "consolidateDynamicAddressRow";
	addDynamicInputRow(name,fields,classes,sizes,maxlengths,radios,onchange,deres_prefix);
}

function consolidateDynamicAddressRow(name,row_index){
	try {
		var fields = ["street", "city", "state", "zip"];
		var critical_field_indices = [0, 1, 2, 3];
		var radios = ["address_billing", "address_mailing"];
		var deres_prefix = "consolidateDynamicAddressRow";
		consolidateDynamicInputRow(name, fields, critical_field_indices, radios, row_index, deres_prefix);
	}
	catch(e){
		"consolidateDynamicAddressRow("+name+","+row_index+"): "+e;
	}
}

//Phone Number
function dynamicPhoneNumberRowChanged(name){
	addDynamicPhoneNumberRow(name);
	queueAutosave();
}

function addDynamicPhoneNumberRow(name){
	var fields = ["value","type"];
	var classes = ["input_text_value","input_text_type"]
	var sizes = [null,null];
	var maxlengths = [20,20];
	var radios = [name+"_primary"];
	var onchange = "dynamicPhoneNumberRowChanged('"+name+"');";
	var deres_prefix = "consolidateDynamicPhoneNumberRow";
	addDynamicInputRow(name,fields,classes,sizes,maxlengths,radios,onchange,deres_prefix);
}

function consolidateDynamicPhoneNumberRow(name,row_index){
	//var name = "address";
	var fields = ["value","type"];
	var critical_field_indices = [0];
	var radios = [name+"_primary"];
	var deres_prefix = "consolidateDynamicPhoneNumberRow";
	consolidateDynamicInputRow(name,fields,critical_field_indices,radios,row_index,deres_prefix);
}

/*-- Dynamic Input Row --------------------------------------------*/

function addDynamicInputRow(name,fields,classes,sizes,maxlengths,radios,onchange,deres_prefix){
	var i,j,n,col,el,td,tmp_value;
	try {
	
		var parent = document.getElementById(name + "_list").getElementsByTagName("tbody")[0];
		var new_row_index = parent.getElementsByTagName("tr").length-1;
		
		//Decide If Add is Needed
		var all_full = (new_row_index > 0);
		var row_has_text;
		for (i = 0; i < new_row_index; i++) {
			row_has_text = false;
			for (j = 0; j < fields.length; j++) {
				tmp_value = new String(document.getElementsByName(name + "_"+fields[j]+"_" + i)[0].value);
				if (tmp_value.length > 0) row_has_text = true;
			}
			if(!row_has_text) all_full = false;
		}
		
		//Perform the Add
		if (all_full && new_row_index < 20) {
			var row = document.createElement("tr");
			parent.appendChild(row);
			
			n = Math.min(fields.length, sizes.length, maxlengths.length);
			//Add The Fields To New Level
			for (i = 0; i < n; i++) {
				col = document.createElement("td");
				row.appendChild(col);
				//parent,css_class,name,value,size,maxlength,onkeyup,onblur
				createTextInput(col,classes[i], (name + "_" + fields[i] + "_" + new_row_index),null,sizes[i],maxlengths[i], onchange, null);
				
				
				//Set Deres Function For Previous Level
				if (new_row_index > 0) {
					el = document.getElementsByName(name + "_" + fields[i] + "_" + (new_row_index - 1))[0];
					el.setAttribute("onblur", deres_prefix+"('"+name+"',"+(new_row_index-1)+");");
				}
			}
			
			//Create Radios
			for (i = 0; i < radios.length; i++) {
				td = document.createElement("td");
				row.appendChild(td);
				
				//create radios for previous level
				td = (parent.getElementsByTagName("tr")[new_row_index]).getElementsByTagName("td")[n+i];
				//parent,name,value,checked,onchonge
				createRadioInput(td,radios[i], name+"_"+(new_row_index - 1),false, "queueAutosave();");
			}
		}
		else{
			//report("No Add");
		}
	}
	catch(e){
		report("addDynamicInputRow: "+e);
	}
}

function consolidateDynamicInputRow(name,form_fields,critical_field_indices,radios,row,deres_prefix){

	//queue autosave
	var i,n,value,input,inputs;
	
	try{
		var values = new Array();
		var deresolutionize = true;
		
		for(i=0;i<critical_field_indices.length;i++){
			value = new String(document.getElementsByName(name+"_"+form_fields[critical_field_indices[i]]+"_"+row)[0].value);
			if(value.length > 0) deresolutionize = false;
		}
		
		var parent = document.getElementById(name+"_list").getElementsByTagName("tbody")[0];
		/*-- Deresolutionize -------------------------------*/
		if(deresolutionize && row<(parent.getElementsByTagName("tr").length-2)){
			//remove child
			var target = parent.getElementsByTagName("tr")[1+row];
			parent.removeChild(target);
			
			//renumber
			var rows = parent.getElementsByTagName("tr");
			
			for(i=1;i<rows.length;i++){
				inputs = rows[i].getElementsByTagName("input");
				
				//input names and deres targets
				n = form_fields.length;
				for(j=0;j<n;j++){
					inputs[j].setAttribute("name",name+"_"+form_fields[j]+"_"+(i-1));
					if(i<(rows.length-1)) inputs[j].setAttribute("onblur", deres_prefix+"('"+name+"',"+(i-1)+")");
					else inputs[j].setAttribute("onblur","");
				}
				
				//radio values
				if (i < (rows.length - 1)) {
					for (j = 0; j < radios.length; j++) {
						//report((n + j) + "/" + inputs.length);
						inputs[n + j].setAttribute("value", name + "_" + j);
					}
				}
			}
			
			//Make Sure a Radio Value Is Selected
			for(i=(radios.length-1);i>=0;i--){
				inputs = document.getElementsByName(radios[i]);
				row_selected = false;
				for(j=(inputs.length-1);j>=0;j--){
					if(inputs[j].checked == true) row_selected = true;
				}
				if(!row_selected && inputs.length>0) inputs[0].checked = true;
			}
			
		}
	}
	catch(e){
		report("consolidateDynamicInputRow("+name+","+form_fields+","+critical_field_indices+","+radios+","+row+","+deres_prefix+"): "+e);
	}
}

/*-- UI Element Support --------------------------------*/
function dateYearBlur(eid,onchange){
	var year_el = document.getElementById(eid+"_year");
	var year = parseInt(year_el.value);
	if(year<1900 || 9999<year){
		var now = new Date();
		year_el.value = now.getFullYear();
		eval(onchange);
	}
}
function dateChanged(eid,onchange){
	try {
		var year_el = document.getElementById(eid+"_year");
		var month_el = document.getElementById(eid+"_month");
		var day_el = document.getElementById(eid+"_day");//document.getElementsByName(eid + "_day")[0];
		//var hour_el = document.getElementById(eid+"_hour");
		//var minute_el = document.getElementById(eid+"_minute");
		
		//Year
		var block_onchange = false;
		var year = parseInt(year_el.value);
		if(year<1900 || 9999<year){
			//var now = new Date();
			//year_el.value = now.getFullYear();
			block_onchange = true;
		}

		//Day Faffery
		var days_in_month;
		if (month_el.value == 2) {
			// In the Gregorian calendar there is a leap year every year divisible by four
			// except for years which are both divisible by 100 and not divisible by 400.
			
			if (year_el.value % 4 != 0) {
				days_in_month = 28;
			}
			else {
				if (year_el.value % 100 != 0) {
					days_in_month = 29; // Leap year
				}
				else {
					if (year_el.value % 400 != 0) {
						days_in_month = 28;
					}
					else {
						days_in_month = 29; // Leap year
					}
				}
			}
		}
		else {
			if ((month_el.value <= 7 && month_el.value % 2 != 0) || (8 <= month_el.value && month_el.value % 2 == 0)) 
				days_in_month = 31;
			else 
				days_in_month = 30;
		}
		
		var new_day;
		while (day_el.options.length > days_in_month) {
			if(day_el.value == day_el.options[day_el.options.length-1].value) day_el.options[day_el.options.length-2].selected = true;
			day_el.remove(day_el.options.length-1);
		}
		while (day_el.options.length < days_in_month) {
			day_el.options[day_el.options.length] = new Option((day_el.options.length+1),(day_el.options.length+1),false);
			//day_el.add(new_option,day_el.options.length);
		}
		
		if(!block_onchange) eval(onchange);
	}
	catch(e){
		report("dateChanged: "+e);
	}
}

function refreshRepeatOptions(autosave){
	try {
		var i,j;
		var days = new Array('Day','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
		var day_offsets = new Array('Last');
		for(i=1;i<=31;i++){
			j = i%10;
			day_offsets[i]= (i+"th");
			if(j==1) day_offsets[i]= (i+"st");
			if(j==2) day_offsets[i]= (i+"nd");
			if(j==3) day_offsets[i]= (i+"rd");
		}
		var indices = new Array();
		for(var i=0;i<=31;i++) indices[i]=i;
		
		var period_el = $("repeat_period");
		var offset_el = $("repeat_day_offset");
		var day_el = $("repeat_day");
		var month_el = $("repeat_month");
		var of_el = $("repeat_of");
		var label = $("repeat_label");
		
		var value = parseInt(period_el.value);
		switch(value){
			default:
			case 0: //Weekly
				label.innerHTML = "Every";
				offset_el.style.display="none";
				of_el.style.display="none";
				month_el.style.display="none";
				
				days = days.slice(1);
				indices = indices.slice(1,8);
				setSelectOptions("repeat_day",days,indices);

				break;
			case 1: //Monthly
				label.innerHTML = "On The";
				offset_el.style.display="";
				of_el.style.display="none";
				month_el.style.display="none";
				
				//Repopulate Days
				var tmp_indices = indices.slice(0,8);
				setSelectOptions("repeat_day",days,tmp_indices);
				
				//Adjust Offsets
				if(parseInt(day_el.value)>0){
					//Limit Offsets
					day_offsets = day_offsets.slice(0,6);
					tmp_indices = indices.slice(0,6);
					setSelectOptions("repeat_day_offset",day_offsets,tmp_indices);
				}
				else{
					//Repopulate Offsets
					setSelectOptions("repeat_day_offset",day_offsets,indices);
				}
				break;
			case 2://Yearly
				label.innerHTML = "On The";
				offset_el.style.display="";
				of_el.style.display="";
				month_el.style.display="";
				
				//Repopulate Days
				var tmp_indices = indices.slice(0,8);
				setSelectOptions("repeat_day",days,tmp_indices);
				
				//Account for days in month
				var mo = month_el.value;
				var days_in_mo = 31;
				if((mo<=7 && mo%2==0) || (8<=mo && mo%2==1)) var days_in_mo = 30;
				if(mo==2) days_in_mo=29;
				
				//Adjust Offsets
				if(parseInt(day_el.value)>0){
					//Limit Offsets
					day_offsets = day_offsets.slice(0,6);
					tmp_indices = indices.slice(0,6);
					setSelectOptions("repeat_day_offset",day_offsets,tmp_indices);
				}
				else{
					//Repopulate Offsets
					day_offsets = day_offsets.slice(0,days_in_mo+1);
					tmp_indices = indices.slice(0,days_in_mo+1);
					setSelectOptions("repeat_day_offset",day_offsets,tmp_indices);
				}
				break;
		}
		if(autosave!=undefined && autosave==true) queueAutosave();
	}
	catch(e){
		report("refreshRepeatOptions:"+e);
	}
}

/*-- Windows ----------*/
function queuePasswordWindow(id){
	try {
		if(window_handle!=null) return;
		url = "action.php?method=password_reset&id=" + id;
		var my_ajax = new Ajax.Request(url, {
			method: 'get',
			onComplete: openPasswordWindow,
			onFail: openWindowFail
		});
	}
	catch(e){
		report("queuePasswordWindow:"+e);
	}
}

function openPasswordWindow(transport){

	try {
		transport.responseText;
		window_handle = new Window({
			className: "alphacube",
			title: "",
			width: 400,
			height: 150,
			destroyOnClose: true,
			onClose: onWindowClose,
			recenterAuto: false
		});
		
		
		window_handle.getContent().update(transport.responseText);
		window_handle.showCenter();
	}
	catch(e){
		report("openPasswordWindow:"+e);
	}
}

/*-- UPDATE DROPDOWN MENU -------------*/
function updateSelectMenu(eid,indices,options,selected){
	try {
		if (indices.length != options.length) 
			return;
		
		//Remove All Options
		var n_options = $(eid).options.length;
		for (var i = n_options - 1; i >= 0; i--) {
			$(eid).remove(i);
		}

		//Add New Values
		n_options = indices.length;
		if (selected == undefined) 
			selected = indices[0];
		for (i = 0; i < n_options; i++) {
			$(eid).options[i] = new Option(options[i], indices[i], indices[i] == selected);
		}
	}
	catch(e){
		report("updateSelectMenu: "+e);
	}
	
}

