var ajx_object    = new Array(10);
var ajx_target    = new Array(10);
var ajx_call_back = new Array(10);
var ajx_in_use    = new Array(10);
var ajx_scrollHeight = 0;
var ajx_status_bar = null;
var ajx_post = [ ajx_post_process_0, ajx_post_process_1, ajx_post_process_2, ajx_post_process_3, ajx_post_process_4, ajx_post_process_5, ajx_post_process_6, ajx_post_process_7, ajx_post_process_8, ajx_post_process_9 ];

function ajx_init () {
    for (i=0; i<10; i++)
        ajx_in_use[i] = false;
}

function ajx_process (url, target, call_back, method, params, id) {
    if (!id) {
        for (i=0;i<10;i++) {
            if (!ajx_in_use[i]) {
                ajx_in_use[i] = true;
                id = i;
                break;
            }
        }
    }
    ajx_object[id]=ajx_GetXmlHttpObject();
    if (ajx_object[id]==null) {
        alert ("Browser does not support HTTP Request")
        return;
    }
    ajx_status (id+': '+target+": "+url+": "+call_back);
    url=url+"&sid="+Math.random();
    ajx_target[id]    = null;
    ajx_call_back[id] = null;

    method = method ? method : "GET";
    ajx_object[id].open(method,url,true);
    if (method=='POST') {
        //Send the proper header information along with POST request
        ajx_object[id].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajx_object[id].setRequestHeader("Content-length", params.length);
        ajx_object[id].setRequestHeader("Connection", "close");
    }
    ajx_object[id].send(params);
    if (target || call_back) {
        ajx_target[id] = document.getElementById(target);
        //ajx_scrollHeight = ajx_target.scrollHeight;
        ajx_call_back[id] = call_back;
        ajx_object[id].onreadystatechange=ajx_post[id];
    } else {
        ajx_in_use[id] = false;
    }

}

function ajx_post_process(id) {
    if ((ajx_object[id].readyState==4 || ajx_object[id].readyState=="complete")) {
        if (ajx_target[id]) ajx_target[id].innerHTML=ajx_object[id].responseText;
        if (ajx_call_back[id]) eval(ajx_call_back[id]);
    }
    ajx_in_use[id] = false;
}

// got to be a cleaner way to do this, but this works for now
function ajx_post_process_0() { ajx_post_process(0); }
function ajx_post_process_1() { ajx_post_process(1); }
function ajx_post_process_2() { ajx_post_process(2); }
function ajx_post_process_3() { ajx_post_process(3); }
function ajx_post_process_4() { ajx_post_process(4); }
function ajx_post_process_5() { ajx_post_process(5); }
function ajx_post_process_6() { ajx_post_process(6); }
function ajx_post_process_7() { ajx_post_process(7); }
function ajx_post_process_8() { ajx_post_process(8); }
function ajx_post_process_9() { ajx_post_process(9); }

function ajx_GetXmlHttpObject() {
    var xmlHttp=null;
    try  {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    } catch (e) {
        //Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function ajx_status (s) {
    if (obj = document.getElementById("status")) {
        obj.innerHTML = s;
    }
}
var cal_hour_height = 60;
// following functions update div "info" with coordinates of dragged object
function cal_drag_begin (element) {
}

function cal_dragging (element) {
    cal_drag_status(element.style.top);
    cal_update_bar(element);
}

function cal_drag_end (element) {
    cal_drag_status("drag ended");
    element.style.top = (Math.floor(parseInt(element.style.top)/(cal_hour_height/4))*(cal_hour_height/4)) + "px";
    cal_change_start(cal_event_id(element), cal_obj_to_hour(element), cal_obj_to_min(element));
}

function cal_drag_status(s) {
    if (document.getElementById('status')) document.getElementById('status').innerHTML = s;
}

function cal_update_bar(element) {
    var bar = document.getElementById(element.id.replace("event_", "event_bar_"));
    bar.innerHTML = cal_pix_to_time(element.style.top);
    var stretch = document.getElementById(element.id.replace("event_", "event_stretch_"));
    stretch.innerHTML = cal_pix_to_time(parseInt(element.style.top)+parseInt(element.style.height));
}

function cal_stretch_begin (element) {
}

function cal_stretching (element, h) {
    cal_update_stretch(element);
}

function cal_stretch_end (element) {
    cal_drag_status("stretch ended");
    pix = parseInt(element.style.top) + parseInt(element.style.height);
    cal_change_end (cal_event_id(element), cal_pix_to_hour(pix), cal_pix_to_min(pix));
}

function cal_update_stretch(element) {
    var stretch = document.getElementById(element.id.replace("event_", "event_stretch_"));
    stretch.innerHTML = cal_pix_to_time(parseInt(element.style.top)+parseInt(element.style.height));
}

function cal_event_id (element) {
    return element.id.substr(6);
}

function cal_pix_to_time (pix) {
    var quart_height = cal_hour_height/4;
    var ampm = "AM";
    pix = parseInt(pix);
    var hour = Math.floor (pix/cal_hour_height);
    var min = Math.floor ((pix - (hour * cal_hour_height))/quart_height)*15;
    min = min==0 ? "00" : min;
    if (hour>=12) {
        hour = hour>12 ? hour-12 : hour;
        ampm = "PM";
    }
    return hour+":"+min+" "+ampm;
}

function cal_obj_to_hour (obj) {
    pix = parseInt(obj.style.top);
    return Math.floor (pix/cal_hour_height);
}

function cal_obj_to_min (obj) {
    var quart_height = cal_hour_height/4;
    pix = parseInt(obj.style.top);
    var hour = Math.floor (pix/cal_hour_height);
    return Math.floor ((pix - (hour * cal_hour_height))/quart_height)*15;
}

function cal_obj_to_end_hour (obj) {
    pix = parseInt(obj.style.top) + parseInt(obj.style.height);
    return Math.floor (pix/cal_hour_height);
}

function cal_obj_to_end_min (obj) {
    var quart_height = cal_hour_height/4;
    pix = parseInt(obj.style.top) + parseInt(obj.style.height);
    var hour = Math.floor (pix/cal_hour_height);
    return Math.floor ((pix - (hour * cal_hour_height))/quart_height)*15;
}

function cal_pix_to_hour (pix) {
    return Math.floor (pix/cal_hour_height);
}

function cal_pix_to_min (pix) {
    var quart_height = cal_hour_height/4;
    var hour = Math.floor (pix/cal_hour_height);
    return Math.floor ((pix - (hour * cal_hour_height))/quart_height)*15;
}

function cal_round_top (element) {
    alert (element.id);
    return "";
    return floor(parseInt(element.style.top)/(cal_hour_height/4));
}

var cal_saved_scroll=0;
function cal_change_month(stamp,id) {
    var url="ajax/calendar.php?cal_change_month=true&stamp="+stamp+"&id="+id
    ajx_process (url, "cal_sidebar_"+id, null);
}

function cal_change_day (stamp, view) {
    new_date = new Date (stamp*1000);
    var disp = document.getElementById("cal_header_left");
    if (disp) {
        disp.innerHTML = (cal_month(new_date.getMonth())+" "+new_date.getDate()+", "+new_date.getFullYear());
    }
    if (obj=document.getElementById(cal_cur_day)) obj.style.background = '#fff';
    if (obj=document.getElementById(stamp)) obj.style.background = '#ccc';
    cal_cur_day = stamp;
    var url="ajax/calendar.php?action=cal_change_day&stamp="+stamp
    cal_save_scroll();
    ajx_process (url, "cal_disp_box", "cal_event_changed()");
}

function cal_change_start(id, hour, min) {
    var url="ajax/calendar.php?action=cal_change_start&event_id="+id+"&hour="+hour+"&min="+min
    cal_save_scroll ();
    ajx_process (url, "cal_disp_box", "cal_event_changed()");
}

function cal_change_end (id, hour, min) {
    var url="ajax/calendar.php?action=cal_change_end&event_id="+id+"&hour="+hour+"&min="+min
    cal_save_scroll ();
    ajx_process (url, "cal_disp_box", "cal_event_changed()");
}

function cal_event_changed() {
    cal_set_scroll ();
    for (i=0; i<7; i++) {
        if (document.getElementById("cal_day_script_"+i)) eval(document.getElementById("cal_day_script_"+i).innerHTML);
    }
}

function cal_edit(event_id,hour,minute,cal_index) {
    cal_save_scroll ();
    var url="index.php?subform=cal_edit&action=edit_event&event_id="+event_id+"&hour="+hour+"&minute="+minute+"&cal_index="+cal_index;
    if (cal_saved_scroll) url = url+"&cal_saved_scroll="+cal_saved_scroll;
    fun_goto(url);
}

function cal_check_group(checkbox,group_id) {
    var url="ajax/calendar.php?action=cal_check_group&group_id="+group_id
    cal_save_scroll ();
    ajx_process (url, "cal_disp_box", "cal_event_changed()");
}

function cal_save_scroll () {
    if (document.getElementById("cal_scroll_box")) cal_saved_scroll = document.getElementById("cal_scroll_box").scrollTop;
}

function cal_set_scroll () {
    if (document.getElementById("cal_scroll_box")) document.getElementById("cal_scroll_box").scrollTop = cal_saved_scroll;
}

function cal_month (num, short) {
    if (short) {
        var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    } else {
        var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    }
    return months[num];
}

function cal_assign_to_group (contact_id, group_id, assign) {
    var url="ajax/calendar.php?action=cal_assign_to_group&ccontact_id="+contact_id+"&group_id="+group_id+"&value="+assign
    ajx_process (url, null, null);
}

function cal_date_class(obj) {
    var date = new Date();
    var obj_date = get_object(obj+"_date");
    var obj_time = get_object(obj+"_time");
    var s = String(obj+"_time").replace('end_','start_');
    var obj_start_time = get_object (s);
    var s = String(obj+"_time").replace('start_','end_');
    var obj_end_time = get_object (s);
    var s = String(obj+"_date").replace('start_','end_');
    var obj_end_date = get_object (s);
    var delta_hour = 0;
    var delta_min = 0;
    obj_date.onkeypress=key_date;
    obj_date.onblur=set_date;
    obj_time.onkeypress=key_hour;
    obj_time.onblur=set_time;
    obj_time.onfocus=set_delta;
    set_date();
    set_time();

    this.date_add = date_add;
    function date_add(n, s, date) {
        switch(s) {
            case "d":
                return new Date(date.getUTCFullYear(), date.getMonth(), date.getDate()+n, date.getHours(), date.getMinutes());
            case "m":
                return new Date(date.getUTCFullYear(), date.getMonth()+n, date.getDate(), date.getHours(), date.getMinutes());
            case "y":
                return new Date(date.getUTCFullYear()+n, date.getMonth(), date.getDate(), date.getHours(), date.getMinutes());
        }
    }

    this.set_delta = set_delta;
    function set_delta () {
        if (obj_end_time) {
            vs = parse_time (obj_time.value);
            ve = parse_time (obj_end_time.value);
            delta_hour = ve[0] - vs[0];
            delta_min = ve[1] - vs[1];
        }
    }

    this.set_time = set_time;
    function set_time(t) {
        // determine format/positioning
        t = t == null ? obj_time.value : t;
        t = obj_time.value;
        v = parse_time (t);
        h = v[0]; m = v[1];
        if (obj_time.name.match(/end_/i)) { // if we're working with an end time, make sure that it's after the start time
            v = parse_time (obj_start_time.value);
            sh = v[0]; sm = v[1];
            h = Math.max(h, sh);
            if (h == sh) {
                m = Math.max (m, sm+10);
                if (m >= 60) {
                    h++;
                    m -= 60;
                }
            }
        } else if (obj_time.name.match(/start_/) && delta_min != 0) { // if we're working with a start time, make sure end time is after start time
            eh = Math.min(h+delta_hour, 23); // end hour can't be less than start hour
            em = m+delta_min;
            if (em >= 60) {
                if (eh < 23) {
                    eh++;
                    em -= 60;
                } else {
                    em = 59;
                }
            }
            date = new Date(year(),month(),day(), eh, em);
            obj_end_time.value = show_time();
        }
        date = new Date(year(),month(),day(), h, m);
        obj_time.value = show_time();
        return date;
    }

    this.set_date = set_date;
    function set_date(d, format) {
        // determine format/positioning
        //d = d == null ? obj_date.value : d;
        d = obj_date.value;
        format = format == null ? "mdy" : format;
        if (format=="mdy") {        mp = 0; dp = 1; yp = 2;
        } else if (format=="dmy") { mp = 1; dp = 0; yp = 2;
        } else if (format=="ymd") { mp = 1; dp = 2; yp = 0; }

        s = new String (d);

        // determine delimiter
        if (s.search(".")>0) delim = ".";
        else if(s.search("\/")>0) delim = "/";
        else if(s.search("-")>0) delim = "-";
        else delim = '/';
        if (delim != null) {
            try {
                var p = s.split(delim);
                m = parseFloat(p[mp],10);
                d = parseFloat(p[dp],10);
                y = parseFloat(p[yp],10);
                //alert (m+' ('+s+')'+'/'+d+'/'+y+':'+delim);
                if (y && m && d) {
                    y = String(y).length == 1 ? "200"+String(y) : y;
                    y = String(y).length == 2 ? "20"+String(y) : y;
                    date = new Date(y, m-1, d, date.getHours(), date.getMinutes());
                }
            } catch(e) {}
        }
        obj_date.value = show_date();
        if (obj_end_date) {
            obj_end_date.value = show_date();
        }
        return date;
    }

    this.get    = get;    function get() { return date;  }
    this.month  = month;  function month() { return date.getMonth()+1; }
    this.day    = day;    function day() { return date.getDate(); }
    this.year   = year;   function year() { return date.getUTCFullYear(); }
    this.inc    = inc;    function inc() { date = date_add(1, "d", date); }
    this.hour   = hour;   function hour () { return date.getHours(); }
    this.minute = minute; function minute () { return date.getMinutes(); }

    this.show_time = show_time;
    function show_time () {
        var m = minute();
        var h = hour();
        var ampm = h >= 12 ? " PM" : " AM";
        h = h > 12 ? (h-12) : h;
        h = h < 10 ? "0"+h : h;
        m = m < 10 ? "0"+m : m;
        return h+":"+m+ampm;
    }

    this.show_date = show_date;
    function show_date() {
        m = month();
        d = day();
        y = year();
        m = m < 10 ? "0"+m : m;
        d = d < 10 ? "0"+d : d;
        return m+"/"+d+"/"+y;
    }

    this.key_id = null;
    this.key_date = key_date;
    function key_date() {
        key_id = event ? event.keyCode : e.keyCode;
        if (is_num() || is_slash()) return key_id;
        return false;
    }
    this.key_hour = key_hour;
    function key_hour() {
        key_id = event ? event.keyCode : e.keyCode;
        if (is_num() || is_colon() || is_ampm()) return key_id;
        return false;
    }
    function is_num()   { return (key_id >= 48 && key_id <= 57); }
    function is_ampm()  { return (key_id == 65 || key_id == 97 || key_id == 80|| key_id == 112); }
    function is_slash() { return key_id == 47; }
    function is_colon() { return key_id == 58; }
    function to_char()  { return String.fromCharCode(key_id) }
    function parse_time (t) {
        var values = t.split(":");
        if (values[1]) {
            var h = (parseFloat(values[0]) == "NaN") ? 0 : parseFloat(values[0]);
            var m = (parseFloat(values[1]) == "NaN") ? 0 : parseFloat(values[1]);
        } else {
            var s = String((parseFloat(t) == "NaN") ? "0000" : parseFloat(t));
            if (s.length == 4) { h = s.substring(0,2); m = s.substring(2,4); }
            else if (s.length == 3) { h = s.substring(0,1); m = s.substring(1,3); }
            else if (s.length == 2) { h = s.substring(0,2); m = 0; }
            else if (s.length == 1) { h = s.substring(0,1); m = 0; }
            else { h = 0; m = 0; }
        }
        var pm = t.toLowerCase().indexOf("p") != -1;
        h = Math.max(Math.min(h,23),0);
        h = h < 12 && pm ? h+12 : h;
        m = Math.max(Math.min(m,59),0);
        return [h,m];
    }
}

function cal_select_date (val, old_val, fld) {
    if (obj=document.getElementById('cal_'+fld+'_month_box')) {
        obj.style.display='none';
    }
    if (val == old_val) return;
    if (obj=document.getElementById('cal_'+fld+'_date')) {
        if (!frm_is_date(val)) {
            alert ("You've entered an invalid date! Please enter dates in mm/dd/yyyy format.");
            obj.value = old_val;
            return;
        }
        obj.value = val;
        eval("cal_"+fld+"_current='"+val+"'");
        var url="ajax/calendar.php?action=cal_select_date&date="+val+'&selector='+fld;
        ajx_process (url, null, null);
        eval ("cal_"+fld+"_process('"+val+"')");
    }
}

function cal_select_month (stamp, nm) { // called by generic calendar selector
    var url="ajax/calendar.php?action=cal_select_month&stamp="+stamp+'&selector='+nm;
    ajx_process (url, 'cal_'+nm+'_month_box', null);
}

function cal_print(disp) {
    var d = new Date();
    var ts = parseInt(d.getTime());
    ts = parseInt(ts / 1000);
    if (disp == 'week') {
        obj=document.getElementById('cal_printable_week');
    } else {
        obj=document.getElementById('cal_printable_day');
    }
    if (obj) {
        if (disp == 'week') {
            print_window=window.open ("","cal_print_"+ts,"status=1,width=1200,height=700,scrollbars=2");
        } else {
            print_window=window.open ("","cal_print_"+ts,"status=1,width=700,height=1100,scrollbars=2");
        }
        // print_window.document.write("<link href=\"default.css\" rel=\"stylesheet\" type=\"text/css\" />\n");
        print_window.document.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">');
        print_window.document.write('<html>');
        print_window.document.write('<head>');
        print_window.document.write('</head>');
        print_window.document.write('<body>');
        print_window.document.write('<div style="align: right; width: 100%; text-decoration: none;"><a href="javascript:window.print();">Print this page</a></div><br />');
        print_window.document.write(obj.innerHTML);
        // print_window.document.write("<br /><br /><center><small>Copyright 2009, relate to autism, inc</small></center>");
        print_window.document.write('</body>');
        print_window.document.write('</html>');
    }
}
function con_change_query(id,alt_id) {
    //frm = document.getElementById("con_query_"+id);
    frm = get_object("con_query_"+id);
    var url="ajax/people.php?action=retrieve_search&instance="+id;
    url = url + "&first_name="+frm.first_name.value
    url = url + "&last_name="+frm.last_name.value
    url = url + "&email1="+frm.email1.value
    url = url + "&city1="+frm.city1.value
    url = url + "&country1="+frm.country1.value
    url = url + "&group_id="+frm.group_id.value
    var call_back = null;
    if (alt_id) call_back = "con_refresh('"+alt_id+"')";
    // ajx_process (url, "con_contact_list_"+id, call_back);
    ajx_process (url, "con_contact_list_"+id, null);
    return false;
}

function con_delete_contact (contact_id) {
    if (confirm("Really delete this contact and all associated records?")) {
        con_goto ("index.php?subform=contact_delete&action=delete_contact&contact_id="+contact_id);
    }
}

function con_delete_group (id,group_id) {
    if (confirm("Really delete this group?")) {
        var url="ajax/people.php?action=delete_group&instance="+id+"&group_id="+group_id;
        ajx_process (url, "con_contact_list_"+id, null);
    }
}

function con_fields_to_query(id,alt_id) {
    frm = document.getElementById("con_query_"+id);
    frm.group_id.value = "";
    con_change_query(id,alt_id);
}

function con_group_to_query(id,group_id,alt_id) {
    frm = document.getElementById("con_query_"+id);
    if (frm) {
        con_clear_fields(frm);
        frm.group_id.value = group_id;
        con_change_query(id,alt_id);
    }
}

function con_change_group(id,group_id) {
    if (obj=document.getElementById("con_contact_list_"+id)) obj.innerHTML="<div style='text-align: center; font-size: 1.3em;'>Please wait<br />If this page doesn't refresh in a few moments, please click <a href='index.php'>here</a>.</div>";
    var url="ajax/people.php?action=change_group&instance="+id+"&group_id="+group_id;
    ajx_process (url, "con_contact_list_"+id, null);
}

function con_refresh(id) {
    var url="ajax/people.php?action=refresh&instance="+id;
    ajx_process (url, "con_contact_list_"+id, null);
}

function con_refresh_alias() {
    var url="ajax/people.php?action=refresh_alias";
    ajx_process (url, null, null);
}

function con_clear_fields (frm) {
    frm.first_name.value = '';
    frm.last_name.value = '';
    frm.email1.value = '';
    frm.city1.value = '';
    frm.country1.value = '';
    frm.group_id.value = -1;
}

function con_select_contact(contact_id,target) {
    var url="ajax/people.php?action=select_contact&contact_id="+contact_id;
    ajx_process (url, target, null);
}

function con_show_hide_group_links (id,contact_id) {
    if (obj=document.getElementById("con_group_links_"+id+"_"+contact_id)) {
        obj.style.display = obj.style.display=='none' ? 'block' : 'none';
    }
}

function con_next_batch(id) {
    var url="ajax/people.php?action=retrieve_next&instance="+id;
    ajx_process (url, "con_contact_list_"+id, null);
    return false;
}

function con_prev_batch(id) {
    var url="ajax/people.php?action=retrieve_prev&instance="+id;
    ajx_process (url, "con_contact_list_"+id, null);
    return false;
}

function con_change_batch_size(id, batch_size) {
    if (parseInt(batch_size) == "NaN") {
        batch_size = 10;
    }
    var url="ajax/people.php?action=change_batch_size&instance="+id+"&batch_size="+batch_size;
    ajx_process (url, "con_contact_list_"+id, null);
    return false;
}

function con_group_assign(group_id, contact_id, checked) {
    var url="ajax/people.php?action=group_assign&group_id="+group_id+"&contact_id="+contact_id+"&checked="+checked;
    ajx_process (url, null, null);
}

function con_add_to_group(id, contact_id) {
    var url="ajax/people.php?action=add_to_group&instance="+id+"&contact_id="+contact_id;
    ajx_process (url, "con_contact_list_"+id, null);
}

function con_delete_from_group(id, contact_id) {
    var url="ajax/people.php?action=delete_from_group&instance="+id+"&contact_id="+contact_id;
    ajx_process (url, "con_contact_list_"+id, null);
}

function con_set_role(id, contact_id, role) {
    var url="ajax/people.php?action=set_group_role&instance="+id+"&contact_id="+contact_id+"&role="+role;
    ajx_process (url, null, null);
    return false;
}

function con_set_group_desc(id, group_desc) {
    var url="ajax/people.php?action=set_group_desc&instance="+id+"&group_desc="+group_desc;
    ajx_process (url, null, null);
    return false;
}

function con_get_scroll() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
  //return scrOfY;
}

