/**
 * @author Brooks
 */

/*--$_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();
	var ref_obj = new Object();
	var ref_array = {bs:"bs"};
	try{
		var elstr = "<"+tag;
		for (var field in attributes) {
			var bs = false;
			if(ref_obj[field]!=undefined || ref_array[field]!=undefined) bs = true;;
			if(ref_obj[field]!=null || ref_array[field]!=null) bs = true;;
			if(ref_obj[field] == attributes[field]) bs = true;
			if(!bs){
				field = new String(field);
				field=field.toLowerCase();
				switch(field){
					case "checked":
						if(attributes['checked']==true) elstr += " checked=\"checked\"";
						break;
					case "selected":
						if(attributes['selected']==true) elstr += " selected=\"selected\"";
						break;
					default:
						elstr += " "+field+"="+ (isNaN(attributes[field])?("\""+attributes[field]+"\""):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){
				el.setAttribute(field,attributes[field]);
			}
			return el;
		}
		catch(f){
			report("lfCreateElement (ie block): "+e+"\nlfCreateElement (other block): "+f);
		}
	}
}


/*--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>";
}

/*--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; 
}

/**
 * @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 {
		document.export_form.ids.value = document.search_form.search_selected.value;
		document.export_form.submit();
	}
	catch(e){
		report("exportCSV: "+e);
	}
}

/*-- SELECT ALL / NONE ----------------------*/
function selectAll(){
	try {
		var search_selected_el = document.getElementsByName("search_selected")[0];
		var search_showing_el = document.getElementsByName("search_showing")[0];
		
		var search_showing_str = new String(search_showing_el.value);
		var search_showing_array = search_showing_str.split(" ");
		for (var i = 0; i < search_showing_array.length; i++) {
			if (search_showing_array[i].length > 0) 
				addToSelected(search_showing_array[i]);
		}
		
		//Physically check everything
		var form_elements = document.forms["list_form"].elements;
		for (key in form_elements) {
			form_elements[key].checked = true;
		}
	}
	catch(e){
		report("selectAll:"+e);
	}
	
}

function isSelected(id){
	var search_selected_el = document.getElementsByName("search_selected")[0];
	var search_selected_str = new String(search_selected_el.value);
	return search_selected_str.include((" "+id+" "))
}

function addToSelected(id){
	try {
		var search_selected_el = document.getElementsByName("search_selected")[0];
		var search_selected_str = new String(search_selected_el.value);
		if(search_selected_str.length<1) search_selected_str = " ";
		if(!isSelected(id)) search_selected_str += id + " ";
		search_selected_el.value = search_selected_str;
	}
	catch(e){
		report("addToSelected:"+e);
	}
}

function removeFromSelected(id){
	try{	
		var search_selected_el = document.getElementsByName("search_selected")[0];
		var search_selected_str = new String(search_selected_el.value);
		var search_selected_array = search_selected_str.split(" ");
		search_selected_str = " ";
		for (var i = 0; i < search_selected_array.length; i++) {
			if (search_selected_array[i] != id && search_selected_array[i].length > 0) 
				search_selected_str += search_selected_array[i] + " ";
		}
		search_selected_el.value = search_selected_str;
	}
	catch(e){
		report("removeFromSelected:"+e);
	}
}

function selectNone(){
	var search_selected_el = document.getElementsByName("search_selected")[0];
	search_selected_el.value = "";
	
	//Uncheck Everything
	var form_elements = document.forms["list_form"].elements;
	for(key in form_elements){
		form_elements[key].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_form").elements['search_showing'].setAttribute("value",getXMLTagValue("indices_showing",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);
}

/*-- 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 (domain != undefined) 
			url += "&domain=" + domain;
		var my_ajax = new Ajax.Request(url, {
			method: 'post',
			onComplete: openSelectWindow,
			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);
	}
}

/*-- 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)
			}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 = height/(divs.length/2);
		
		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);
	}
}
/**
 * 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 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);
		}
		/*
		var new_div = document.createElement("div");
		if (style_class != null) 
			new_div.setAttribute("class", style_class);
		if (html != null) 
			new_div.innerHTML = html;
		if (on_click != null) 
			new_div.setAttribute("onclick", on_click);
		if(parent != null) {
			parent.appendChild(new_div);
		}
		*/
		return new_div;
	}catch(e){
		report("createDiv("+style_class+","+html+","+kids+","+on_click+"): "+e);
	}
}

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 Array();
			attributes['name'] = 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 echoBasicListRow(bullet_el,row_onclick,title,subtitle,info,content_onclick,menu_options){
	try {
		
		if(title==null || title.length<1) info = "&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 = createDiv("list_row", null, container, null);
			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_content = createDiv("list_row_content_content", null, list_row_content, null);
					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_div", 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 createListRowMenu(parent,options){
	try {
		var attributes = new Object();
		attributes['onmouseover'] = "expandListRowMenu('"+options['id']+"');";
		attributes['onmouseout'] = "collapseListRowMenu('"+options['id']+"');";
		
		attributes['id'] = "list_row_menu_" + options['id'];
		attributes['style'] = "position: absolute; "+
							  "right:0px;";
							  "background-color:#FFF;"+
							  "text-align:right;";
							  
		var menu_el = lfCreateElement("table", attributes);
		parent.appendChild(menu_el);
		
		
		var menu_items = new Array();
		var actions = new Array();
		if(options['options'].length>1){
			menu_items[0] = 'menu';
			actions[0] = 'null;';
		}
		var s = menu_items.length;
		for(i=s;i<options['options'].length+s;i++){
			menu_items[i] = options['options'][i-s];
			actions[i] = options['actions'][i-s];
		}
		
		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_el.appendChild(tmp_row);
			
			tmp_col = lfCreateElement("td",new Object);
			tmp_row.appendChild(tmp_col);
			
			attributes['onclick'] = actions[i];
			tmp_div = lfCreateElement("div",attributes);
			tmp_div.innerHTML = menu_items[i];
			tmp_col.appendChild(tmp_div);
			
			
		}
		//menu_el.childNodes[0].style.display="table-row";
		//menu_el.childNodes[0].setAttribute("class","");
	}
	catch(e){
		report("createListRowMenu: "+e);
	}
}

function expandListRowMenu(id){
	try {
		var parent = $('list_row_menu_' + id);
		parent.style.border = "1px solid";
		parent.style.backgroundColor = "#FFF";
		
		for(var i=0;i<parent.childNodes.length;i++){
			parent.childNodes[i].style.display="table-row";
		}
		
	}
	catch(e){
		report("expandListRowMenu: "+e);
	}
}

function collapseListRowMenu(id){
	try{
		var parent = $('list_row_menu_' + id);
		parent.style.border = "none";
		parent.style.backgroundColor = "transparent";
		
		for(var i=0;i<parent.childNodes.length;i++){
			parent.childNodes[i].style.display="none";
		}
		parent.childNodes[0].style.display="table-row";
	}
	catch(e){
		report("colapseListRowMenu: "+e);
	}
}

/*-- Lists -------------------------------------------------------*/

function refreshPropertyRows(){
	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(){
	var url = "action.php?method=directory_mini_list"+
			  "&ids="+document.forms['current_form'].elements['people_selected'].value;
	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;
	//report(transport.responseText);
	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);
	}
}