function con_set_scroll(x, y) {
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    window.pageYOffset = y;
    window.pageXOffset = x;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    document.body.scrollTop = y;
    document.body.scrollLeft = x;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    document.documentElement.scrollTop = y;
    document.documentElement.scrollLeft = x;
  }
}

function con_goto (url) {
    var xy = con_get_scroll();
    window.location=url+"&scroll_y="+xy[1];
    return false;
}

function con_status (s) {
    document.getElementById("status").innerHTML=s;
}


function con_accept_invitation(invitation) {
    var url="ajax/people.php?action=accept_invitation&invitation="+invitation;
    ajx_process (url, "con_invitation", null);
}

function con_decline_invitation(invitation) {
    var url="ajax/people.php?action=decline_invitation&invitation="+invitation;
    ajx_process (url, "con_invitation", null);
}

function con_ignore_invitation(invitation) {
    var url="ajax/people.php?action=ignore_invitation&invitation="+invitation;
    ajx_process (url, "con_invitation", null);
}

function con_cancel_invitation(invitation) {
    if (!confirm("Really cancel this invitation?")) return;
    var url="ajax/people.php?action=cancel_invitation&invitation="+invitation;
    ajx_process (url, "con_invitation_status", null);
}

function con_resend_invitation(invitation) {
    if (!confirm("Really resend this invitation?")) return;
    var url="ajax/people.php?action=resend_invitation&invitation="+invitation;
    ajx_process (url, "con_invitation_status", null);
}

function con_set_photo(photo_id,contact_id) {
    var url="ajax/people.php?action=set_photo&photo_id="+photo_id+"&contact_id="+contact_id;
    ajx_process (url, null, null);
}
/* fun_grab_form (form_name) {
    for(i=0; i<document.form_name.elements.length; i++) {
        document.write("The field name is: " + document.FormName.elements[i].name + " and it’s value is: " + document.FormName.elements[i].value + ".<br />");
    }
} */
function stretch_class (obj,win) {
    // private property.
    var _bar = document.getElementById(obj.replace('_','_stretch_'));
    var _box = document.getElementById(obj);
    var _win = document.getElementById(win);
    var _opacity=null;
    var _filter=null;
    var _visibility=null;
    var _zIndex=0;
    var _winH = 2000;
    var _winW = 2000;
    var _maxY = _winH;
    var _maxX = _winW;
    var _unit = '%';

    _bar.onmousedown=_begin;
    _box.stretch_start = new Function();
    _box.stretch       = new Function();
    _box.stretch_end   = new Function ();
    return _box;

    function set_opacity () {
        _opacity    = _box.opacity;
        _filter     = _box.style.filter;
        _visibility = _box.style.visibility;
        _zIndex     = _box.style.zIndex;
        _box.style.filter     = 'alpha(opacity=100)';
        _box.style.opacity    = 1;
        _box.style.visibility = 'visible';
        _box.style.zIndex     = 100;
    }

    function restore_opacity () {
        _box.style.filter     = _filter;
        _box.style.opacity    = _opacity;
        _box.style.visibility = _visibility;
        _box.style.zIndex     = _zIndex;
    }

    // private method. Begin stretch process.
    function _begin (e) {
        if (_win) {
            _winH = get_style_int(_win, 'height');
            _winW = get_style_int(_win, 'width');
            _maxY = get_style(_win,'overflow')=='auto' ? _win.scrollHeight : _winH;
            _maxX = get_style(_win,'overflow')=='auto' ? _win.scrollWidth : _winW;
        }
        e = e ? e : window.event;
        _box.mouseY = e.clientY;
        set_opacity();
        document.onmousemove = _stretch;
        document.onmouseup   = _end;
        _box.stretch_start(_box);
        return false;
    }

    // private method. stretch (move) element.
    function _stretch (e) {
        e = e ? e : window.event;
        var deltaY = e.clientY - _box.mouseY;
        var newH = Math.max(parseInt(_box.style.height) + deltaY, 30);
        var newT = newH - parseInt(_bar.style.height);
        _box.style.height = newH + (_box.style.height.match(/%/) == "%" ? "%" : "px");
        _bar.style.top    = newT + (_box.style.top.match(/%/) == "%" ? "%" : "px");
        _box.mouseY       = e.clientY;

        if (_win && _win.style.overflow == 'auto') {
            var scroll_rate = 25;
            if (top + newH > (_win.scrollTop + _winH - scroll_rate) && ((_win.scrollTop + _winH + scroll_rate) < _win.scrollHeight)) {
                _win.scrollTop += scroll_rate;
                _box.mouseY -= scroll_rate;
            } else if (top + newH < _win.scrollTop && _win.scrollTop > 0) {
                _win.scrollTop -= scroll_rate;
                _box.mouseY +=scroll_rate;
            }
        }
        _box.stretch(_box);

        return false;
    }

    // private method. Stop stretch process.
    function _end() {
        var y = parseInt(_box.style.top);
        restore_opacity();
        document.onmousemove = null;
        document.onmouseup = null;
        _box.stretch_end(_box);
    }
}

function get_style_int (obj,par) {
     if (obj.currentStyle) return parseInt(obj.currentStyle[par.replace(/-/g,'')]);
     return parseInt(document.defaultView.getComputedStyle(obj,null).getPropertyValue(par.toLowerCase()));
}

function get_style (obj,par) {
     if (obj.currentStyle) return obj.currentStyle[par.replace(/-/g,'')];
     return document.defaultView.getComputedStyle(obj,null).getPropertyValue(par.toLowerCase());
}

function drag_class (obj, win, style) {
    // private property
    var _bar =  document.getElementById(obj.replace('_','_bar_')); // attach the box
    var _box =  document.getElementById(obj);
    var _win =  document.getElementById(win);
    var _winH = 2000;
    var _winW = 2000;
    var _maxY = _winH;
    var _maxX = _winW;
    var _limitLeft=0;
    var _limitRight=0;
    var _limitTop=0;
    var _limitBottom=0;
    var _opacity=null;
    var _filter=null;
    var _visibility=null;
    var _style= (style ? style : 'vert');
    var _target=null;
    var _zIndex=0;
    _bar.onmousedown=_begin;
    _box.drag_start = new Function();
    _box.drag       = new Function();
    _box.drag_end   = new Function ();
    return _box;

    function set_opacity () {
        _opacity = _box.opacity;
        _filter = _box.style.filter;
        _visibility = _box.style.visibility;
        _zIndex = _box.style.zIndex;
        _box.style.filter='alpha(opacity=100)';
        _box.style.opacity=1;
        _box.style.visibility = 'visible';
        _box.style.zIndex=100;
    }

    function restore_opacity () {
        _box.style.filter=_filter;
        _box.style.opacity=_opacity;
        _box.style.visibility = _visibility;
        _box.style.zIndex=_zIndex;
    }

    // private method. Begin drag process.
    function _begin (e) {
        if (_win) {
            _winH = get_style_int(_win, 'height');
            _winW = get_style_int(_win, 'width');
            _maxY = get_style(_win,'overflow')=='auto' ? _win.scrollHeight : _winH;
            _maxX = get_style(_win,'overflow')=='auto' ? _win.scrollWidth : _winW;
        }
        if (isNaN(parseInt(_box.style.left)))   { _box.style.left   = '0px'; }
        if (isNaN(parseInt(_box.style.top)))    { _box.style.top    = '0px'; }
        if (isNaN(parseInt(_box.style.height))) { _box.style.height = '400px'; }

        var x = parseInt(_box.style.left);
        var y = parseInt(_box.style.top);
        if (_style=='vert') {
            _limitLeft = x; _limitRight = x;     _limitTop = 0; _limitBottom = _maxY;
            //alert(_limitLeft+", "+_limitTop+", "+_limitRight+", "+_limitBottom);
        } else if (_style=='horz') {
            _limitLeft = 0; _limitRight = _maxX; _limitTop = y; _limitBottom = y;
        } else {
            _limitLeft = 0; _limitRight = _maxX; _limitTop = 0; _limitBottom = _maxY
        }

        e = e ? e : window.event;
        _box.mouseX = e.clientX;
        _box.mouseY = e.clientY;
        set_opacity();

        _box.drag_start(_box);
        document.onmousemove = _drag;
        document.onmouseup = _end;
        return false;
    }


    // private method. Drag (move) element.
    function _drag(e) {
        var x = parseInt(_box.style.left);
        var y = parseInt(_box.style.top);

        e = e ? e : window.event;
        // set new coordinates within limits
        var newY = Math.max(Math.min(y + (e.clientY - _box.mouseY), _limitBottom), _limitTop);
        var newX = Math.max(Math.min(x + (e.clientX - _box.mouseX),_limitRight),_limitLeft);
        _box.style.top = newY + (_box.style.top.match(/%/)=='%' ? "%" : "px");
        _box.style.left = newX + (_box.style.left.match(/%/)=='%' ? "%" : "px");
        // capture new mouse position
        _box.mouseX = e.clientX;
        _box.mouseY = e.clientY;

        if (_win && _win.style.overflow == 'auto') {
            var scroll_rate = 25;
            if (newY > (_win.scrollTop + parseInt(_win.style.height) - scroll_rate) && ((_win.scrollTop + parseInt(_win.style.height) + scroll_rate) < _win.scrollHeight)) {
                _win.scrollTop += scroll_rate;
                _box.mouseY -= scroll_rate;
            } else if (newY < _win.scrollTop && _win.scrollTop > 0) {
                _win.scrollTop -= scroll_rate;
                _box.mouseY +=scroll_rate;
            }
        }
        _box.drag(_box);
        return false;
    }

    // private method. Stop drag process.
    function _end () {
        var x = parseInt(_box.style.left);
        var y = parseInt(_box.style.top);
        restore_opacity ();
        document.onmousemove = null;
        document.onmouseup = null;
        _box.drag_end(_box);
        return false;
    }
}
var DragHandler = {
    // private property.
    _limitLeft: 0,
    _limitRight: 0,
    _limitTop: 0,
    _limitBottom: 0,
    _oElem : null,

    // public method. Attach drag handler to an element.
    attach : function(o) {
        o.onmousedown = DragHandler._dragBegin;

        // callbacks
        o.dragBegin = new Function();
        o.drag = new Function();
        o.dragEnd = new Function();

        return o;
    },


    // private method. Begin drag process.
    _dragBegin : function(e) {
        var o = DragHandler._oElem = this;

        if (isNaN(parseInt(o.style.left))) { o.style.left = '0px'; }
        if (isNaN(parseInt(o.style.top))) { o.style.top = '0px'; }

        // var x = parseInt(o.style.left);
        var x = 0;
        var y = parseInt(o.style.top);

        e = e ? e : window.event;
        o.mouseX = e.clientX;
        o.mouseY = e.clientY;

        o.dragBegin(o, x, y);
        document.onmousemove = DragHandler._drag;
        document.onmouseup = DragHandler._dragEnd;
        return false;
    },


    // private method. Drag (move) element.
    _drag : function(e) {
        var o = DragHandler._oElem;

        var x = parseInt(o.style.left);
        var y = parseInt(o.style.top);

        e = e ? e : window.event;
        //o.style.left = x + (e.clientX - o.mouseX) + 'px';
        o.style.left = DragHandler._limitLeft
        o.style.top = y + (e.clientY - o.mouseY) + 'px';

        o.mouseX = e.clientX;
        o.mouseY = e.clientY;

        o.drag(o, x, y, e.clientX, e.clientY, o.mouseX, o.mouseY);

        return false;
    },

    // private method. Stop drag process.
    _dragEnd : function() {
        var oElem = DragHandler._oElem;

        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);

        oElem.dragEnd(oElem, x, y);

        document.onmousemove = null;
        document.onmouseup = null;
        DragHandler._oElem = null;
    }
}


    // following functions update div "info" with coordinates of dragged object
    function begin (element, x, y) {
        var s = '#' + element.id + ' (begin drag)' + ' x:' + x + ', y:' + y;
        updateInfo(s);
    }

    function drag (element, x, y, cx, cy, mx, my) {
        var s = '#' + element.id + ' (dragging)' + ' x:' + x + ', y:' + y + ', cx:' + cx + ', cy:' + cy + ', mx:' + mx + ', my:' + my;
        updateInfo(s);
    }

    function end (element, x, y) {
        var s = '#' + element.id + ' (end drag)' + ' x:' + x + ', y:' + y;
        updateInfo(s);
    }

    function updateInfo(s) {
        document.getElementById('status_bar').innerHTML = s;
    }
var dyna_form_id = 0;

function dyna_form (prnt_id, frm_name) {
    this.prnt_id = prnt_id;
    this.prnt = document.getElementById (prnt_id);
    this.frm_name = frm_name+'_frm';

	this.modal 	= document.createElement('div');
	_set_style (this.modal, 'height: 100%; width: 100%; display: none; position: absolute; top: 0px; left: 0px; backgroundColor: #000; filter: alpha(opacity=30); opacity: .3;');
	this.prnt.appendChild (this.modal);
    this.div 	= document.createElement('div');
    _set_style (this.div, 'borderWidth: 3px; borderStyle: solid; borderColor: #000; width: 820px; display: none; position: absolute; zIndex: 1000; background: #fff');
    this.prnt.appendChild(this.div);

    this.dragger = document.createElement('div');
    _set_style (this.dragger, 'width: 100%; height: 20px; display: block; position: relative; backgroundColor: #154890; textAlign: center; color: #fff;');
    this.div.appendChild (this.dragger);

    this.inner = document.createElement('div');
    _set_style (this.inner, 'display: block; position: relative; width: 100%; padding: 10px;');
    this.div.appendChild (this.inner);

    this.elements = new Array();
    var _found_value = '';
    var _value_found = false;

    function _trim (s) {
        return s.replace(/^\s+|\s+$/g, '') ;
    }

    function _set_style (element, cssString) {
        var styles = cssString.split (';');
        for (var i=0; i<styles.length; i++) {
            var style = styles[i].split(':');
            if (style.length == 2) {
                var s = 'element.style.'+_trim(style[0])+'="'+_trim(style[1])+'";'
                try {
                    eval(s);
                }
                catch (e) {
                  alert (e+':'+s);
                }
            }
        }
    }

    this.get_val = get_val;
    function get_val (element) {
        for (var i = 0; i < this.elements.length; i++) {
            if (this.elements[i].name == element) {
                return this.elements[i].value;
            }
        }
    }

    this.value_by_name = function (nm) {
        var obj = _obj_by_name (nm, this.div);
        if (obj) return obj.value;
        return '';
    }

    this.obj_by_name = function (nm) {
        return _obj_by_name (nm, this.div);
    }

    function _obj_by_name (nm, div) {
        var rval = null;
        if (div.childNodes) {
            for (var i=0; i<div.childNodes.length; i++) {
                if (div.childNodes[i].name == nm || div.childNodes[i].id == nm) {
                    rval = div.childNodes[i];
                } else {
                    rval = _obj_by_name (nm, div.childNodes[i]);
                }
                if (rval) return rval;
            }
        }
        return rval;
    }

    this.set_val = _set_val;
    function _set_val (element, val) {
        for (var i = 0; i < this.elements.length; i++) {
            if (this.elements[i].name == element) {
                this.elements[i].value = val;
                return;
            }
        }
    }

    this.get_obj = _get_obj
    function _get_obj (nm) {
        return _obj_by_name (nm, this.div);
    }

    this.is_checked = function (nm) {
        var obj;
        if (obj = this.get_obj(nm)) return obj.checked;
        return false;
    }

    this.set_action = _set_action;
    function _set_action (element, event, action) {
        for (var i = 0; i < this.elements.length; i++) {
            if (this.elements[i].name == element) {
                switch (event) {
                    case 'onclick':
                        this.elements[i].onclick = action;
                        break;
                    case 'onfocus':
                        this.elements[i].onfocus = action;
                        break;
                    case 'onblur':
                        this.elements[i].onblur = action;
                        break;
                    case 'onchange':
                        this.elements[i].onchange = action;
                        break;
                    default:
                }
                return;
            }
        }
    }

    this.add_form = add_form;
    function add_form () {
        this.frm = document.createElement('form');
        this.frm.setAttribute('id', this.frm_name);
        this.frm.setAttribute('name', this.frm_name);
        this.frm.action = "";
        this.frm.method = "get";

        this.tbl      = document.createElement("table");
        this.tbl_body = document.createElement("tbody");
        // put the <tbody> in the <table>
        this.tbl.appendChild(this.tbl_body);
        this.frm.appendChild(this.tbl);
        this.inner.appendChild(this.frm);
    }

    this.clear = clear;
    function clear () {
    	if (this.div) {
    		this.remove_children (this.div);
	        this.prnt.removeChild(this.div);
		}
    }

    this.add_text_input = add_text_input;
    function add_text_input (nm, lbl, val) {
        // creating all cells
        var element = document.createElement("input");
        element.setAttribute('name', nm);
        element.setAttribute('id', this.frm_name+'_'+nm);
        element.setAttribute('type', 'text');
        element.setAttribute('size', 40);
        element.setAttribute('maxlength', 255);
        element.setAttribute('value', val ? val : "");
        element.style.width = '400px';
        element.style.borderWidth = '1px';
        element.style.borderColor = '#ccc';
        element.style.borderStyle = 'solid';
        this.elements[this.elements.length] = element;
        this.show_element (element, lbl);
        return (element);
    }


    var _hours = ('12,01,02,03,04,05,06,07,08,09,10,11,12,01,02,03,04,05,06,07,08,09,10,11').split(',');
    var _am_pm = ('am,am,am,am,am,am,am,am,am,am,am,am,pm,pm,pm,pm,pm,pm,pm,pm,pm,pm,pm,pm').split(',');
    var _minutes = ('00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,55,52,53,54,55,56,57,58,59').split(',');
    var _months = ('Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dece').split(',');
    var _days = ('Sun,Mon,Tue,Wed,Thu,Fri,Sat').split(',');

    this.date_element = function (nm, ts, hidden) {
        // creating all cells
        var element = document.createElement("input");
        element.setAttribute('name', nm);
        element.setAttribute('id', this.frm_name+'_'+nm);
        if (hidden) {
            element.setAttribute('type', 'hidden');
        } else {
            element.setAttribute('type', 'text');
            element.setAttribute('size', 20);
            element.setAttribute('maxlength', 255);
        }

        var val = "";
        if (parseInt(ts) != 'NaN' && parseInt(ts) > 0) {
            var d = new Date(ts);
            val = (_minutes[parseInt(d.getMonth())+1]) + "/" + _minutes[d.getDate()] + "/" +d.getFullYear();
        }
        element.setAttribute('value', val);
        element.style.width = '100px';
        element.style.borderWidth = '1px';
        element.onfocus = _focus_date;
        element.onblur  = _blur_date;
        return element;
    }

    this.time_element = function (nm, val) {
        var element = document.createElement("input");
        element.setAttribute('name', nm);
        element.setAttribute('id', this.frm_name+'_'+nm);
        element.setAttribute('type', 'text');
        element.setAttribute('size', 10);
        element.setAttribute('maxlength', 255);
        element.onfocus = _focus_time;
        element.onblur  = _blur_time;

        var disp = "";
        if (val) {
            var d = new Date(val);
            disp = _hours[d.getHours()]+":"+_minutes[d.getMinutes()]+' '+_am_pm[d.getHours()];
        }
        element.setAttribute('value', disp);
        element.style.width = '80px';
        element.style.borderWidth = '1px';
        element.style.textAlign = 'right';
        return element;
    }

    this.add_date_time = add_date_time;
    function add_date_time (nm, lbl, start_ts, end_ts) {
        // creating all cells
        var val;
        var prnt = document.createElement ("div");
        prnt.style.display='block';
        prnt.style.position='relative';
        prnt.style.margin='0pt';
        prnt.style.padding='0pt';
        prnt.id = nm+"_"+new Date().getTime();

        var start_date = this.date_element(nm+"_start_date", start_ts);
        this.elements[this.elements.length] = start_date;
        prnt.appendChild(start_date);
        prnt.appendChild (document.createTextNode ("  "));

        var start_time = this.time_element(nm+"_start_time", start_ts);
        this.elements[this.elements.length] = start_time;
        prnt.appendChild(start_time);

        var end_date = this.date_element(nm+"_end_date", end_ts, true);
        this.elements[this.elements.length] = end_date;
        prnt.appendChild(end_date);

        var end_time = this.time_element(nm+"_end_time", end_ts);
        this.elements[this.elements.length] = end_time;
        prnt.appendChild (document.createTextNode (" to "));
        prnt.appendChild(end_time);


        start_time.end_time = end_time;
        start_time.start_date = start_date;
        end_time.start_time = start_time;
        end_date.start_date = start_date;

        var row = document.createElement("tr");
        var lbl = document.createTextNode (lbl);
        var lbl_cell = document.createElement ("td");
        lbl_cell.appendChild(lbl);
        row.appendChild (lbl_cell);

        var element_cell = document.createElement ("td");
        element_cell.appendChild(prnt);
        row.appendChild (element_cell);
        this.tbl_body.appendChild (row);
        return prnt;
    }

    function _target (e) {
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        if (targ.nodeType == 3) targ = targ.parentNode;
        return targ;
    }

    var _saved_date_val = "";
    var _saved_date_obj = null;
    function _focus_date (e) {
        _saved_date_obj = _target(e);
        _saved_date_val = _saved_date_obj.value;
    }

    this.blur_date = _blur_date;
    function _blur_date (e) {
        if (!_saved_date_obj) return;
        _saved_date_obj.value = _process_date (_saved_date_obj.value);
        _saved_date_val = "";
        _saved_date_obj = null;
    }

    function _sync_times (d, t0, t1) {
    }

    var _saved_time_val = "";
    var _saved_time_obj = null;
    function _focus_time (e) {
        _saved_time_obj = _target(e);
        _saved_time_val = _saved_time_obj.value;
    }

    this.blur_time = _blur_time;
    function _blur_time (e) {
        if (!_saved_time_obj) return;
        var tgt = _saved_time_obj;
        var start_time;
        var end_time;
        var start_date;

        tgt.value = _process_time (tgt.value);
        if (tgt.start_time) {
            start_time = tgt.start_time;
            end_time   = tgt;
        } else if (tgt.end_time) {
            start_time = tgt;
            end_time   = tgt.end_time;
        }

        if (start_time && end_time) {
            start_date = start_time.start_date;
            var start_ts = new Date(start_date.value + " " +start_time.value).getTime();
            var end_ts   = new Date(start_date.value + " " +end_time.value).getTime();
            if (end_ts <= start_ts) {
                end_ts = start_ts + (15*60*1000);
                var end_date = new Date(end_ts);
                end_time.value = _hours[parseInt(end_date.getHours())]+":"+_minutes[parseInt(end_date.getMinutes())]+" "+_am_pm[parseInt(end_date.getHours())];
            }
        }
        _saved_time_val = "";
        _saved_time_obj = null;
    }

    function _to_int (t) {
        if (t.length == 2 && t.substring(0,1) == '0') {
            return parseInt (t.substring(1,2));
        } else {
            return parseInt (t);
        }
    }

    function _get_time (t) {
        var hr;
        var mn;

        var tm = t.replace(/[^0-9]/g,'');
        switch (tm.length) {
            case 1:
            case 2:
                hr = _to_int(tm);
                mn = parseInt(0);
                break;

            case 3:
                hr = parseInt(tm.substring(0,1));
                mn = _to_int (tm.substring(1,3));
                break;

            case 4:
                hr = _to_int(tm.substring(0,2));
                mn = _to_int(tm.substring(2,4));
                break;

            default:
                return false;
        }
        if (hr > 23) hr = 23;
        if (mn > 59) mn = 59;

        var ampm = t.replace (/[^aApP]/g, "");
        if (ampm == "p" && hr < 12) hr += 12;
        return new Array (hr, mn);
    }

    function _process_time (t) {
        var tm;
        if (tm = _get_time (t)) {
            return _hours[tm[0]]+":"+_minutes[tm[1]]+' '+_am_pm[tm[0]];
        } else {
            return _saved_time_val;
        }
    }

    function _process_date (d) {
        var matches = d.match(/([0-9]+)[.-\/]([0-9]+)[.-\/]([0-9]+)/);
        if (!matches)    matches = d.match(/([0-9]+)[.-\/]([0-9]+)/);
        if (!matches)    return _saved_date_val;
        if (!matches[3]) matches[3]= new Date().getFullYear();
        if (matches[3].length == 2) {
            if (_to_int(matches[3]) > 20) {
                matches[3] = '19'+matches[3];
            } else {
                matches[3] = '20'+matches[3];
            }
        }
        if (matches[3].length == 1) {
            matches[3] = '200'+matches[3];
        }
        var nd = new Date(matches[3], matches[1], matches[2], 0, 0);
        return _minutes[nd.getMonth()]+'/'+_minutes[nd.getDate()]+'/'+nd.getFullYear();
    }

    this.add_date = add_date;
    function add_date (nm, lbl, ts) {
        var element = this.date_element(nm, ts);
        this.elements[this.elements.length] = element;
        element.onfocus = _focus_date;
        element.onblur  = _blur_date;
        this.show_element (element, lbl);
        return element;
    }

    this.add_text_area = add_text_area;
    function add_text_area (nm, lbl, val) {
        // creating all cells
        var element = document.createElement("textarea");
        element.setAttribute('name', nm);
        element.setAttribute('id', this.frm_name+'_'+nm);
        element.setAttribute('rows', 4);
        element.setAttribute('cols', 40);
        element.style.width = '600px';
        element.style.height = '50px';
        element.value = val;
        this.elements[this.elements.length] = element;
        this.show_element (element, lbl);
        return element;
    }

    this.add_hidden = add_hidden;
    function add_hidden (nm, val) {
        // creating all cells
        var element = document.createElement("input");
        element.setAttribute('name', nm);
        element.setAttribute('id', this.frm_name+'_'+nm);
        element.setAttribute('type', 'hidden');
        element.setAttribute('value',  val);
        this.elements[this.elements.length] = element;
        this.frm.appendChild(element);
        return element;
    }

    this.add_label = add_label;
    function add_label (lbl) {
        var txt = document.createTextNode (lbl);
        this.show_element (txt);
        return element;
    }

    this.add_select = add_select;
    function add_select (nm, lbl, options, val, onchange) {
        var opt;
        var slct = document.createElement("select");
        slct.style.boderWidth='1px';
        slct.setAttribute('name', nm);
        for (var i=0; i<options.length; i+=2) {
            opt = document.createElement('option');
            opt.value = options[i];
            opt.text  = options[i+1];
            if (opt.value == val) {
                opt.selected = true;
            }
            try {
                slct.add(opt, null); // standards compliant; doesn't work in IE
            } catch(ex) {
                slct.add(opt); // IE only
            }
        }
        if (onchange) {
            alert ("onchange set");
            slct.onChange = onchange;
        }
        this.elements[this.elements.length] = slct;
        this.show_element (slct, lbl);
        return slct;
    }

    this.remove_children = _remove_children;
    function _remove_children (node) {
        if (node) {
            if (node.childNodes) {
                for (var i=node.childNodes.length; i>0; i--) {
                    if (node.childNodes[i-1]) {
                        _remove_children (node.childNodes[i-1]);
                        node.removeChild(node.childNodes[i-1]);
                    }
                }
            }
        }
    }

    this.set_options = set_options;
    function set_options (opts, vals, prnt, cols) {
        var col = 0;
        var lpos = 0;
        var element;
        var txt;
        var opt;
        var opt_div;
        var i;
        var row;
        var append_count = 0;
        if (typeof prnt == 'string') {
            prnt = this.get_obj(prnt);
        }

        _remove_children (prnt);

        for (i=0; i<opts.length; i+=3) {
            if (col % cols == 0) {
                if (row) {
                    prnt.appendChild (row);
                }
                lpos = 0;
                row = add_div ('block', 'relative', '30px', '100%');
            }
            opt_div = add_div ('block', 'absolute', '30px', '200px', '0px', lpos+'px');
            append_count++;
            lpos += 200;
            element = this.add_chk (opts[i], opts[i+1], vals);
            txt = document.createTextNode(opts[i+2]);
            opt_div.appendChild(element);
            opt_div.appendChild(txt);
            row.appendChild(opt_div);
            col++;
        }
        if (row) {
            prnt.appendChild(row);
        }
    }

    this.add_options = add_options;
    function add_options (opts, vals, lbl, scroll, name) {
        var cols = 4;
        var prnt = document.createElement ("div");
        prnt.style.display = 'block';
        prnt.style.position = 'relative';
        prnt.style.margin = '0pt';
        prnt.style.padding = '0pt';
        prnt.id = new Date().getTime();
        if (name) prnt.id = name;
        if (scroll) {
            _set_style (prnt, 'width: 220px; height: 120px; border: 1px solid #ccc; overflowY: scroll; overflowX: hidden;');
            cols = 1;
        }
        this.set_options (opts, vals, prnt, cols);
        if (lbl) {
            this.show_element (prnt, lbl);
        } else {
            this.show_element (prnt);
        }
        this.elements[this.elements.length] = prnt;
        return prnt;
    }

    this.add_chk = add_chk;
    function add_chk (nm, option, values) {
        var element =  document.createElement('input');
        element.type = is_array(values) ? 'checkbox' : 'radio';
        element.name = nm;
        element.id = nm+'_'+option;
        element.value = option;
        if (option_selected(option, values)) {
            element.defaultChecked = true;
        }
        this.elements[this.elements.length] = element;
        return element;
    }

    this.add_checkbox = _add_checkbox;
    function _add_checkbox (nm, value, checked, lbl) {
        var element     =  document.createElement('input');
        element.type    = 'checkbox';
        element.name    = nm;
        element.id      = nm;
        element.value   = value;
        if (checked) {
            element.defaultChecked = true;
        }
        this.elements[this.elements.length] = element;
        this.show_element(element, lbl);
        return (element);
    }

    this.add_submit = add_submit;
    function add_submit (nm,val,action) {
        var submit = document.createElement('input');
        submit.type = 'submit';
        submit.name = nm;
        submit.value = val;
        if (action) submit.onclick=action;
        this.frm.appendChild(submit);
        return submit;
    }

    function add_div (disp, pos, h, w, t, l, id) {
        var div = document.createElement ('div');
        if (id) div.id = id;
        div.style.display = disp;
        div.style.position = pos;
        div.style.width = w;
        div.style.height = h;
        if (t) div.style.top = t;
        if (l) div.style.left = l;
        return div;
    }

    function option_selected (opt, vals) {
        if (is_array(vals)) {
            var i;
            for (i=0;i<vals.length;i++) {
                if (vals[i] == opt) {
                    return true;
                }
            }
        } else {
            if (vals == opt) {
                return true;
            }
        }
        return false;
    }

    this.show_element = show_element;
    function show_element (element, lbl) {
        var row = document.createElement("tr");
        if (lbl) {
            var lbl = document.createTextNode (lbl);
            var lbl_cell = document.createElement ("td");
            lbl_cell.style.verticalAlign='top';
            lbl_cell.appendChild(lbl);
            row.appendChild (lbl_cell);
        }

        var element_cell = document.createElement ("td");
        if (!lbl) element_cell.colspan=2;
        element_cell.appendChild(element);
        row.appendChild (element_cell);
        this.tbl_body.appendChild (row);
    }

    function is_array(obj) {
        return obj && !(obj.propertyIsEnumerable('length')) && typeof obj === 'object' && typeof obj.length === 'number';
    }

    this.show = show;
    function show (x, y) {
    	var dw = parseInt (this.div.style.width);
    	var pw = parseInt (document.body.clientWidth);
    	if (dw != 'NaN' && pw != 'NaN') {
    		x = parseInt (Math.abs(pw - dw)/2);
		}
		y = 20;
        if (y) this.div.style.top = y+'px';
        if (x) this.div.style.left = x+'px';
        this.modal.style.display = 'block';
        this.div.style.display = 'block';
    }

    this.hide = hide;
    function hide () {
    	this.modal.style.display = 'none';
        this.div.style.display = 'none';
    }
}
var frm_current_field;
var frm_highlight_color = '#ffcccc';
var frm_normal_color = '#ffffff';

function frm_highlight (id, valid) {
    document.getElementById(id).style.backgroundColor = (valid ? frm_normal_color : frm_highlight_color);
}

function frm_show_by_name(id) {
    document.getElementByName(id).style.visibility = 'visibile';
}

function frm_hide_by_name(id) {
    document.getElementByName(id).style.visibility = 'hidden';
}

function frm_precheck (fld, req, format, caption) {
    if ((frm_current_field != null) && (frm_current_field == fld)) {
        if (!frm_check(fld, req, format, caption)) {
            // fld.focus();
        } else {
            frm_current_field = null;
        }
    } else if (frm_current_field == null) {
        frm_current_field = fld;
        frm_precheck(fld, req, format,caption);
    }
}

var frm_saved_value = '';
function frm_save_value(obj) {
    frm_saved_value = obj.value;
}

function frm_check (fld, req, format, caption) {
    var msg = null;
    var rval = true;
    switch (format) {
        case "date":
            rval = frm_is_date(fld.value);
            msg = caption + ' is a mandatory date field (mm/dd/yyy)';
            if (!rval) {
                fld.value = "";
            }
            break;

        case "time":
            var re = /^(\d{1,2})[:]?(\d{0,2})[\s]?([ap]?)/i;
            var s = fld.value;
            var m;
            var ampm;
            if (m = s.match(re)) {
                ampm = m[3].length == 0 ? 'AM' : (m[3].toLowerCase() == 'a' ? 'AM' : 'PM');
                var hour = Math.min(Math.max(m[1], 0), 23);
                if (hour > 12) {
                    ampm = 'PM';
                    hour -= 12;
                }
                hour = hour.length == 1 ? '0'+hour : hour;
                var min = m[2].length == 0 ? '00' : (m[2].length==1 ? '0'+m[2] : m[2]);
                fld.value = (hour+':'+min+' '+ampm);
                rval = true;
            } else {
                rval = false;
                msg = caption + ' is a mandatory time field (hh:mm am/pm)';
                fld.value = frm_saved_value;
            }
            break;

        case "number":
            rval = !isNaN(fld.value);
            msg = caption + ' is must be a number';
            if (!rval) {
                if (isNaN(frm_saved_value))
                    fld.value = "";
                else
                    fld.value=frm_saved_value;
            }
            break;

        case "email":
            rval = frm_is_email(fld.value);
            msg = caption + ' is a mandatory email field (address@domain.xxx)';
            if (!rval) {
                fld.value = "";
            }
            break;

        case "password":
            rval = fld.value.length >= 8 && frm_valid_chars (fld.value, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
            msg = caption + ' is a mandatory password field (8 or more letters and/or numbers)';
            if (!rval) {
                fld.value = "";
            }
            break;

        default:
            rval = (fld.value != "");
            msg = caption + ' is mandatory';
            break;
    }
    if (msg != null && rval == false && req) {
        fld.style.backgroundColor = frm_highlight_color;
        //alert (msg);
    } else {
        fld.style.backgroundColor = frm_normal_color;
    }
    frm_saved_value = '';
    if (req) return rval;
    return true;
}

function frm_valid_chars (v, valid_chars) {
    var all_valid = true;
    for (i = 0;  i < v.length;  i++) {
        ch = v.charAt(i);
        for (j = 0;  j < valid_chars.length;  j++) {
            if (ch == valid_chars.charAt(j)) {
                break;
            }
        }
        if (j == valid_chars.length) {
            return false;
        }
    }
    return true;
}

function frm_radio_selected (f, e) {
    var radios = document.getElementById(f).getElementsByTagName(e);
    for(var i=0; i<radios.length; i++) {
        if (radios[i].type!='radio') continue;
        if (radios[i].checked) return true;
    }
    return false;
}

function frm_is_email(email){
    var results
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    results = filter.test(email)
    return (results)
}

function frm_is_date(s) {
    var r = true;
    var results = s.match(/^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/);

    if (results == null) {
        r = false
    } else {
        var m = results[1]; var d = results[3]; var y = results[5];
        var isleap = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
        r = !((m < 1 || m > 12) || (d < 1 || d > 31) || ((m==4 || m==6 || m==9 || m==11) && d==31) || (m==2 && !isleap && d>28) || (m==2 && isleap && d > 29));
    }
    return r;
}

function frm_confirm(msg) {
    if (confirm(msg)) {
        return true;
    } else {
        return false;
    }
}

function frm_change_type (new_type) {
    switch (new_type) {
        case "text":
        case "heading":
            document.getElementById('frm_edit_list').style.display = 'none';
            break;
        case "radio_horz":
        case "radio_vert":
        case "drop_down":
        case "multi_select":
            document.getElementById('frm_edit_list').style.display = 'block';
            break;
    }
}
function frm_change_list_type (new_type) {
    switch (new_type) {
        case "array":
            document.getElementById('frm_edit_list_id').style.display = 'none';
            document.getElementById('list_id').value = '-1';
            document.getElementById('frm_edit_arrays').style.display = 'block';
            document.getElementById('frm_edit_query').style.display = 'none';
            break;

        case "id":
            document.getElementById('frm_edit_list_id').style.display = 'block';
            document.getElementById('list_id').value = '-1';
            document.getElementById('frm_edit_arrays').style.display = 'none';
            document.getElementById('frm_edit_query').style.display = 'none';
            break;

        case "query":
            document.getElementById('frm_edit_list_id').style.display = 'none';
            document.getElementById('list_id').value = '-1';
            document.getElementById('frm_edit_arrays').style.display = 'none';
            document.getElementById('frm_edit_query').style.display = 'block';
            break;

        default:
            document.getElementById('frm_edit_list_id').style.display = 'none';
            document.getElementById('list_id').value = '-1';
            document.getElementById('frm_edit_arrays').style.display = 'none';
            document.getElementById('frm_edit_query').style.display = 'none';
            break;
    }
}

function frm_confirm_and_go (msg, loc) {
    if (confirm(msg)) {
        window.location=loc;
    }
}

function frm_validate_form() {
highlight = "#ffcccc";
normal = "#ffffff";
rval = true;
// updateRTEs();
if (document.layers||document.getElementById||document.all) {
    if (document.frm_admin_form.code.value.length == 0) {
        document.frm_admin_form.code.style.backgroundColor = frm_highlight_color;
        rval = false;
    } else {
        document.frm_admin_form.code.style.backgroundColor = frm_normal_color;
    }
    if (document.frm_admin_form.caption.value.length == 0) {
        document.frm_admin_form.caption.style.backgroundColor = frm_highlight_color;
        rval = false;
    } else {
        document.frm_admin_form.caption.style.backgroundColor = frm_normal_color;
    }
    if (!rval) alert ("Please complete all required (highlighted) fields prior to submitting your form.");
    return rval;
} else
    return true
}
function fun_goto (url) {
    var xy = con_get_scroll();
    window.location=url+"&scroll_y="+xy[1];
    return false;
}

function get_object(obj) {
  if(document.getElementById) {
      return document.getElementById(obj);
  }
  if(document.all) {
      return document.all(obj);
  }
  return null;
}

//function disp_msg (msg) {
    //e = e ? e : window.event;
    //mouseX = e.clientX;
    //mouseY = e.clientY;
    //dynamic_content ('site_msg_box', msg);
    //get_object('site_msg_box').innerHTML = msg;
    //document.onmouseout = hide_msg ();
//}

//function hide_msg () {
    //dynamic_content ('site_msg_box', '');
    //get_object('site_msg_box').innerHTML = '';
    //document.onmouseout = null;
//}

function dynamic_content(elementid, content){
    //var msg = "x: " + site_mouse_x + ", y: " + site_mouse_y;
    if (document.getElementById && !document.all){
        rng = document.createRange();
        el = document.getElementById(elementid);
        rng.setStartBefore(el);
        htmlFrag = rng.createContextualFragment(content);
        while (el.hasChildNodes())
        el.removeChild(el.lastChild);
        el.appendChild(htmlFrag);
    } else {
        get_object(elementid).innerHTML = content;
    }
}

function find_mouse (e) {
    evt = e ? e : window.event;
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
    var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
    x = evt.clientX + scrollLeft;
    y = evt.clientY + scrollTop;
    return [x,y];
}

var msg_obj = null;
function disp_msg (e, obj, msg) {
    //pos = findPos (obj);
    pos = find_mouse (e);
    //alert (pos[0]+","+pos[1]);
    msgbox = get_object ('site_msg_popup');
    if (!msgbox) {
        msgbox = document.createElement('div');
        document.getElementsByTagName('body')[0].appendChild(msgbox);
        msgbox.id = "site_msg_popup";
    }
    if (msg_obj != obj) {
        msgbox.style.left = (pos[0]+2)+'px';
        msgbox.style.top  = (pos[1]+2)+'px';
        msgbox.innerHTML = msg;
        // msgbox.innerHTML = "testing";
        msgbox.style.display = 'block';
        obj.onmouseout = hide_msg;
        document.onmousedown = hide_msg;
        msg_obj = obj;
    }
}

function hide_msg () {
    msgbox = document.getElementById ('site_msg_popup');
    if (msgbox) msgbox.style.display='none';
    document.onmousedown = null;
    msg_obj = null;
}

function findPos(obj) {
    //obj = document.getElementById(obj);
    var curleft = parseInt(obj.style.width);
    var curtop = parseInt(obj.style.height);
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);

    }
    //document.getElementById("msgBox").innerHTML = curleft+","+curtop;
    return [curleft,curtop];
}

function show_hide (id,show) {
    if (obj=document.getElementById(id)) {
        if (show=='show') {
            obj.style.display='block';
            if (obj = document.getElementById(id+'_show')) obj.src = 'images/system/icons/show_gray.gif';
            if (obj = document.getElementById(id+'_hide')) obj.src = 'images/system/icons/hide.gif';
        } else if (show == 'hide') {
            obj.style.display='none';
            if (obj = document.getElementById(id+'_show')) obj.src = 'images/system/icons/show.gif';
            if (obj = document.getElementById(id+'_hide')) obj.src = 'images/system/icons/hide_gray.gif';
        } else {
            obj.style.display=(obj.style.display!='block' ? 'block' : 'none');
        }
    }
}

function fun_toggle (fld) {
    if (obj=document.getElementById(fld)) obj.style.display = obj.style.display!='block' ? 'block' : 'none';
}


function print_article(id) {
    if (obj=document.getElementById('article_'+id)) {
        var d = new Date();
        var tag = (d.getHours()*60*60)+(d.getMinutes()*60)+d.getSeconds();
        print_window=window.open ("","print_window_"+tag,"status=1,width=800,height=600,scrollbars=1,menubar=1,resizable=1");
        // print_window.document.write("<link href=\"default.css\" rel=\"stylesheet\" type=\"text/css\" />\n");
        print_window.document.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">');
        print_window.document.write('<html>');
        print_window.document.write('<head>');
        print_window.document.write("<style type='text/css'>");
        print_window.document.write("td { font-size: 12px; }");
        print_window.document.write("table.grid { border-top: 1px solid #ccc; border-left: 1px solid #ccc; font-size: 12px; }");
        print_window.document.write("table.grid td { border-bottom: 1px solid #ccc; border-right: 1px solid #ccc; vertical-align: top; }");
        print_window.document.write("table.grid th { border-bottom: 1px solid #ccc; border-right: 1px solid #ccc; }");
        print_window.document.write("body { font: 12px \"Trebuchet MS\", Arial, Helvetica, sans-serif; color: #222;  }");
        print_window.document.write("ul { font: 12px \"Trebuchet MS\", Arial, Helvetica, sans-serif; color: #222;  }");
        print_window.document.write("ol { font: 12px \"Trebuchet MS\", Arial, Helvetica, sans-serif; color: #222;  }");
        print_window.document.write(".chart { display: block; position: relative; width: 800px; height: 16px; font-size: 12px; font-weight: normal; font-style: italic; padding: 0; margin: 0; color: #222; }");
        print_window.document.write(".chart div { display: block; position: absolute; height: 16px; left: 100px; top: 0px; width: 700px; padding: 0px; margin: 0px; font-size: 12px; font-weight: normal; color: #222; background: url('images/system/chart_00.gif') repeat-x 0 0;}");
        print_window.document.write(".label_field { display: block; position: relative; width: 100%; height: 24px; font-size: 14px; font-weight: bold; padding-left: 4px; padding-top: 4px; padding-bottom: 4px; color: #555; }");
        print_window.document.write(".label_field div { display: block; position: absolute; left: 0px; top: 0px; width: 100%; padding-top: 4px; padding-bottom: 0; padding-left: 15%; font-size: 14px; font-weight: normal; color: #333; }");
        print_window.document.write(".label_field input.text { width: 40%; }");
        print_window.document.write(".label_field input.text.money { text-align: right; }");
        print_window.document.write(".label_field_high { display: block; position: relative; width: 100%; height: 72px; font-size: 14px; font-weight: bold; padding-left: 4px; padding-top: 4px; padding-bottom: 4px; color: #555}");
        print_window.document.write(".label_field_high div { display: block; position: absolute; left: 0px; top: 0px; width: 100%; padding-left: 15%; font-size: 12px; font-weight: normal; }");
        print_window.document.write(".label_field_high div textarea { width: 50%; height: 60px; }");
        print_window.document.write(".label_report { display: block; position: relative; width: 100%; height: 24px; font-size: 14px; font-weight: bold; padding-left: 4px; padding-top: 4px; padding-bottom: 4px; color: #555; border-bottom: 1px solid #ccc; overflow: hidden;}");
        print_window.document.write(".label_report div { display: block; position: absolute; left: 0px; top: 0px; width: 100%; padding-top: 4px; padding-bottom: 0; padding-left: 15%; font-size: 14px; font-weight: normal; color: #333; overflow: hidden;}");
        print_window.document.write(".label_report .yes_no_label { display: block; position: absolute; left: 0px; top: 0px; width: 100%; padding-top: 4px; padding-bottom: 0; padding-left: 15%; font-size: 14px; font-weight: normal; color: #333; overflow: hidden;}");
        print_window.document.write(".label_report .scale_label { display: block; position: absolute; left: 0px; top: 0px; width: 100%; padding-top: 4px; padding-bottom: 0; padding-left: 15%; font-size: 14px; font-weight: normal; color: #333; overflow: visible;}");
        print_window.document.write(".label_report_count { display: block; position: relative; width: 100%; height: 24px; font-size: 14px; padding: 0px 4px 4px 4px; border-bottom: 1px solid #ccc;}");
        print_window.document.write(".label_report_count .count_value { display: block; position: absolute; left: 0px; bottom: 4px; width: 14%; font-weight: bold; color: #333; text-align: right;}");
        print_window.document.write(".label_report_count .count_label { display: block; position: absolute; left: 0px; bottom: 4px; width: 100%; padding-left: 15%; font-weight: normal; color: #333; height: 20px; }");
        print_window.document.write(".report_note { padding-top: 2px; border-bottom: 1px solid #ccc; color: #000; }");
        print_window.document.write(".report_note div { color: #777; font-style: italic; }");
        print_window.document.write("h1 { padding: 6px 0px 0px 0px; margin: 0px; font-size: 16px; }");
        print_window.document.write("h2 { padding: 6px 0px 0px 0px; margin: 0px; font-size: 14px; }");
        print_window.document.write("h3 { padding: 4px 0px 0px 0px; margin: 0px; font-size: 12px;}");
        print_window.document.write("</style>");
        print_window.document.write('</head>');
        print_window.document.write('<body>');
        print_window.document.write('<div style="align: right; width: 100%; text-decoration: none;"><a href="javascript:window.print();">Print this page</a></div><br />');
        print_window.document.write("If your document fails to print using the button above, please use your browser's menus to print this page.<br />");
        // print_window.document.write("<input type='button' value=' Print this page ' onclick='window.print();return false;' /> ");
        print_window.document.write(obj.innerHTML);
        print_window.document.write("<br /><br /><center><small>Copyright 2009-2010, relate to autism, inc</small></center>");
        print_window.document.write('</body>');
        print_window.document.write('</html>');
    }
}

function pst_leave_msg(frm) {
    call_back = "pst_clean_up('"+frm.id+"')";
    if (frm.body.value.length == 0) {
        alert ("You haven't entered a message!");
        pst_clean_up (frm.name);
        return false;

    }
    var body = format_text(frm.body.value);
    body = body.replace(/&amp;/ig, "[amp]");
    body = body.replace(/&/ig, "[amp]");
    // body = body.replace (/\r\n|\n|\r/g,'[n]');  // get rid of carriage returns so that the GET works
    var url="ajax/post.php?action=pst_leave_msg";
    param = "action=pst_leave_msg";
    param = param + "&body="+body;
    param = param + "&receiver_id="+frm.receiver_id.value;
    param = param + "&receiver_type="+frm.receiver_type.value;
    param = param + "&receiver_name="+frm.receiver_name.value;
    param = param + "&submitter_id="+frm.submitter_id.value;
    if (frm.private.checked == true) {
        param = param + "&private=true";
    }
    if (obj=document.getElementById(frm.id+'_wait')) {
        obj.style.display='block';
    }
    ajx_process (url, "my_messages", call_back, 'POST', param);
    return false;
}

function pst_send_msg_grp(frm) {
    call_back = "pst_clean_up('"+frm.id+"')";
    if (frm.body.value.length == 0) {
        pst_clean_up (frm.name);
        return false;
    }
    receiver_id = -1;
    for (i=0; i<frm.receiver_id.length; i++) {
        if (frm.receiver_id[i].checked) {
            receiver_id = frm.receiver_id[i].value;
            frm.receiver_id[i].checked = false;
            break;
        }
    }
    if (frm.receiver_email) {
        receiver_email = frm.receiver_email.value;
    }
    if (receiver_id < 0 && receiver_email.length == 0) {
        alert ("Please select a group to whom you want to send a message");
        return false;
    }
    var body = format_text(frm.body.value);
    body = body.replace(/&amp;/ig, "[amp]");
    body = body.replace(/&/ig, "[amp]");
    subject = frm.subject.value;
    subject = subject.replace(/&/ig, "[amp]");

    // body = body.replace (/\r\n|\n|\r/g,'[n]');  // get rid of carriage returns so that the GET works
    var url="ajax/post.php?action=pst_send_msg_grp";
    param = "action=pst_send_msg_grp";
    param = param + "&subject="+subject;
    param = param + "&body="+body;
    param = param + "&receiver_id="+receiver_id;
    param = param + "&receiver_email="+receiver_email;
    param = param + "&submitter_id="+frm.submitter_id.value;
    if (frm.private.checked == true) {
        param = param + "&private=true";
    }

    if (obj=document.getElementById(frm.id+'_wait')) {
        obj.style.display='block';
    }
    ajx_process (url, "my_messages", call_back, 'POST', param);
    return false;
}

function pst_comment (post_id) {
    frm_name = 'comment_form_'+post_id;
    call_back = "pst_hide_comment('"+post_id+"')";
    frm = get_object(frm_name);
    var body = format_text(frm.body.value);
    body = body.replace(/&amp;/ig, "[amp]");
    body = body.replace(/&/ig, "[amp]");
    // body = body.replace (/\r\n|\n|\r/g,'[n]');  // get rid of carriage returns so that the GET works
    var url="ajax/post.php?action=pst_comment";
    param = "action=pst_comment";
    param = param + "&body="+body;
    param = param + "&reply_to_id="+post_id;
    param = param + "&receiver_id="+frm.receiver_id.value;
    param = param + "&receiver_name="+frm.receiver_name.value;
    param = param + "&receiver_type="+frm.receiver_type.value;
    param = param + "&submitter_id="+frm.submitter_id.value;
    if (frm.private.value == '1') {
        param = param + "&private=true";
    }
    ajx_process (url, 'my_messages', call_back, 'POST', param);
    return false;
}

function pst_clean_up (frm) {
    if (obj = get_object (frm+"_wait")) {
        obj.style.display='none';
    }
    frm = get_object(frm)
    frm.body.value = '';
    for (i=0; i<frm.receiver_id.length; i++) {
        if (frm.receiver_id[i].checked) {
            receiver_id = frm.receiver_id[i].value;
            frm.receiver_id[i].checked = false;
            break;
        }
    }
    if (frm.receiver_email) {
        frm.receiver_email.value = "";
    }
    if (frm.subject) {
        frm.subject.value = '';
    }
    if (frm.private) {
        frm.private.checked = false;
    }
    frm.body.style.height='40px';
    if (d=get_object('message_form_options')) d.style.display='none';
}

function pst_delete_msg (post_id) {
    if (obj=get_object('delete_message_'+post_id)) {
        obj.innerHTML='';
        obj.style.display='none';
    }
    var url="ajax/post.php?action=pst_delete_msg";
    url = url + "&post_id="+post_id;
    ajx_process (url, null, null);
    return false;

}

function pst_archive_msg (post_id) {
    if (obj=get_object('delete_message_'+post_id)) {
        obj.innerHTML='';
        obj.style.display='none';
    }
    var url="ajax/post.php?action=pst_archive_msg";
    url = url + "&post_id="+post_id;
    ajx_process (url, null, null);
    return false;

}

function pst_subscribe (type, id, flag,contact_id) {
    var url="ajax/post.php?action=pst_subscribe&subscribe_type="+type+"&subscribe_to="+id+"&flag="+flag+"&contact_id="+contact_id;
    ajx_process (url, null, null);
    return false;
}


function pst_hide_comment (id) {
    if (frm = get_object('comment_form_'+id)) frm.body.value = "";
    if (div = get_object('comment_div_'+id)) div.style.display='none';
}

function pst_show_comment (id) {
    if (div = get_object('comment_div_'+id)) div.style.display='block';
    if (frm = get_object('comment_form_'+id)) frm.body.focus();
}

function art_show_comment (id) {
    if (obj = document.getElementById('article_comment_div_'+id)) {
        if (obj.style.display != 'block') {
            obj.style.display = 'block';
        } else {
            set_form_value ('article_comment_form_'+id,'comment', '');
            radio_clear ('article_comment_form_'+id,'rating');
            show_hide('article_comment_div_'+id,'hide');
        }
    }
}

function art_submit_comment (id) {
    call_back = "art_show_comment('"+id+"')";
    var comment = get_form_value('article_comment_form_'+id,'comment');
    var rating  = radio_value('article_comment_form_'+id,'rating');
    var posted_by = get_form_value('article_comment_form_'+id,'posted_by');
    if (comment) {
        var url="ajax/article.php?action=submit_comment";
        param = 'action=submit_comment';
        param = param + "&comment="+comment;
        param = param + "&rating="+rating;
        param = param + "&posted_by="+posted_by;
        param = param + "&article_id="+id;
        ajx_process (url, null, call_back, 'POST', param);
    } else {
        art_show_comment (id);
    }
    return false;
}

function get_form_value(fname,ename) {
    var elements = document.forms[fname].elements;
    return elements[ename].value;
}

function set_form_value(fname,ename,val) {
    var elements = document.forms[fname].elements;
    elements[ename].value = val;
}

function radio_value (fname,ename) {
    var elements = document.forms[fname].elements;
    for (var i=0; i<elements.length; i++) {
        if (elements[i].id==ename && elements[i].checked) return elements[i].value;
    }
}

function radio_clear (fname,ename) {
    var elements = document.forms[fname].elements;
    for (var i=0; i<elements.length; i++) {
        if (elements[i].id==ename) elements[i].checked=false;
    }
}


function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function format_text (txt) {
    var content = '';

    var yt = "<div style=\"display: block; position: relative; height: 320px; width: 260px;\">" +
        "<object width=\"300\" height=\"240\">" +
        "<param name=\"movie\" value=\"http://www.youtube.com/v/$1&amp;hl=en&amp;fs=1\"></param>" +
        "<embed src=\"http://www.youtube.com/v/$1&amp;hl=en&amp;fs=1\" type=\"application/x-shockwave-flash\" width=\"300\" height=\"240\">" +
        "</embed>" +
        "</object>" +
        "</div>";

    // strip out any html tags
    // txt = txt.replace(/(<([^>]+)>)/ig,"");
    txt = txt.replace(/\\/g, "");

    // strip all carriage returns
    txt = txt.replace (/\r/, '');
    // translate bold, italic and other tags
    for (var i=0; i<4; i++) {
        if (txt.match(/[\[b|\[i|\[s|\[y|\[h|\[cr|\[linkx]/)) {
            txt = txt.replace(/\[article\s+(\d+)\s*:\s*([^\[]*)\]/ig, "<a href='http://www.relatetoautism.com/article_$1'>$2</a>");
            txt = txt.replace(/\[linkx\s+(\S.*[^s:])\s*:\s*([^\[]*)\]/ig, "<a href='$1'>$2</a>");
            txt = txt.replace(/\[reg\]/ig, "&reg;");
            txt = txt.replace(/\[cr\]/ig, "&copy;");
            txt = txt.replace(/\[b\s+([^\[]+?)\]/ig, "<b>$1</b>");
            txt = txt.replace(/\[i\s+([^\[]+?)\]/ig, "<em>$1</em>");
            txt = txt.replace(/\[big\s+([^\[]+?)\]/ig, "<span class='big'>$1</span>");
            txt = txt.replace(/\[sup\s+([^\[]+?)\]/ig, "<sup>$1</sup>");
            txt = txt.replace(/\[sub\s+([^\[]+?)\]/ig, "<sub>$1</sub>");
            txt = txt.replace(/\[small\s+([^\[]+?)\]/ig, "<span class='small'>$1</span>");
            txt = txt.replace(/\[yt\s+([^\[]+?)\]/ig, yt);
            txt = txt.replace(/\[h1\s+([^\[]+?)\]/ig, "<h1>$1</h1>");
            txt = txt.replace(/\[h2\s+([^\[]+?)\]/ig, "<h2>$1</h2>");
            txt = txt.replace(/\[h3\s+([^\[]+?)\]/ig, "<h3>$1</h3>");
        }
    }

    // translate the single string into an array of lines
    txt = txt.split ('\n');

    // initialize counters for list translation
    var num_start = false; var bul_start = false; var number_type = 'number';
    var s = ''; var content = ''; var item_processed = false;

    // walk through all the lines
    for (i=0;i<txt.length;i++) {
        //s = trim(txt[i]);
        s = txt[i];
        item_processed = false;
        if (s.match (/^\s*(\*|-)/)) { // process bullet lists
            if (!bul_start) {
                content += "<ul style='margin: 4px; padding: 4px; list-style: disc inside;'>\n";
            }
            bul_start = true;
            content += s.replace(/^\s*[\*-]\s*(.*)/, "<li>$1</li>\n");
            item_processed = true;
        }
        if (bul_start && s.length > 0 && item_processed == false) {
            content += "</ul>\n";
            bul_start = false;
        }
        if (s.match (/^\s*\#/)) { // process numbered lists
            if (!num_start) {
                content += "<ol style='margin-top: 4px; margin-bottom: 4px;'>\n";
            }
            num_start = true;
            content += s.replace (/^\#[iIaA]*\s*(.*)/, "<li>$1</li>\n");
            item_processed = true;
        }
        if (num_start && s.length > 0 && item_processed == false) {
            content += "</ol>\n";
            num_start = false;
        }
        if (!item_processed) {
            content += s + '<br />\n';
        }
    }
    if (bul_start) content += "</ul>\n";
    if (num_start) content += "</ol>\n";
    // alert (content);
    return content;
}

function msg_preview (txt,div) {
    var content = '';
    if (obj=document.getElementById(div)) {
        content += "<h2 style='display: inline;'>Message Preview</h2>&nbsp;&nbsp;&nbsp;";
        content += "<input type='submit' value='Hide Preview' onclick=\"get_object('"+div+"').style.display='none';return false;\" />";
        content += '<br />\n';
        content += format_text(txt);
        obj.innerHTML = content;
        obj.style.display = 'block';
    }
}

function msg_article (src, max_chars, is_pdf, personalize) {
    this.src            = src;
    this.dst            = "";
    this.lines          = new Array();
    this.body           = "";
    this.bul_start      = false;
    this.num_start      = false;
    this.num_item       = 1;
    this.max_chars      = (max_chars ? max_chars : -1);
    this.is_pdf         = is_pdf ? true : false;
    this.personize      = personalize ? true : false;
    this.use_cols       = true;
    this.cur_line       = "";
    this.image_header   = "http://relatetoautism.com/";
    this.col_start      = false;
    this.col_end        = false;
    this.cols           = 0;
    this.blocks         = 0;
    this.append         = true;
    this.tab_start      = false;
    this.bg_color       = "#fff";

    this.disable_cols = disable_cols;
    function disable_cols () {
        this.use_cols = false;
    }

    function trim(s) {
        return s.replace(/^\s+|\s+$/g,"");
    }

    function ltrim(s) {
        return s.replace(/^\s+/,"");
    }

    function rtrim(s) {
        return s.replace(/\s+$/,"");
    }

    function num_to_roman (num) {
        // Make sure that we only use the integer portion of the value
        var n = parseInt(num);
        var result = '';
        // Declare a lookup array that we will use to traverse the number:
        lookup = ("M,1000;CM,900;D,500;CD,400;C,100;XC,90;L,50;XL,40;X,10;IX,9,V,5;IV,4;I,1").split(";");

        var roman;
        var decimal;
        var entry;
        var ccount;
        for (var i=0; i<lookup.length; i++) {
            entry = lookup[i].split(",");
            roman = entry[0];
            decimal = entry[1];
            // Determine the number of matches
            count = parseInt(n/decimal);
            // Store that many characters
            result += str_repeat(roman, count);
            // Substract that from the number
            n = n % decimal;
        }
        // The Roman numeral should be built, return it
        return result;
    }

    this.list_enumerator = list_enumerator;
    function list_enumerator(i, type) {
        var val;
        switch (type) {
            case "i":
                val = num_to_roman (i);
                return val.toLowerCase();
            case "I":
                return num_to_roman (i);
            case "a":
                var s = "a";
                var ascii = s.charCodeAt(0) + i - 1;
                return String.fromCharCode(ascii);
            case "A":
                var s = "A";
                var ascii = s.charCodeAt(0) + i - 1;
                return String.fromCharCode(ascii);
            default:
                return (i);
        }
    }

    function str_repeat (s, c) {
        var content = "";
        for (var i=0; i<c; i++) {
            content += s;
        }
        return content;
    }

    this.make_personal = make_personal;
    function make_personal () {
        if (this.personalize) {
            this.src = this.src.replace ("[child]", "your child");
            this.src = this.src.replace ("[childpos]", "your child's");
            this.src = this.src.replace ("[childpos]", "your child's");
            this.src = this.src.replace ("[he]", "he or she");
            this.src = this.src.replace ("[him]", "him or her");
            this.src = this.src.replace ("[his]", "his or her");
            this.src = this.src.replace ("[first_name]", "you");
        }
    }

    this.replace_links = replace_links;
    function replace_links () {
        this.src = this.src.replace(/\[link\s+([0-9]+)\s*:\s*([^\[]+?)\]/i, "<a href='http://www.relatetoautism.com/index.php?subform=article&article_id=$1'>$2</a>");
        this.src = this.src.replace(/\[link\s+([a-z]+[a-zA-Z0-9_]*)\s*:\s*([^\[]+?)\]/i, "<a href='http://www.relatetoautism.com/index.php?chapter=$1'>$2</a>");
        this.src = this.src.replace(/\[linka\s+([a-z0-9_].*)\s*:\s*([^\[]+?)\]/i, "<a href='http://www.relatetoautism.com/index.php?subform=article&amp;article_id=$1'>$2</a>");
        this.src = this.src.replace(/\[link\s+\?([a-z0-9_].*)\s*:\s*([^\[]+?)\]/i, "<a href='http://www.relatetoautism.com/index.php?$1'>$2</a>");
        this.src = this.src.replace(/\[links\s+([a-z0-9_].*)\s*:\s*([^\[]+?)\]/i, "<a href='http://www.relatetoautism.com/index.php?$1'>$2</a>");
        this.src = this.src.replace(/\[linkl\s+(\S+)\s*:\s*([^\[]+?)\]/i, "<a href='#$1'>$2</a>");
        this.src = this.src.replace(/\[linkx\s+(www.\S+)\s*:\s*([^\[]+?)\]/i, "<a href='http://$1'>$2</a>");
        this.src = this.src.replace(/\[linkx\s+(\S+)\s*:\s*([^\[]+?)\]/i, "<a href='$1'>$2</a>");
    }

    this.replace_av = replace_av;
    function replace_av () {
        var audio = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' " +
            "codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width='340' height='20' id='mp3_player'> " +
            "<param name='allowScriptAccess' value='sameDomain' />" +
            "<param name='movie' value='/media/aplayer.swf?soundFile=/media/audio/$1' />" +
            "<param name='quality' value='high' />" +
            "<param name='bgcolor' value='#ffffff' />" +
            "<param name='wmode' value='transparent' />" +
            "<embed src='/media/aplayer.swf?soundFile=/media/audio/$1' quality='high' wmode='transparent' " +
            "bgcolor='#ffffff' width='340' height='20' name='player' allowScriptAccess='sameDomain' " +
            "type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' /> " +
            "</object>";
        var audio_caption = "<strong>$2</strong>" + audio;
        var audio_caption_photo = "<img src='$3' style='width: 320px; height: 240px; border: 1px solid #333;' /><br />" + audio_caption;

        var embed = "<div style=\"display: block; position: relative\">\n" +
                "<object width=\"300\" height=\"240\">\n" +
                "<param name=\"movie\" value=\"http://www.youtube.com/v/$1&hl=en&fs=1\"></param>\n" +
                "<embed src=\"http://www.youtube.com/v/F5NkJes3-gE&hl=en&amp;fs=1\" type=\"application/x-shockwave-flash\" width=\"300\" height=\"240\">\n" +
                "</embed>\n" +
                "</object>\n" +
                "</div>\n";

        var video = "<div style='float: left; height: 291px; width: 342px; background: #fff; margin-right: 10px;'>";
            video += "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' " +
            "codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='342' height='291' id='FLVPlayer'> " +
            "<param name='movie' value='media/vplayer.swf' /> " +
            "<param name='salign' value='lt' /> " +
            "<param name='quality' value='high' /> " +
            "<param name='scale' value='noscale' /> " +
            "<param name='FlashVars' value='&amp;MM_ComponentVersion=1&amp;skinName=media/full_skin&amp;streamName=/media/video/$1&amp;photo=/images/user/blank.jpg&amp;autoPlay=true&amp;autoRewind=false' />" +
            "<embed src='media/vplayer.swf' " +
            "flashvars='&amp;MM_ComponentVersion=1&amp;skinName=media/full_skin&amp;streamName=/media/video/$1&amp;photo=/images/user/blank.jpg&amp;autoPlay=true&amp;autoRewind=false' " +
            "quality='high' scale='noscale' width='342' height='291' name='FLVPlayer' salign='LT' type='application/x-shockwave-flash' " +
            "pluginspage='http://www.macromedia.com/go/getflashplayer' />" +
            "</object>";
            video += "</div>\n";


        this.src = this.src.replace(/\[yt\s+(.*)\]/, "<div style=\"display: block; position: relative\">" +
            "<object width=\"300\" height=\"240\">" +
            "<param name=\"movie\" value=\"http://www.youtube.com/v/$1&amp;hl=en&amp;fs=1\"></param>" +
            "<embed src=\"http://www.youtube.com/v/$1&amp;hl=en&amp;fs=1\" type=\"application/x-shockwave-flash\" width=\"300\" height=\"240\">" +
            "</embed>" +
            "</object>" +
            "</div>"); // You Tube Embed

        this.src = this.src.replace(/\[video\s+([^\[].*)\]/i, video); // internal video embed
        this.src = this.src.replace(/\[audio\s+(\S*)\s*:\s*(.*)\s*:\s*(\S*)\s*\]/i, audio_caption_photo); // internal audio with caption and image
        this.src = this.src.replace(/\[audio\s+(\S*)\s*:\s*([^:]*)\]/i, audio_caption); // internal audio with caption
        this.src = this.src.replace(/\[audio\s+(.*)\]/i, audio); // internal audio embed
    }

    this.replace_format = replace_format;
    function replace_format () {
        var iframe_inst = "It appears that your browser doesn't support iframes.  To view the content for this article, please click";
        this.src = this.src.replace(/\[bm\s+([^\[ ].*)\s*\]/i,  "<a name='$1' ></a>");
        this.src = this.src.replace(/\[b\s+([^\[]+?)\]/ig,        "<b>$1</b>");
        this.src = this.src.replace(/\[i\s+([^\[]+?)\]/ig,        "<em>$1</em>");
        this.src = this.src.replace(/\[bi\s+([^\[]+?)\]/ig,       "<strong><em>$1</em></strong>");
        this.src = this.src.replace(/\[big\s+([^\[]+?)\]/ig,      "<big>$1</big>");
        this.src = this.src.replace(/\[cell\s+([^\[]+?)\]/ig,     "<td valign='top'>$1</td>");
        this.src = this.src.replace(/\[mid\s+([^\[]+?)\]/ig,      "<span class='medium'>$1</span>");
        this.src = this.src.replace(/\[bigb\s+([^\[]+?)\]/ig,     "<big><b>$1</b></big>");
        this.src = this.src.replace(/\[bigi\s+([^\[]+?)\]/ig,     "<big><em>$1</em></big>");
        this.src = this.src.replace(/\[bigbi\s+([^\[]+?)\]/ig,    "<big><b><em>$1</em></b></big>");
        this.src = this.src.replace(/\[small\s+([^\[]+?)\]/ig,    "<small>$1</small>");
        this.src = this.src.replace(/\[smallb\s+([^\[]+?)\]/ig,   "<small><b>$1</b></small>");
        this.src = this.src.replace(/\[smalli\s+([^\[]+?)\]/ig,   "<small><em>$1</em></small>");
        this.src = this.src.replace(/\[smallbi\s+([^\[]+?)\]/ig,  "<small><b><em>$1</em></b></small>");
        this.src = this.src.replace(/\[sup\s+([^\[]+?)\]/ig,      "<sup>$1</sup>");
        this.src = this.src.replace(/\[sub\s+([^\[]+?)\]/ig,      "<sub>$1</sub>");
        this.src = this.src.replace(/\[h1\s+([^\[]+?)\]/ig,       "<h1>$1</h1> ");
        this.src = this.src.replace(/\[h2\s+([^\[]+?)\]/ig,       "<h2>$1</h2> ");
        this.src = this.src.replace(/\[h3\s+([^\[]+?)\]/ig,       "<h3>$1</h3> ");
        this.src = this.src.replace(/\[right\s+([^\[]+?)\]/ig,    "<div style='width: 100%; text-align: right;'>$1</div>");
        this.src = this.src.replace(/\[center\s+([^\[]+?)\]/ig,   "<div style='width: 100%; text-align: center;'>$1</div>");
        this.src = this.src.replace(/\[include\s+([^\[]+?)\]/ig,  "<iframe src='http://$1' width='80%' height='600' style='margin-left: 10%;'>\n"+iframe_inst+"<a href='$1'>here</a>.\n</iframe>\n");
    }

    this.replace_photos = replace_photos;
    function replace_photos (max_chars) {
        // insert photos
        this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(audio).*\]/, "<img src='$1' width='320px' height='240px' style='margin-right: 10px; margin-bottom: 10px;' />");
        if (max_chars < 0) {
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(right)\s*:\s*(\d+%)\s*\]/i, "<img src='$1' width='$3' align='$2' style='margin-left: 10px;' />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(left)\s*:\s*(\d+%)\s*\]/i,  "<img src='$1' width='$3'  align='$2' style='margin-right: 10px;' />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(right)\s*:\s*(\d+)\s*\]/i, "<img src='$1' width='$3' align='$2' style='margin-left: 10px;' />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(left)\s*:\s*(\d+)\s*\]/i,  "<img src='$1' width='$3'  align='$2' style='margin-right: 10px;' />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(\S+)\s*:\s*(\d+)\s*:\s*(\d+)\s*\]/i, "<img src='$1' align='$2' style='margin: 10px;' width='$3' height='$4'/>");
        } else {
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(right)\s*:\s*(\d+%)\s*\]/i, "<img src='$1' width='100' align='$2' style='margin-left: 10px;' />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(left)\s*:\s*(\d+%)\s*\]/i,  "<img src='$1' width='100'  align='$2' style='margin-right: 10px;' />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(right)\s*:\s*(\d+)\s*\]/i, "<img src='$1' width='100' align='$2' style='margin-left: 10px;' />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(left)\s*:\s*(\d+)\s*\]/i,  "<img src='$1' width='100'  align='$2' style='margin-right: 10px;' />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(right|left)\s*:\s*(\d+)\s*:\s*(\d+)\s*\]/i, "<img src='$1' align='$2' style='margin: 10px;' width='100'  />");
            this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(\S+)\s*:\s*(\d+)\s*:\s*(\d+)\s*\]/i, "<img src='$1' style='margin: 10px;' width='100' />");
        }
        this.src = this.src.replace(/\[p\s+(\S+)\s*:\s*(\S+)\s*\]/ig, "<img src='$1' align='$2' style='margin: 10px;' />");
        this.src = this.src.replace(/\[p\s+(\S+)\s*\]/ig, "<img src='$1' />");
        this.src = this.src.replace(/\[icon\s+([a-z0-9_\.].*)\s*:\s*(.*[^\[])\]/ig, "<img src='images/system/icons/$1' alt=\"$2\" />");
    }

    this.replace_tags = replace_tags;
    function replace_tags () {
        // this.src = this.src.replace(/\[(table|row|cell|center)\]\n/ig,    "[$1]");
        // this.src = this.src.replace(/\[\/(table|row|cell|center)\]\n/ig,  "[/$1]");
        this.src = this.src.replace(/\[amp\]/ig,                      "&amp;");
        this.src = this.src.replace(/\[plus\]/ig,                     "+");
        this.src = this.src.replace(/\[div\]/ig,                      "<div style='display: block; position: relative;'>");
        this.src = this.src.replace(/\[\/div\]/ig,                    "</div><div style='clear: both'></div>");
        this.src = this.src.replace(/\[div\s*:\s*([0-9]+\%)\s*\]/ig,  "<div style='display: block; position: relative; width:$1;'>");
        this.src = this.src.replace(/\[box\]/ig,                      "<div style='clear: both;'></div><div class='top_rounded'><div><div></div></div></div><div class='middle_rounded'>");
        this.src = this.src.replace(/\[\/box\]/ig,                    "<div style='clear: both;'></div></div><div class='bottom_rounded'><div><div></div></div></div>");
        this.src = this.src.replace(/\[center\]/ig,                   "<center>");
        this.src = this.src.replace(/\[\/center\]/ig,                 "</center>");
        this.src = this.src.replace(/\[table\]/ig,                    "<table width='100%' cellspacing='0' cellpadding='4' style='margin-left: 10px;' class='grid'>");
        this.src = this.src.replace(/\[\/table\]/ig,                  "</table>");
        this.src = this.src.replace(/\[x\]/ig,                        "");
        this.src = this.src.replace(/\[\/x\]/ig,                      "");
        this.src = this.src.replace(/\[row\]/ig,                      "<tr>");
        this.src = this.src.replace(/\[\/row\]/ig,                    "</tr>");
        this.src = this.src.replace(/\[cell\]/ig,                     "<td valign='top'>");
        this.src = this.src.replace(/\[\/cell\]/ig,                   "</td>");
        this.src = this.src.replace(/\[reg\]/ig,                      "&reg;");
        this.src = this.src.replace(/\[hr\]/ig,                       "<hr style='border: 1px solid #ccc;' />");
        this.src = this.src.replace(/\[cr\]/ig,                       "&copy;");
        this.src = this.src.replace(/\[sp\]/ig,                       "&nbsp;");
        this.src = this.src.replace(/\[tm\]/ig,                       "<sup><span class='small'>TM</span></sup>");
        this.src = this.src.replace(/\[big\]/ig,                       "<big>");
        this.src = this.src.replace(/\[\/big\]/ig,                     "</big>");
    }

    this.process_bullet = process_bullet;
    function process_bullet () {
        if (this.cur_line.match(/^\s*(\*|-)/)) {
            if (!this.bul_start  && (!this.num_start || this.is_pdf)) {
                if (this.is_pdf) {
                    this.dst += "<ul>\n";
                } else {
                    this.dst += "<table cellspacing='0' cellpadding='0' style='margin-top: 4px; margin-bottom: 4px; border: none;'>\n";
                }
            }
            if (this.is_pdf) {
                this.dst += this.cur_line.replace(/^\s*[\*-]\s*(.*)/, "<li>$1</li>\n");
            } else {
                this.dst += this.cur_line.replace (/^\s*[\*-]\s*(.*)/, "<tr><td width='20' align='right' valign='top' style='border: none;'>&#8226;&nbsp;</td><td style='padding-bottom: 8px; border: none;'>$1</td></tr>");
            }
            this.bul_start = true;
            this.cur_line = "";
        } else if (this.bul_start && !this.cur_line.match(/^\s*(\*|-)/)) {
            if (!this.num_start && !this.is_pdf) {
                this.dst += "</table>\n";
            } else if (this.is_pdf) {
                this.dst += "</ul>\n";
            }
            this.bul_start = false;
        }
    }

    this.process_table = process_table;
    function process_table () {
        if (this.cur_line.match (/\[(ltab|ctab|rtab|tab)\]/ig)) {
            var is_header = false;
            if (!this.table_start) {
                this.table_start = true;
                this.dst += "<table cellpadding='4' cellspacing='0' width='80%'>";
                is_header = true;
                this.bg_color = "#fff";
            } else {
                this.bg_color = this.bg_color == "#fff" ? "#eee" : "#fff";
            }
            if (is_header) {
                this.dst += "<tr><td align='center'><strong>";
                this.dst += this.cur_line.replace (/\[(ltab|ctab|rtab|tab)\]/ig, "</strong></td><td align='center'><strong>");
                this.dst += "</strong></td></tr>\n";
            } else {
                this.dst += "<tr>";
                var elements = this.cur_line.split("[tab]");
                var align = 'left';
                for (var i=0; i<elements.length; i++) {
                    var element = trim(elements[i]);
                    if (element.match(/^\d+:\d+\s*[Aa]*[Pp]*$/)) {
                        align = 'right';
                    } else if (element.match(/^\d+\.*\d*/i)) {
                        align = 'right';
                    }
                    this.dst += "<td style='background: "+this.bg_color+";' align='"+align+"' >" + element + "</td>";
                }
                this.dst += "</tr>";
            }
            this.cur_line = "";

        } else if (this.table_start) {
            this.dst += "</table>";
            this.table_start = false;
        }
    }

    this.process_num_list = process_num_list;
    function process_num_list () {
        var matches;
        if (this.cur_line.match (/^\s*\#/)) {
            if (!this.num_start) {
                if (matches = this.cur_line.match (/^\s*\#(i|I|a|A)/)) {
                    this.num_type = matches[1];
                } else {
                    this.num_type = "n";
                }
                this.num_item = 1;
            }

            if (!this.bul_start  && !this.num_start && !this.is_pdf) {
                this.dst += "<table cellspacing='0' cellpadding='0' style='margin-top: 4px; border: none;'>\n";
            } else if (!this.num_start && this.is_pdf) {
                this.dst += "<ol>\n";
            }
            this.num_start = true;
            if (this.is_pdf) {
                this.dst = this.cur_line.replace (/^\s*[#]\s*(.*)/, "<li>$1</li>\n");
            } else {
                if (this.cur_line.match (/^\s*\#[iIaA]/)) {
                    this.dst += this.cur_line.replace (/^\s*#[iIaA]\s*(.*)/, "<tr><td width='20' align='right' valign='top' style='border: none;'>"+list_enumerator(this.num_item++, this.num_type)+".&nbsp;</td>"+
                        "<td style='padding-bottom: 8px; border: none;'>$1</td></tr>");
                } else {
                    this.dst += this.cur_line.replace (/^\s*#\s*(.*)/, "<tr><td width='20' align='right' valign='top' style='border: none;'>"+list_enumerator(this.num_item++, this.num_type)+".&nbsp;</td>" +
                        "<td style='padding-bottom: 8px; border: none;'>$1</td></tr>");
                }
            }
            this.cur_line = "";
        } else if (this.num_start && !this.cur_line.match (/^\s*$/)) {
            this.num_start = false;
            this.num_item = 1;
            if (!this.bul_start && !this.is_pdf) {
                this.dst += "</table>\n";
            } else if (this.is_pdf) {
                this.dst += "</ol>\n";
            }
        }
    }

    this.process_cols = process_cols;
    function process_cols () {
        if (this.cur_line.match (/\[\s*\/?col\s*([^\[]*)\]/i)) {
            this.col_end  = this.cur_line.match (/^\[\s*\/col\s*\]/i);
            var percent = this.cur_line.match(/^\[\s*col\s*(\d+%)/i);
            this.cur_line = this.cur_line.replace (/\[\s*\/?col\s*([^\[]*)\]/i, "");
            if (percent) {
                percent = percent[1];
            } else {
                percent = '45%';
            }
            if (this.use_cols) {
                if (this.col_start) {
                    this.dst += "</div><!-- end column "+this.cols+"-->";
                    this.col_start = false;
                } else {
                    this.dst += "<div style='clear: both'></div>\n";
                }
                if (this.col_end) {
                    this.dst += "<div style='clear: both'></div>\n";
                    this.cols = 0;
                } else {
                    this.col_start = true;
                    this.cols++;
                    this.dst += "<div style='float: left; padding-left: 8px; padding-right: 8px; width: "+percent+";" + (this.cols > 1 ? "border-left: 1px solid #eeeeee;" : "")+"'><!-- start column "+this.cols+" -->";
                }
            }
        }
    }

    this.process_blocks = process_blocks;
    function process_blocks () {
        var block_end;
        var block_start;
        if (this.cur_line.match (/\[\s*\/?block\s*(\S*)\s*\]/i)) { // block start, block end or both
            block_start = this.cur_line.match (/\[\s*block\s*(\S*)\s*\]/i); // look for block start
            block_end   = this.cur_line.match (/\[\/block.*\]/i);           // look for block end
            this.cur_line = this.cur_line.replace (/\[\s*\/?block\s*(\S*)\s*\]/i, ""); // get rid go tags
            if (this.use_cols && block_start) {
                if (block_start[1]) {
                    this.dst += "<div class='"+block_start[1]+"'>"; // has a style setting
                } else {
                    this.dst += "<div style='display: block; position: relative; padding: 10px;'>"; // default style
                }
                this.blocks++;
            }
            this.dst += this.cur_line;
            this.cur_line = "";
            if (this.use_cols && block_end) {
                this.dst += "</div>";
                this.blocks--;
            }
        }
    }

    this.format_text = format_text;
    function format_text () {

        // set up the new lines
        this.src = this.src.replace(/(\r\n|\r|\n|\[n\]|\[nl\])/, "\n");

        make_personal ();
        this.replace_tags ();

        var count = 0;
        // loop though up to twenty times to handle nesting of tags
        while (this.src.match (/(\[reg\]|cr\]|tm\]|yt\s|video\s|audio\s|b\s|i\s|bi\s|big\s|bigb\s|cell\s|bigi\s|bigbi\s|small\s|smallb\s|smalli\s|smallbi\s|sup\s|sub\s|link\s|linkx\s|h1|h2|h3|include\s|\[p|\[h|\[right|\[center|\[b)/)) {
            this.replace_links();
            this.replace_av ();
            this.replace_format ();
            this.replace_photos (this.max_chars);
            if (count++ > 200) break;
        }

        // process each line for lists, etc.
        this.lines = this.src.split("\n");
        this.dst   = "";
        var num_type = "n";
        var matches;

        for (var i=0; i<this.lines.length; i++) {
            this.cur_line = trim(this.lines[i]);
            if (this.cur_line.length == 0) {
                this.dst += "<br />\n";
                continue;
            }
            this.process_bullet ();
            this.process_num_list ();
            this.process_cols ();
            this.process_blocks ();
            this.process_table ();

            if (this.cur_line.length == 0) continue; // don't process empty lines
            if (!this.cur_line.match (/^<[ht].*>$/i) && !this.cur_line.match (/(tr|td|table|div)>$/ig) && !this.bul_start && !this.num_start) this.cur_line += "<br />\n";
            // process line breaks
            this.dst += this.cur_line;
            if (this.max_chars > 0 && this.dst.length > max_chars) break;
        }
        if (this.is_pdf) {
            if (this.bulstart) this.dst += "</ul>\n";
            if (this.numstart) this.dst += "</ol>\n";
        } else if (this.bul_start || this.num_start) {
            this.dst += "</table>\n";
        }
        if (this.table_start) this.dst += "</table>";
        if (this.col_start) this.dst += "</div><div style='clear: both;'></div>\n";
        if (this.blocks > 0)  this.dst += str_repeat ("</div>\n", this.blocks); // clear out any open divs for blocks
        if (!this.is_pdf) {
            this.dst = this.dst.replace (/relate to autism/ig, "<span class='relate'>relate to autism</span>");
        }
        this.dst = this.dst.replace (/src='\//ig, "src='http://relatetoautism.com/");
        this.dst = this.dst.replace (/(tr|td|table|div)><br \/>/ig, "$1>");
        this.dst = this.dst.replace (/(<\/table>|<\/tr>|<tr>|<\/td>|<\/div>)/ig, "$1\n");
        return (this.dst);
    }
}
// Cross-Browser Rich Text Editor
// http://www.kevinroth.com/rte/demo.htm
// Written by Kevin Roth (kevin@NOSPAMkevinroth.com - remove NOSPAM)
// Visit the support forums at http://www.kevinroth.com/forums/index.php?c=2

//init variables
var isRichText = false;
var rng;
var currentRTE;
var allRTEs = "";

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;


function initRTE(imgPath, incPath, css) {
	//set browser vars
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
	isGecko = (ua.indexOf("gecko") != -1);
	isSafari = (ua.indexOf("safari") != -1);
	isKonqueror = (ua.indexOf("konqueror") != -1);

	//check to see if designMode mode is available
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}

	if (isIE) {
		document.onmouseover = raiseButton;
		document.onmouseout  = normalButton;
		document.onmousedown = lowerButton;
		document.onmouseup   = raiseButton;
	}

	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;

	if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');

	//for testing standard textarea, uncomment the following line
	//isRichText = false;
}

function writeRichText(rte, html, width, height, buttons, readOnly) {
	if (isRichText) {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte;

		if (readOnly) buttons = false;

		//adjust minimum table widths
		if (isIE) {
			if (buttons && (width < 540)) width = 540;
			var tablewidth = width;
		} else {
			if (buttons && (width < 540)) width = 540;
			var tablewidth = width + 4;
		}

		document.writeln('<div class="rteDiv">');
		if (buttons == true) {
			document.writeln('<table class="rteBack" cellpadding=2 cellspacing=0 id="Buttons1_' + rte + '" width="' + tablewidth + '">');
			document.writeln('	<tr>');
			document.writeln('		<td>');
			document.writeln('			<select id="formatblock_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id);">');
			document.writeln('				<option value="">[Style]</option>');
			document.writeln('				<option value="<p>">Paragraph &lt;p&gt;</option>');
			document.writeln('				<option value="<h1>">Heading 1 &lt;h1&gt;</option>');
			document.writeln('				<option value="<h2>">Heading 2 &lt;h2&gt;</option>');
			document.writeln('				<option value="<h3>">Heading 3 &lt;h3&gt;</option>');
			document.writeln('				<option value="<h4>">Heading 4 &lt;h4&gt;</option>');
			document.writeln('				<option value="<h5>">Heading 5 &lt;h5&gt;</option>');
			document.writeln('				<option value="<h6>">Heading 6 &lt;h6&gt;</option>');
			document.writeln('				<option value="<address>">Address &lt;ADDR&gt;</option>');
			document.writeln('				<option value="<pre>">Formatted &lt;pre&gt;</option>');
			document.writeln('			</select>');
			document.writeln('		</td>');
			document.writeln('		<td>');
			document.writeln('			<select id="fontname_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id)">');
			document.writeln('				<option value="Font" selected>[Font]</option>');
			document.writeln('				<option value="Arial, Helvetica, sans-serif">Arial</option>');
			document.writeln('				<option value="Courier New, Courier, mono">Courier New</option>');
			document.writeln('				<option value="Times New Roman, Times, serif">Times New Roman</option>');
			document.writeln('				<option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>');
			document.writeln('			</select>');
			document.writeln('		</td>');
			document.writeln('		<td>');
			document.writeln('			<select unselectable="on" id="fontsize_' + rte + '" onchange="selectFont(\'' + rte + '\', this.id);">');
			document.writeln('				<option value="Size">[Size]</option>');
			document.writeln('				<option value="1">1</option>');
			document.writeln('				<option value="2">2</option>');
			document.writeln('				<option value="3">3</option>');
			document.writeln('				<option value="4">4</option>');
			document.writeln('				<option value="5">5</option>');
			document.writeln('				<option value="6">6</option>');
			document.writeln('				<option value="7">7</option>');
			document.writeln('			</select>');
			document.writeln('		</td>');
			document.writeln('		<td width="100%">');
			document.writeln('		</td>');
			document.writeln('	</tr>');
			document.writeln('</table>');
			document.writeln('<table class="rteBack" cellpadding="0" cellspacing="0" id="Buttons2_' + rte + '" width="' + tablewidth + '">');
			document.writeln('	<tr>');
			document.writeln('		<td><img id="bold" class="rteImage" src="' + imagesPath + 'bold.gif" width="25" height="24" alt="Bold" title="Bold" onClick="rteCommand(\'' + rte + '\', \'bold\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'italic.gif" width="25" height="24" alt="Italic" title="Italic" onClick="rteCommand(\'' + rte + '\', \'italic\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'underline.gif" width="25" height="24" alt="Underline" title="Underline" onClick="rteCommand(\'' + rte + '\', \'underline\', \'\')"></td>');
			document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'left_just.gif" width="25" height="24" alt="Align Left" title="Align Left" onClick="rteCommand(\'' + rte + '\', \'justifyleft\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'centre.gif" width="25" height="24" alt="Center" title="Center" onClick="rteCommand(\'' + rte + '\', \'justifycenter\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'right_just.gif" width="25" height="24" alt="Align Right" title="Align Right" onClick="rteCommand(\'' + rte + '\', \'justifyright\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'justifyfull.gif" width="25" height="24" alt="Justify Full" title="Justify Full" onclick="rteCommand(\'' + rte + '\', \'justifyfull\', \'\')"></td>');
			document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'hr.gif" width="25" height="24" alt="Horizontal Rule" title="Horizontal Rule" onClick="rteCommand(\'' + rte + '\', \'inserthorizontalrule\', \'\')"></td>');
			document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'numbered_list.gif" width="25" height="24" alt="Ordered List" title="Ordered List" onClick="rteCommand(\'' + rte + '\', \'insertorderedlist\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'list.gif" width="25" height="24" alt="Unordered List" title="Unordered List" onClick="rteCommand(\'' + rte + '\', \'insertunorderedlist\', \'\')"></td>');
			document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'outdent.gif" width="25" height="24" alt="Outdent" title="Outdent" onClick="rteCommand(\'' + rte + '\', \'outdent\', \'\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'indent.gif" width="25" height="24" alt="Indent" title="Indent" onClick="rteCommand(\'' + rte + '\', \'indent\', \'\')"></td>');
			document.writeln('		<td><div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'textcolor.gif" width="25" height="24" alt="Text Color" title="Text Color" onClick="dlgColorPalette(\'' + rte + '\', \'forecolor\', \'\')"></div></td>');
			document.writeln('		<td><div id="hilitecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'bgcolor.gif" width="25" height="24" alt="Background Color" title="Background Color" onClick="dlgColorPalette(\'' + rte + '\', \'hilitecolor\', \'\')"></div></td>');
			document.writeln('		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'hyperlink.gif" width="25" height="24" alt="Insert Link" title="Insert Link" onClick="insertLink(\'' + rte + '\')"></td>');
			document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'image.gif" width="25" height="24" alt="Add Image" title="Add Image" onClick="addImage(\'' + rte + '\')"></td>');
			document.writeln('		<td><div id="table_' + rte + '"><img class="rteImage" src="' + imagesPath + 'insert_table.gif" width="25" height="24" alt="Insert Table" title="Insert Table" onClick="dlgInsertTable(\'' + rte + '\', \'table\', \'\')"></div></td>');
			if (isIE) {
				document.writeln('		<td><img class="rteImage" src="' + imagesPath + 'spellcheck.gif" width="25" height="24" alt="Spell Check" title="Spell Check" onClick="checkspell()"></td>');
			}
            document.writeln('		<td width="100%"></td>');
			document.writeln('	</tr>');
			document.writeln('</table>');
		}
		document.writeln('<iframe style="border: 1px solid" id="' + rte + '" name="' + rte + '" width="100%" height="' + height + 'px" src="' + includesPath + 'blank.htm"></iframe>');
        document.writeln('<div id="importer_'+rte+'" style="display: none; position: relative;">');
        var action='<a onclick="process_import(\''+rte+'\'); return false;">here</a>';
        document.writeln('<br /><font color="#111111">Paste text (from MS Word or other application) into the box below and click '+action+'.</font>');
        document.writeln('<textarea id="import_text_'+rte+'" name="import_text_'+rte+'" rows="10" cols="40" style="width: 100%;" ></textarea>');
        document.writeln('</div>');
        if (!readOnly) {
            //document.writeln('<br /><a onclick="show_importer(\''+rte+'\');return false;">Import Text</a>');
            document.writeln('<br /><input type="checkbox" id="chkImport' + rte + '" onclick="show_importer(\''+rte+'\');" />&nbsp;Import Text');
            document.writeln('&nbsp;&nbsp;<input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\');" />&nbsp;View Source');
        }
		document.writeln('<iframe width="154" height="104" id="cp' + rte + '" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; position: absolute;"></iframe>');
		document.writeln('<input type="hidden" id="hdn' + rte + '" name="' + rte + '" value="">');
		document.writeln('</div>');

		document.getElementById('hdn' + rte).value = html;
		enableDesignMode(rte, html, readOnly);
	} else {
		if (!readOnly) {
			document.writeln('<textarea name="'+rte+'" id="'+rte+'" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>');
		} else {
			document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;" readonly>' + html + '</textarea>');
		}
	}
}

function enableDesignMode(rte, html, readOnly) {
	var frameHtml = "<html xmlns=\"http://www.w3.org/1999/xhtml\" id=\"" + rte + "\">\n";
	frameHtml += "<head>\n";
	//to reference your stylesheet, set href property below to your stylesheet path and uncomment
	if (cssFile.length > 0) {
		frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n";
	} else {
		frameHtml += "<style>\n";
		frameHtml += "body {\n";
		frameHtml += "	background: #FFFFFF;\n";
		frameHtml += "	margin: 0px;\n";
		frameHtml += "	padding: 0px;\n";
		frameHtml += "}\n";
		frameHtml += "</style>\n";
	}
	frameHtml += "</head>\n";
	frameHtml += "<body>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";

	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) oRTE.designMode = "On";
	} else {
		try {
			if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
			try {
				var oRTE = document.getElementById(rte).contentWindow.document;
				oRTE.open();
				oRTE.write(frameHtml);
				oRTE.close();
				if (isGecko && !readOnly) {
					//attach a keyboard handler for gecko browsers to make keyboard shortcuts work
					oRTE.addEventListener("keypress", kb_handler, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			//gecko may take some time to enable design mode.
			//Keep looping until able to set.
			if (isGecko) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10);
			} else {
				return false;
			}
		}
	}
}

function updateRTEs() {
	var vRTEs = allRTEs.split(";");
	for (var i = 0; i < vRTEs.length; i++) {
		updateRTE(vRTEs[i]);
	}
}

function updateRTE(rte) {
	if (!isRichText) return;

	//set message value
	var oHdnMessage = document.getElementById('hdn' + rte);
	var oRTE = document.getElementById(rte);
	var readOnly = false;

	//check for readOnly mode
	if (document.all) {
		if (frames[rte].document.designMode != "On") readOnly = true;
	} else {
		if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true;
	}

	if (isRichText && !readOnly) {
		//if viewing source, switch back to design view
		if (document.getElementById("chkSrc" + rte).checked) {
			document.getElementById("chkSrc" + rte).checked = false;
			toggleHTMLSrc(rte);
		}

		if (oHdnMessage.value == null) oHdnMessage.value = "";
		if (document.all) {
			var x = frames[rte].document.body.innerHTML;
		} else {
			var x = oRTE.contentWindow.document.body.innerHTML;
		}
        oHdnMessage.value = x;

		//if there is no content (other than formatting) set value to nothing
		if (stripHTML(oHdnMessage.value.replace("&nbsp;", " ")) == ""
			&& oHdnMessage.value.toLowerCase().search("<hr") == -1
			&& oHdnMessage.value.toLowerCase().search("<img") == -1) oHdnMessage.value = "";
		//fix for gecko
		if (escape(oHdnMessage.value) == "%3Cbr%3E%0D%0A%0D%0A%0D%0A") oHdnMessage.value = "";
	}
}

function rteCommand(rte, command, option) {
	//function to perform command
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	try {
		oRTE.focus();
	  	oRTE.document.execCommand(command, false, option);
		oRTE.focus();
	} catch (e) {
//		alert(e);
//		setTimeout("rteCommand('" + rte + "', '" + command + "', '" + option + "');", 10);
	}
}

function forceHTML (rte) {
    return;
    if (!document.getElementById('chkSrc'+rte).checked) {
        document.getElementById('chkSrc'+rte).checked = true;
        toggleHTMLSrc(rte);
    }
}

function forceDesign (rte) {
    return;
    if (document.getElementById('chkSrc'+rte).checked) {
        document.getElementById('chkSrc'+rte).checked = false;
        toggleHTMLSrc(rte);
    }
}

function set_body (rte,html) {
    insertHTML(rte,html);
    return;
    forceHTML (rte);
    if (document.all) {
        oRTE = frames[rte].document;
        oRTE.body.innerText = html;
    } else {
        oRTE = document.getElementById(rte).contentWindow.document;
        oRTE.body.innerHTML = html;
        //oRTE.body.appendChild(html);
    }
    forceDesign (rte);
}

function toggleHTMLSrc(rte) {
	//contributed by Bob Hutzel (thanks Bob!)
	var oRTE;
	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}

	if (document.getElementById("chkSrc" + rte).checked) {
		showHideElement("Buttons1_" + rte, "hide");
		showHideElement("Buttons2_" + rte, "hide");
		if (document.all) {
			oRTE.body.innerText = oRTE.body.innerHTML;
		} else {
			var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML);
			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	} else {
		showHideElement("Buttons1_" + rte, "show");
		showHideElement("Buttons2_" + rte, "show");
		if (document.all) {
			//fix for IE
			var output = escape(oRTE.body.innerText);
			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");

			oRTE.body.innerHTML = unescape(output);
		} else {
			var htmlSrc = oRTE.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oRTE.body);
			oRTE.body.innerHTML = htmlSrc.toString();
		}
	}
}

function dlgColorPalette(rte, command) {
	//function to display or hide color palettes
	setRange(rte);

	//get dialog position
	var oDialog = document.getElementById('cp' + rte);
	var buttonElement = document.getElementById(command + '_' + rte);
	var iLeftPos = getOffsetLeft(buttonElement);
	var iTopPos = getOffsetTop(buttonElement) + (buttonElement.offsetHeight + 4);
	oDialog.style.left = (iLeftPos) + "px";
	oDialog.style.top = (iTopPos) + "px";

	if ((command == parent.command) && (rte == currentRTE)) {
		//if current command dialog is currently open, close it
		if (oDialog.style.visibility == "hidden") {
			showHideElement(oDialog, 'show');
		} else {
			showHideElement(oDialog, 'hide');
		}
	} else {
		//if opening a new dialog, close all others
		var vRTEs = allRTEs.split(";");
		for (var i = 0; i < vRTEs.length; i++) {
			showHideElement('cp' + vRTEs[i], 'hide');
		}
		showHideElement(oDialog, 'show');
	}

	//save current values
	parent.command = command;
	currentRTE = rte;
}

function dlgInsertTable(rte, command) {
	//function to open/close insert table dialog
	//save current values
	setRange(rte);
	parent.command = command;
	currentRTE = rte;
	var windowOptions = 'history=no,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=no,width=360,height=200';
	window.open(includesPath + 'insert_table.htm', 'InsertTable', windowOptions);
}

function insertLink(rte) {
	//function to insert link
	var szURL = prompt("Enter a URL:", "");
	try {
		//ignore error for blank urls
		rteCommand(rte, "Unlink", null);
		rteCommand(rte, "CreateLink", szURL);
	} catch (e) {
		//do nothing
	}
}

function setColor(color) {
	//function to set color
	var rte = currentRTE;
	var parentCommand = parent.command;

	if (document.all) {
		//retrieve selected range
		var sel = frames[rte].document.selection;
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		if (sel != null) {
			var newRng = sel.createRange();
			newRng = rng;
			newRng.select();
		}
	}

	rteCommand(rte, parentCommand, color);
	showHideElement('cp' + rte, "hide");
}

function addImage(rte) {
	//function to add image
	imagePath = prompt('Enter Image URL:', 'http://');
	if ((imagePath != null) && (imagePath != "")) {
		rteCommand(rte, 'InsertImage', imagePath);
	}
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2; //the positioning div is 2 elements up the tree

	while(parents_up > 0) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}

	return mOffsetTop;
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2;

	while(parents_up > 0) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}

	return mOffsetLeft;
}

function selectFont(rte, selectname) {
	//function to handle font changes
	var idx = document.getElementById(selectname).selectedIndex;
	// First one is always a label
	if (idx != 0) {
		var selected = document.getElementById(selectname).options[idx].value;
		var cmd = selectname.replace('_' + rte, '');
		rteCommand(rte, cmd, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
}

function kb_handler(evt) {
	var rte = evt.target.id;

	//contributed by Anti Veeranna (thanks Anti!)
	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = '';
		switch (key) {
			case 'b': cmd = "bold"; break;
			case 'i': cmd = "italic"; break;
			case 'u': cmd = "underline"; break;
		};

		if (cmd) {
			rteCommand(rte, cmd, null);

			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

function process_import (rte) {
    if (obj = document.getElementById('import_text_'+rte)) {
        html=str_to_html(obj.value);
        set_body(rte, html);
        obj.value = '';
    }
    if (obj = document.getElementById('importer_'+rte)) {
        obj.style.display='none';
    }
}

function show_importer (rte) {
    var importer = null;
    if (importer = document.getElementById('importer_'+rte)) {
        importer.style.display=(importer.style.display=='block' ? 'none' : 'block');
        if (importer.style.display == 'block') {
            forceHTML (rte);
        } else {
            forceDesign (rte);
        }
    }
}

function insertHTML(rte,html) {
	//function to add HTML -- thanks dannyuk1982
	//var rte = currentRTE;

	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}

	oRTE.focus();
	if (document.all) {
		oRTE.document.selection.createRange().pasteHTML(html);
	} else {
		oRTE.document.execCommand('insertHTML', false, html);
	}
}

function showHideElement(element, showHide) {
	//function to show or hide elements
	//element variable can be string or object
	if (document.getElementById(element)) {
		element = document.getElementById(element);
	}

	if (showHide == "show") {
		element.style.visibility = "visible";
	} else if (showHide == "hide") {
		element.style.visibility = "hidden";
	}
}

function setRange(rte) {
	//function to store range of current selection
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		var selection = oRTE.document.selection;
		if (selection != null) rng = selection.createRange();
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
}

function stripHTML(oldString) {
	//function to strip all html
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");

	//replace carriage returns and line feeds
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");

	//trim string
	newString = trim(newString);

	return newString;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);

   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length - 1, retValue.length);

   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length - 1);
      ch = retValue.substring(retValue.length - 1, retValue.length);
   }

	// Note that there are two spaces in the string - look for multiple spaces within the string
   while (retValue.indexOf("  ") != -1) {
		// Again, there are two spaces in each of the strings
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
   }
   return retValue; // Return the trimmed string back to the user
}

//*****************
//IE-Only Functions
//*****************
function checkspell() {
	//function to perform spell check
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell not detected.  Click Ok to go to download page."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		} else {
			alert("Error Loading ieSpell: Exception " + exception.number);
		}
	}
}

function raiseButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;

	className = el.className;
	if (className == 'rteImage' || className == 'rteImageLowered') {
		el.className = 'rteImageRaised';
	}
}

function normalButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;

	className = el.className;
	if (className == 'rteImageRaised' || className == 'rteImageLowered') {
		el.className = 'rteImage';
	}
}

function lowerButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;

	className = el.className;
	if (className == 'rteImage' || className == 'rteImageRaised') {
		el.className = 'rteImageLowered';
	}
}

function str_to_html (s) {
    var o = '';
    for(i=0; i<s.length;i++) {
        c = s.charCodeAt(i);
        o = o + char_to_html(c);
    }
    alert (o);
    o = o.replace(/\n-(.*)<br \/>\n/, '<div style="display: block; position: relative"><div style="float: left; width: 30px;">-</div><div style="float: left;">$1</div><div style="clear: both;"></div></div>');
    return o;
}

function char_to_html (x) {
    switch (x) {
        case 9: return ' ';
        case 10: return '<br />\n';
        case 11: case 12: return '';
        case 13: return '';
        case 34: return "&quot;";
        case 38: return "&amp;";
        case 39: return "&#39";
        case 60: return "&lt;"
        case 62: return "&gt;"
        default:
            break;
    }
    if ((x<=8)||(x>= 14 && x<=31)) return '';
    if (x<127) return String.fromCharCode(x);
    //if (x>=160) return "&#"+x.toString(16)+";";
    if (x>=160) return "&#"+x+";";
    return ("");
}
function site_assign_chapter(chapter_id, section_id) {
    for (var i=0; i<chapter_list.length; i+=3) {
        if (chapter_list[i] == chapter_id) {
            chapter_list[i+1] = section_id;
            break;
        }
    }
    var url="ajax/site.php?action=assign_chapter";
    url = url + "&section_id="+section_id;
    url = url + "&chapter_id="+chapter_id;
    ajx_process (url, "site_structure", "draw_site_structure()");
    return false;
}

function site_assign_article(article_id, chapter_id) {
    for (var i=0; i<article_list.length; i+=3) {
        if (article_list[i] == article_id) {
            article_list[i+1] = chapter_id;
            break;
        }
    }
    var url="ajax/site.php?action=assign_article";
    url = url + "&article_id="+article_id;
    url = url + "&chapter_id="+chapter_id;
    ajx_process (url, "site_structure", "draw_site_structure()");
    return false;
}

function site_inc_section(section_id) {
    var url="ajax/site.php?action=inc_section";
    url = url + "&section_id="+section_id;
    ajx_process (url, "site_structure", "draw_site_structure()");
}

function site_dec_section(section_id) {
    var url="ajax/site.php?action=dec_section";
    url = url + "&section_id="+section_id;
    ajx_process (url, "site_structure", "draw_site_structure()");
}

function site_inc_chapter(chapter_id) {
    var url="ajax/site.php?action=inc_chapter";
    url = url + "&chapter_id="+chapter_id;
    ajx_process (url, "site_structure", "draw_site_structure()");
}

function site_dec_chapter(chapter_id) {
    var url="ajax/site.php?action=dec_chapter";
    url = url + "&chapter_id="+chapter_id;
    ajx_process (url, "site_structure", "draw_site_structure()");
}

function site_inc_article(article_id) {
    var url="ajax/site.php?action=inc_article";
    url = url + "&article_id="+article_id;
    ajx_process (url, "site_structure", "draw_site_structure()");
}

function site_dec_article(article_id) {
    var url="ajax/site.php?action=dec_article";
    url = url + "&article_id="+article_id;
    ajx_process (url, "site_structure", "draw_site_structure()");
}

function site_edit_section(section_id) {
    window.location="index.php?subform=section&action=edit&admin_section_id="+section_id;
}

function site_edit_chapter(chapter_id) {
    window.location="index.php?subform=section&action=edit&admin_chapter_id="+chapter_id;
}

function site_add_section (seq) {
    seq = seq+0.1;
    window.location="index.php?subform=section&action=add&type=section&seq="+seq;
}

function site_add_chapter (section_id, seq) {
    seq = seq+0.1;
    window.location="index.php?subform=section&admin_section_id="+section_id+"&action=add&type=chapter&seq="+(seq);
}

function site_delete_section (section_id) {
    if (confirm('Really delete this section?')) {
        window.location="index.php?subform=structure&action=delete&type=section&id="+section_id;
    }
}

function site_delete_chapter (chapter_id) {
    if (confirm('Really delete this chapter?')) {
        window.location="index.php?subform=structure&action=delete&type=chapter&id="+chapter_id;
    }
}
