/* General Javascript library */

// shorthand to getElementById
var gimme = function(elem) {
    return document.getElementById(elem);
}

var resizer = function(w, h) {
    var testHeight = h;
    var testWidth  = w;
    window.resizeTo(testWidth, testHeight);

    // resize in a timeout for chrome
    setTimeout(function() {
        var clientHeight = document.documentElement.clientHeight;
        var clientWidth = document.documentElement.clientWidth;

        window.resizeTo(testWidth+(testWidth-clientWidth), testHeight+(testHeight-clientHeight));
    }, 200);
}

var findPos = function(obj) {
  var curleft = curtop = 0;

  if (obj.offsetParent) {
      do {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);

      return [curleft,curtop];
  }
}

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well

var pageWidth = function() {
  return (window.innerWidth != null ) ?
    window.innerWidth :
    ( document.documentElement && document.documentElement.clientWidth ) ?
      document.documentElement.clientWidth :
      ( document.body != null ) ?
        document.body.clientWidth :
        null;
}

var pageHeight = function() {
  return ( window.innerHeight != null ) ?
    window.innerHeight :
    ( document.documentElement && document.documentElement.clientHeight ) ?
      document.documentElement.clientHeight :
      ( document.body != null ) ? document.body.clientHeight : null;
}

var posLeft = function() {
  return ( typeof window.pageXOffset != 'undefined' ) ?
    window.pageXOffset :
    ( document.documentElement && document.documentElement.scrollLeft) ?
      document.documentElement.scrollLeft :
      ( document.body.scrollLeft ) ? document.body.scrollLeft : 0;
}

var posTop = function() {
  return ( typeof window.pageYOffset != 'undefined' ) ?
    window.pageYOffset :
    ( document.documentElement && document.documentElement.scrollTop ) ?
      document.documentElement.scrollTop :
      ( document.body.scrollTop ) ? document.body.scrollTop : 0;
}

var posRight = function() {
  return posLeft() + pageWidth();
}

var posBottom = function() {
  return posTop()+pageHeight();
}

// used in billing form to copy Company Info fields into cc_ fields
var copyBillingFields = function() {
    var fields = ['address1', 'address2', 'city', 'state', 'country', 'zip', 'phone'];

    for ( f in fields ) {
        var c = 'cc_' + fields[f];
        gimme(c).value = gimme(fields[f]).value;
    }

    return false;
}

/** Delete a domain object, confirming with the user first
* @param int id The DO's ID
* @param string domain_object_type The kind of domain object
*/
var doDelete = function(id, domain_object_type) {
  if ( confirm('Are you sure you want to permanently delete this item?') ) {
      location.href = "/Delete/" + domain_object_type + "/" + id;
  }

  return false;
}

// set the class on a tr with a given ID
var setRowClass = function(id, newclass) {
    if ( gimme('tr' + id) ) {
        // for IE6
        gimme('tr' + id).setAttribute('className', newclass);
        gimme('tr' + id).setAttribute('class', newclass);
    }
}

// common logic for massdel and optout popup box
var initZxPopup = function(id) {
    if ( gimme('zxPopup') == undefined ) {
        var x = document.createElement('div');
        x.id = 'zxPopup';
        document.body.appendChild(x);
    }
    else var x = gimme('zxPopup');

    if ( x.getAttribute('zx:lastid') == id ) {
        setRowClass(id, 'row');
        x.setAttribute('zx:lastid', '');
        x.style.display = 'none';
        return false;
    }

    if ( x.getAttribute('zx:lastid') ) setRowClass(x.getAttribute('zx:lastid'), 'row');
    setRowClass(id, 'highlight');

    return x;
}

/** Delete an entire recurring meeting group (PlannedCall)
* @param int id The DO's ID
* @param string domain_object_type The kind of domain object
*/
var doMassDelete = function(id, domain_object_type) {
    var md = initZxPopup(id);

    if ( md == false ) return false;

    var msg = '<span style="float: right;">[<a href="#" onclick="return doMassDelete(' + id + ');">close</a>]</span><br>';
    msg += 'This conference is part of a recurring meeting set. You may therefore choose to ';
    msg += 'delete:<br> <center><a href="/Delete/' + domain_object_type + '/' + id + '">just this conference</a> or ';
    msg += '<a href="/Delete/' + domain_object_type + '/' + id + '?m=1">the entire set</a></center>';

    var linkpos = findPos(gimme('mdel' + id));

    md.innerHTML = msg;
    md.style.left = linkpos[0] - 240 + 'px';
    md.style.top = linkpos[1] - 80 + 'px';
    md.style.display = 'block';
    md.setAttribute('zx:lastid', id);

    return false;
}

// Display opt out menu options for a PlannedCall
var OptOut = {
    multiple:false,

    toggle:function() {
        var l = gimme('ooToggle');
        OptOut.multiple = ( l.checked ) ? true : false;
    },
    go:function(link) {
        if ( OptOut.multiple ) link.href += "?m=1";
    },

    init:function(id, oo_val, ws_only, recurring) {
        var oo = initZxPopup(id);

        if ( oo == false ) return false;

        OptOut.multiple = false;
 
        var msg = '<span style="float: right;">[<a href="#" onclick="return OptOut.init(' + id + ',0,false,false);';
        msg += '">close</a>]</span><br>';

        if ( recurring ) {
            msg += '<b>Recurring Conference Set</b><br> Apply this change to all conferences in the set? ';
            msg += '<input type="checkbox" id="ooToggle" onclick="return OptOut.toggle()"><br><br>';
        }

        var tmp = ( ws_only ) ? '' : 'with Call-Me ';

        var link_opt_out = '<a href="/OptOut/' + id + '/2" onclick="OptOut.go(this)">Completely opt-out of this conference</a>';
        var link_no_call = '<a href="/OptOut/' + id + '/1" onclick="OptOut.go(this)">Disable call-me but still participate via dial-in</a>';
        var link_rejoin  = '<a href="/OptOut/' + id + '/0" onclick="OptOut.go(this)">Participate ' + tmp + 'in this conference</a>';

        if ( oo_val == 1 ) {
            var link_combo = link_opt_out;
            if ( !ws_only ) {
                msg += 'You have disabled Call-Me for this conference. ';
                link_combo += '<br>or<br>' + link_rejoin;
            }
        }
        else if ( oo_val == 2 ) {
            msg += 'You are currently opted-out of this conference. ';
            var link_combo = link_rejoin;
            if ( !ws_only ) link_combo += '<br>or<br>' + link_no_call;
        }
        else {
            msg += 'Your Opt-out flag is not set. ';
            link_combo = link_opt_out;
            if ( !ws_only ) link_combo += '<br>or<br>' + link_no_call;
        }

        msg += 'You may choose to:<br> <center>' + link_combo + '</center>';

        var linkpos = findPos(gimme('opt_' + id));

        oo.innerHTML = msg;
        oo.style.left = linkpos[0] - 240 + 'px';
        oo.style.top = linkpos[1] - 80 + 'px';
        oo.style.display = 'block';
        oo.setAttribute('zx:lastid', id);

        return false;
    }
}

// used in account form for admin suspend flag
var suspendMsg = function(o) {
    if ( o.checked == true ) {
        if ( confirm('This will PERMANENTLY disable this account and all of its sub-accounts. Is that OK?') ) {
            return true;
        }

        o.checked = false;
        return false;
    }

    return true;
}

var helpArrowClose = function() {
    gimme("helpArrowContainer").style.display = "none";
    return false;
}

var downloadRecording = function(f) {
    var dash_window = window.open('/Queue/x/' + f + '/x.html', "ZipDx_Recording_Q", "height=130px,width=435px,resizable=yes,scrollbars=yes"); 
    dash_window.focus();
    return false;
}

var openDashboard = function(url) {
    var dash_window = window.open(url, "ZipDx_Conference_Dash", "height=615px,width=855px,resizable=yes,scrollbars=yes"); 
    dash_window.focus();
    return false;
}

// class for on demand, user invoked dialout
var DO = {
    timer_id:false,

    openCallMe:function() {
        var _window = window.open('/CallMe/init', "ZipDx_Call_Me", "height=650px,width=475px,resizable=yes,scrollbars=yes"); 
        _window.focus();
        return false;
    },

    callMe:function(x, y) {
        var data = ( y ) ? 'custom=' + encodeURIComponent(x) : 'p=' + x;

        if ( DO.timer_id ) clearTimeout(DO.timer_id);
        AJAX.ajaxInit('/CallMe/call', data, 'post', 'DO.callmeCallBack');
        return false;
    },
    
    custom:function() {
        var x = gimme('custom').value.replace(/[^0-9a-z#_@:'\.\-\*\+]/ig, "");
        gimme('custom').value = x;

        DO.callMe(x, true);
        return false;
    },

    disconnect:function() {
        AJAX.ajaxInit('/CallMe/disconnect', null, 'get', 'DO.disconnectCallBack');
        return false;
    },

    checkStatus:function() {
        AJAX.ajaxInit('/CallMe/status', null, 'get', 'DO.statusCallBack');
    },

    ack:function() {
        AJAX.ajaxInit('/CallMe/ack', null, 'get', 'DO.ackCallBack');
        return false;
    },

    callmeCallBack:function(x) {
        if ( DO.timer_id ) clearTimeout(DO.timer_id);
        DO.timer_id = setTimeout(DO.checkStatus, 3000);
        gimme('ackCntnr').innerHTML = '';

        if ( x.indexOf('Calling') > -1 )  {
            gimme('resultCntnr').innerHTML = x;
            gimme('statusCntnr').innerHTML = '';
        }
        else alert(x);
    },

    disconnectCallBack:function(x) {
        if ( DO.timer_id ) clearTimeout(DO.timer_id);
        DO.timer_id = setTimeout(DO.checkStatus, 3000);
        gimme('statusCntnr').innerHTML = x;
        gimme('resultCntnr').innerHTML = '';
        gimme('ackCntnr').innerHTML = '';
    },

    statusCallBack:function(x) {
        gimme('ackCntnr').innerHTML = '';
        if ( DO.timer_id ) clearTimeout(DO.timer_id);
        if ( x ) {
            gimme('statusCntnr').innerHTML = 'There is a Call-Me in progress.<br><a href="#" onclick="return DO.ack();">ACKNOWLEDGE</a> or <a href="#" onclick="return DO.disconnect();">DISCONNECT</a>.';
            DO.timer_id = setTimeout(DO.checkStatus, 3000);
        }
        else {
            gimme('resultCntnr').innerHTML = '';
            gimme('statusCntnr').innerHTML = '';
        }
    },

    ackCallBack:function(x) {
        if ( x == 'OK' ) {
            if ( DO.timer_id ) clearTimeout(DO.timer_id);
            gimme('ackCntnr').innerHTML = 'Connected! <a href="#" onclick="parent.window.close()">Close Window</a>';
            gimme('statusCntnr').innerHTML = '';
            gimme('resultCntnr').innerHTML = '';
        }
        else alert(x);
    }
}

// sets the topic email in the CT form
var displayTopic = function(t) {
    var y = t.value;

    y = y.toLowerCase();
    y = y.replace(/^\s+|\s+$/g, "");
    y = y.replace(/[^a-z0-9_ -]/g, "");
    y = y.replace(/ +/g, "_");
    y = y.replace(/_+/g, "_");
    y = y.replace(/^_|_$/g, "");
    y = y.replace(/\-+/g, "-");
    y = y.replace(/^\-|\-$/g, "");
  
    gimme('topicEmail').innerHTML = y.substring(0, 63);
}

// determines if spontaneous select box is disabled or not
var displaySpont = function(t) {
    var s = gimme('is_spontaneous');
    if ( t.value.length == 6 && /^\d{6}$/.test(t.value) ) {
        s.disabled = false;
    }
    else {
        s.value = 0;
        s.disabled = true;
    }

    // Waiting Room/without_host toggler
    WR.parse();
}

/* Adobe Connect Pro related class */
var ACP = {
    inited:false,
    statusCache:{},

    // for PC form to allow acp enable based on selected account
    init:function() {
        var acpCntnr  = gimme("acpContainer");
        var account   = gimme("account_id");
        var acpStatus = gimme("acpStatus");

        // all required fields available to DOM? otherwise bail
        if ( acpCntnr == undefined || account == undefined || acpStatus == undefined ) return; 

        ACP.statusCache = eval('(' + acpStatus.innerHTML + ')');

        ACP.inited = true;
        account.onchange = function() { REC.parse(); ACP.parse(); TRANS.parse(); };
        ACP.parse();
    },
    parse:function() {
        if ( !ACP.inited ) return;

        var nocallWS = ( arguments[0] != undefined ) ? arguments[0] : false;

        gimme("acpContainer").style.display = ( ACP.statusCache[gimme("account_id").value] == 1 ) ? "block" : "none";

        var tmp = false;
        if ( ACP.statusCache[gimme("account_id").value] == 2 ) {
            gimme("wsContainer").style.display = "none";
            tmp = gimme("webshare_only").value;
            gimme("webshare_only").value = 2;
        }
        else gimme("wsContainer").style.display = "block";

        if ( !nocallWS ) WS.parseWS(true);
        if ( tmp !== false ) gimme("webshare_only").value = tmp;
    },

    openACP:function(pcid) {
        var acp_win = window.open('/Connect/x/' + pcid, "ZipDx_Connect_Pro", "left=0px,top=0px,resizable=yes,scrollbars=yes"); 
        acp_win.resizeTo(screen.availWidth,screen.availHeight);
        acp_win.focus();
        return false;
    }
}

// toggles public/private access for recordings; also for PC form to allow Recording based on selected account
var REC = {
    thespan:null,
    inited:false,
    statusCache:{},
    original_value:0,

    init:function() {
        var rec     = gimme("record");
        var account = gimme("account_id");
        var rStatus = gimme("recForceStatus");

        // all required fields available to DOM? otherwise bail
        if ( rec == undefined || account == undefined || rStatus == undefined ) return; 

        REC.original_value = gimme("record").value;
        REC.statusCache = eval('(' + rStatus.innerHTML + ')');

        REC.inited = true;
        account.onchange = function() { REC.parse(); ACP.parse(); TRANS.parse(); };
        REC.parse();

    },
    parse:function() {
        if ( !REC.inited ) return;

        var rec = gimme("record");
        var rec_force = REC.statusCache[gimme("account_id").value];

        // -1 leave both options
        rec.options[0] = new Option("No", 0);
        rec.options[1] = new Option("Yes", 1);

        if ( rec_force == 0 )      rec.options[1] = null;
        else if ( rec_force == 1 ) rec.options[0] = null;

        // make sure if yes that it is selected value after messing with select options
        if ( REC.original_value == 1 && rec.options[1] != undefined ) rec.options[1].selected = true;
    },

    toggler:function(filename) {
        REC.thespan = 'rec' + filename;
        AJAX.ajaxInit('/Ajax/Recording/' + filename, null, 'get', 'REC.ajaxCheckStatus');

        return false;
    },

    ajaxCheckStatus:function(txt) {
        gimme(REC.thespan).innerHTML = txt;
    }
}

// for PC form to allow Transcription fields based on selected account
var TRANS = {
    inited:false,
    statusCache:{},

    init:function() {
        var tCntnr  = gimme("transcribeContainer");
        var account = gimme("account_id");
        var tStatus = gimme("transcribeStatus");

        // all required fields available to DOM? otherwise bail
        if ( tCntnr == undefined || account == undefined || tStatus == undefined ) return; 

        TRANS.statusCache = eval('(' + tStatus.innerHTML + ')');

        TRANS.inited = true;
        account.onchange = function() { REC.parse(); ACP.parse(); TRANS.parse(); };
        TRANS.parse();
    },
    parse:function() {
        if ( !TRANS.inited ) return;

        if ( TRANS.statusCache[gimme("account_id").value] ) {
            gimme("transcribeContainer").style.display = "block";
            var tx = gimme("transcribe");
            var vx = TRANS.statusCache[gimme("account_id").value];
            if ( vx < 2 ) tx.options[2] = null;
            else if ( tx.options.length < 3 ) tx.options[2] = new Option("Yes, with Scribe (extra charge $$$)", 2);
        }
        else gimme("transcribeContainer").style.display = "none";
    }
}

// For PC/CT form to show/hide host exists based on setting of waiting room (without_host) param
var WR = {
    inited:false,

    init:function() {
        // all required fields available to DOM? otherwise bail
        if ( gimme("hostExitsContainer") == undefined || gimme("without_host") == undefined ) return; 

        WR.inited = true;
        gimme("without_host").onchange = function() { WR.parse(); };
        WR.parse();
    },
    parse:function() {
        if ( !WR.inited ) return;

        var x;
        var woHost = gimme("without_host");

        if ( gimme("is_spontaneous") == undefined ) x = ( woHost.value == 1 ) ? true : false;
        else  x = ( woHost.value == 1 && gimme("is_spontaneous").value == 0 ) ? true : false;

        gimme("hostExitsContainer").style.display = ( x ) ? "none" : "block";
    }
}

/* WebShare popup related class */
var WS = {
    inited:false,
    timer:false,
    ws_win:false,

    // for forms with webshare_only checkbox
    init:function() {
        var ws = gimme("webshare_only");

        // the form may not even have features, in which case don't worry
        if ( ws == undefined || gimme("WSFeaturesControl") == undefined ) return; 

        WS.inited = true;
        WS.parseWS();
    },

    // for forms with webshare_only selection
    parseWS:function() {
        if ( !WS.inited ) return;

        var nocallACP = ( arguments[0] != undefined ) ? arguments[0] : false;

        var ws = gimme("webshare_only");

        var disp = ( ws.value == 1 ) ? 'none' : 'block'; 
        var x = gimme("WSSpontaneous");

        if ( x != undefined ) x.style.display    = disp 
        gimme("WSFeaturesControl").style.display = disp;

        if ( ws.value == 2 ) gimme("acpContainer").style.display = "none";
        else if ( !nocallACP ) ACP.parse(true);
    },

    // opens the webshare popup control and tries to init the session
    openWebshare:function(pcid, is_host) {
        var url = '/WebShare/ws/' + pcid;

        var end_link = '';
        var sv_link  = 'If the Java applet does not load in 60 seconds, use our <a href="#" onclick="return doSureView();" title="If the Java applet fails to load, click here to launch the HTML based viewer.">HTML viewer</a>.';
        var add_msg  = "If a pop-up window appears asking for permission to run the Java application, please click RUN or ACCEPT.";
        var font     = 'font-family: Arial, sans-serif;';

        WS.ws_win = window.open("", "ZipDx_WebShare", "height=665px,width=600px,resizable=yes,scrollbars=yes,location=yes"); 

        var ePen = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ';
        ePen += '"http://www.w3.org/TR/html4/loose.dtd"><html><head>';
        ePen += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript">';

        ePen += 'function $(el) { return document.getElementById(el);}; ';
        ePen += 'function maxWin(w) { w.moveTo(0,0); w.resizeTo(screen.availWidth,screen.availHeight);}; ';
        ePen += 'function showSvLinkDelay() { setTimeout("$(\'msg\').style.display=\'block\'", 5000);}; ';
        ePen += 'function doSureView() { maxWin(window); window.location.href="' +url+ '?html=1"; return false;};';

        if ( is_host ) {
            end_link = '<a href="#" onclick="return cleanupSession();" id="endWS" title="Click this to end this WebShare session for everybody.">End WebShare</a>';
            ePen += 'function goDots() { if ( $("dots").innerHTML == "..." ) $("dots").innerHTML = ".&nbsp&nbsp;"; ';
            ePen += 'else if ($("dots").innerHTML == "..&nbsp;" ) $("dots").innerHTML = "..."; ';
            ePen += 'else $("dots").innerHTML = "..&nbsp;";}; ';
            ePen += 'function cleanupSession() { if ( !confirm("End WebShare for all Participants?") ) { return false; }; ';
            ePen += 'var endurl = "/WebShare/end/' + pcid + '"; if ( window.opener && !window.opener.closed ) { ';
            ePen += 'window.opener.location.href = endurl; } else { var nwh = window.open(endurl, "zipdx"); ';
            ePen += 'this.window.focus(); maxWin(nwh);}; $("sm").style.display = "none"; ';
            ePen += '$("msg").innerHTML = "<br><br>Please Wait while WebShare Session ends<span id=' + "'dots'" + '>...</span>"; ';
            ePen += '$("msg").style.display="block"; setInterval("goDots()", 500); ';
            ePen += '$("ifr").style.display = "none"; setTimeout("window.close()", 5000); return false;};'; 
        }
        else {
            add_msg += "<br><br>If the host's screen image does not fit in your viewer window, look for the Actual Size button in the upper left, and click it to change to Fit In Window.";
        }

        var title = gimme("ipc" + pcid).innerHTML.replace(/<sup .*$/, '').substr(0, 30);

        ePen += '</script><title>' + title + ' - ZipDX WebShare</title>';
        ePen += '<style type="text/css">body {margin:0; ' + font + '} ';
        ePen += 'td.fill {' + font + 'background:url(/img/wsfill.png);} ';
        ePen += 'div#msg {font-weight: bold; font-size: 14px; text-align: center; display: none;} ';
        ePen += '#ifr {border:0; width:99%; height:500px; overflow-y: hidden; margin-left: 5px;} ';
        ePen += 'a#endWS {color: #fff; display: none; background-color: #111; padding: 5px; text-decoration: none; border: 1px solid #111; position: absolute; right: 5px; top: 29px; -moz-border-radius: 12px; -khtml-border-radius: 12px;} ';
        ePen += 'a#endWS:hover {background-color: #747274; border: 1px solid #444; border-bottom:0;}';
        ePen += 'div#sm {font-size: 11px; margin: 5px;display:none;}</style></head><body>';

        ePen += '<table cellpadding="0" cellspacing="0"><tr><td><img src="/img/wslogo.png"></td>';
        ePen += '<td width="100%" align="right" valign="middle" class="fill">' + end_link + '</td></tr></table>';

        ePen += '<div id="msg">' + sv_link + '</div><iframe id="ifr" src="' + url + '" scrolling="no" frameborder="0"></iframe>';
        ePen += '<div id="sm">' + add_msg + ' <a href="#" onclick="$(\'sm\').style.display=\'none\';return false;">OK</a></div>';
        ePen += '</body></html>';

        WS.ws_win.document.open();
        WS.ws_win.document.write(ePen);
        WS.ws_win.document.close();

        WS.ws_win.focus();

        return false;
    },

    // home controller end link tries to close the popup box
    end:function() {
        // this page might not be the same page that opened the popup, so recapture
        if ( !WS.ws_win ) WS.ws_win = window.open('', "ZipDx_WebShare", "height=1px,width=1px"); 
        WS.ws_win.close();        
        return true;
    }
}

/** AJAX object
*
* Usage example:
* The callback function:
* function test_ajax2(txt) { alert(txt) }
*
* The calling function:
* function test_ajax() {
*   var url="/test.php"
*   var data="u=5"
*   var method="post"
*   var callback="test_ajax2"
*   AJAX.ajaxInit(url, data, method, callback)
* }
*/
var AJAX = {
    http_request:false,
    ajax_err:false,

    init:function() {
        http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
        } 
        else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if ( !http_request ) {
            alert("Giving up :( Cannot create an XMLHTTP instance");
            return true;
        }
    },

    ajaxInit:function(url, data, method, callback) {
        ajax_err = AJAX.init();

        AJAX.callback = callback;
        if ( method != 'post' ) {
            // bust caches
            var bc = new Date();

            method = 'get';
            url += ( data ) ? '?' + data + '&' + bc.getTime() : '?' + bc.getTime();
            data = null;
        }

        if ( !ajax_err ) {
            http_request.onreadystatechange = AJAX.postSubmit;
            http_request.open(method, url, true);
            http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            http_request.setRequestHeader("Is_Ajax", "1");
            http_request.send(data);
        }
    },

    postSubmit:function() {
        if ( http_request.readyState == 4 ) {
            if ( http_request.status == 200 ) {
                eval(AJAX.callback + "(http_request.responseText)");
            } 
            else if ( http_request.status != 0 ) {
                alert("There was a problem with the request. (Status: " + http_request.status + ")");
            }
        }
    }
}

// callback used by our js calendar popup
var ZXCal = {
    now:false,

    init:function() {
        var ts = document.createElement("img");
        ts.src = "/img/cal-icon.png";
        ts.id = "calTrigger";
        ts.title = "calendar";
        ts.style.verticalAlign = "middle";

        var x = document.getElementsByName("start_time[A]")[0];
        x.parentNode.insertBefore(ts, x);

        gimme("start_time").parentNode.id = "start_time_group";

        var z = document.createElement("span");
        z.innerHTML = '<a href="#" style="font-weight: normal; font-size: 11px;" onclick="return ZXCal.setNow();">Set start time to now</a>';
        gimme("start_time_group").appendChild(z);
    },

    setNow:function() {
        var x = document.getElementsByName("start_time[Y]")[0];
        x.value = ZXCal.now.substr(0, 4);

        x = document.getElementsByName("start_time[M]")[0];
        var y = parseInt(ZXCal.now.substr(5, 2), 10);
        x.value = y;

        x = document.getElementsByName("start_time[d]")[0];
        var y = parseInt(ZXCal.now.substr(8, 2), 10);
        x.value = y;

        x = document.getElementsByName("start_time[h]")[0];
        var y = parseInt(ZXCal.now.substr(11, 2), 10);
        var m = "AM";
        if ( y > 11 ) {
            if ( y > 12 ) y -= 12;
            m = "PM";
        }
        else if ( y == 0 ) y = 12; 
        x.value = y;

        x = document.getElementsByName("start_time[A]")[0];
        x.value = m;

        x = document.getElementsByName("start_time[i]")[0];
        var y = parseInt(ZXCal.now.substr(14, 2), 10);
        x.value = y;

        return false;
    },

    dateChanger:function(e, x) {
        for (i = 0; i < e.length; i++) {
            if ( x == e[i].value ) {
                e.selectedIndex = i;
                return;
            }
        }
    },

    // used to update date select with js calendar
    dateChanged:function(c) {
        if ( c.dateClicked )  {
            var f = document.PCForm;

            var e = f.elements['start_time[Y]'];
            ZXCal.dateChanger(e, c.date.getFullYear());

            var e = f.elements['start_time[M]'];
            ZXCal.dateChanger(e, c.date.getMonth() + 1);

            var e = f.elements['start_time[d]'];
            ZXCal.dateChanger(e, c.date.getDate());

            c.callCloseHandler();
        }
    }
}

// generic cookie reader
var readCookie = function(name) {
    var nameEQ = name + '=';
    var ca = document.cookie.split(';');
    var c = '';

    for (var i=0; i<ca.length; i++) {
        c = ca[i];
        while ( c.charAt(0) == ' ' ) c = c.substring(1, c.length);
        if ( c.indexOf(nameEQ) == 0 ) return c.substring(nameEQ.length, c.length);
    }

    return null;
}

// showHideCollapsingDivs
var SHCD = {
    things:{'collapseFeatures':0, 'collapseCT':1, 'collapseAC':0, 'collapseRU':0, 'collapsePH':0, 'collapsePH2':0},
    menus:{'collapsePH':{'show':'show advanced preferences',
                         'hide':'hide advanced preferences'},
           'collapsePH2':{'show':'show advanced preferences',
                         'hide':'hide advanced preferences'}
          },

    init:function() {
        var gotCookie = false

        for ( var i in SHCD.things ) {
            cF = gimme(i)

            if ( cF != undefined ) {
            // load the cookie if not done yet
                if ( !gotCookie ) {
                    SHCD.getPrefsFromCookie()
                    gotCookie = true
                }

                cFVal = SHCD.things[i];

                if ( cFVal == 1 ) {
                    cFVal = 'block'
                    cFL = '(hide)'
                    if ( SHCD.menus[i] != undefined ) cFL = SHCD.menus[i]['hide'];

                }
                else {
                    cFVal = 'none'
                    cFL = '(show)'
                    if ( SHCD.menus[i] != undefined ) cFL = SHCD.menus[i]['show'];
                }

                cF.style.display = cFVal
                cFH = gimme(i + 'Head')
                cFH.innerHTML += '&nbsp;&nbsp;<a href="#" style="float: none; display: inline;" id="' + i + 'Link" onclick="return SHCD.divToggle(\'' + i + '\');">' + cFL + '</a>'
            }
        }
    },

    divToggle:function(x) {
        d = gimme(x);
        y = x + 'Link';
        l = gimme(y);

        if ( d.style.display == 'block' ) {
            d.style.display = 'none';
            l.innerHTML = ( SHCD.menus[x] != undefined ) ? SHCD.menus[x]['show'] : '(show)';
            SHCD.things[x] = 0;
        }
        else {
            d.style.display = 'block';
            l.innerHTML = ( SHCD.menus[x] != undefined ) ? SHCD.menus[x]['hide'] : '(hide)';
            SHCD.things[x] = 1;
        }

        SHCD.handleCookieStore();
        return false;
    },

    getPrefsFromCookie:function() {
        var c = readCookie('mPref');

        if ( c == null ) return;

        var data = c.split('^');
      
        for( var j=0; j < data.length; j++) {
            if ( data[j].length > 0 ) {
                k = data[j].split(':');
                if ( SHCD.things[k[0]] != undefined ) SHCD.things[k[0]] = k[1];
            }
        }
    },

    handleCookieStore:function(e) {
        var cData = '';

        var x = 0;
        for (var i in SHCD.things) {
            if ( x > 0 ) cData += '^';
            cData += i + ':' + SHCD.things[i];
            ++x;
        }

        document.cookie = 'mPref=' + cData + '; expires=Sun, 17 May 2037 00:00:00 UTC; path=/';
    }
}

var faqToggler = {
    init:function() {
        var faqp = document.getElementsByTagName('p');

        for ( var i=0; i<faqp.length; ++i ) {
            var item = faqp[i];
            if ( item.id != undefined && item.id.indexOf('faq') == 0 ) {
                item.className = 'faq';
                item.style.display = 'none';
                if ( gimme(item.id + "Link") != undefined ) {
                    gimme(item.id + "Link").href = "#";
                    gimme(item.id + "Link").onclick = function() { return faqToggler.go(item.id); };
                }
            }
        }
    },

    go:function(id) {
        gimme(id).style.display = ( gimme(id).style.display == 'none' ) ? "block" : "none";

        return false;
    }
}

var API = {
    reset:function(x) {
        if ( confirm('Resetting the API key will immediately disable the existing key. All subsequent API access will require the new key.') ) {
            AJAX.ajaxInit('/Ajax/Account/' + x, null, 'get', 'API.ajaxCallback');
        }

        return false;
    },

    ajaxCallback:function(txt) {
        if ( txt ) gimme('apikey').innerHTML = txt;
    }
}

var WK = {
    timerId:null,
    wk:'',
    url:'/Ajax/Webkey/',
    search:'webkey',
    is_new:false,

    fetch:function(x) {
        if ( WK.timerId )  clearInterval(WK.timerId);

        WK.wk = x.value;
        if ( WK.wk == '' ) {
            gimme('wkDisplay').style.display = 'none';
            return;
        }

        gimme('wkDisplay').style.display = 'block';
        gimme('wkDisplay').innerHTML     = 'searching for ' + WK.search + ' details...';
        WK.timerId = setTimeout('WK.ajaxStart()', 2000);
    },

    ajaxStart:function() {
        if ( WK.is_new !== false ) WK.wk += ';' + WK.is_new; 

        AJAX.ajaxInit(WK.url + WK.wk, null, 'get', 'WK.ajaxCallback');
    },

    ajaxCallback:function(txt) {
        gimme('wkDisplay').style.display = 'block';
        gimme('wkDisplay').innerHTML = txt;

        if ( gimme("ccNotReq") == undefined ) return;
        gimme("ccNotReq").style.display = ( txt.indexOf("Does NOT require a credit card") != -1 ) ? 'block' : 'none';
    }
}

var JOKER = {
    init:function() {
        var x = gimme('ic');
        if ( x == undefined ) return;
        x.innerHTML = '<input type="text" name="importantcode2" value="asdf" maxlength="4" size="2" class="importantcode">';
    }
}

// set callerid
var CID = {
    incr:null,

    go:function(i, phoneid) {
        CID.incr = i;
        AJAX.ajaxInit('/Ajax/Phone/' + phoneid, null, 'get', 'CID.ajaxCallback');
        return false;
    },

    ajaxCallback:function(txt) {
        gimme('cid' + CID.incr).innerHTML = txt;

        for (var i=1; i<25; ++i) {
            if ( gimme('cid' + i) == undefined ) break;
            if ( i == CID.incr ) continue;
            
            var x = gimme('cid' + i);
            var phoneid = x.className.substr(3);

            x.innerHTML = '<a href="#" onclick="return CID.go(' + i + ',' + phoneid + ')">Select</a>';
        }

        CID.incr = null;
    }
}

// change password for a zip registered sip
var ZRS = {
    phoneid:null,

    go:function(phoneid) {
        if ( !confirm('Are you sure you want to change your SIP client password?') ) return false;

        ZRS.phoneid = phoneid;
        AJAX.ajaxInit('/Ajax/Phone/pw:' + phoneid, null, 'get', 'ZRS.ajaxCallback');
        return false;
    },

    ajaxCallback:function(txt) {
        gimme('zrs' + ZRS.phoneid).innerHTML = txt;
        ZRS.phoneid = null;
    }
}

var SEC = {
    polling:false,
    init:function() {
        gimme('email').onblur = function() { SEC.ajax(); }
        SEC.ajax();
    },
    ajax:function() {
        var em = gimme('email').value;
        if ( !em || SEC.polling == em ) return;
        if ( em.match(/^(?:[A-Z0-9\+#_\-']+\.?)+[A-Z0-9\+#_\-']@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$/i) ) {
            SEC.polling = em;
            AJAX.ajaxInit('/Ajax/Login/', 'e=' + em, 'post', 'SEC.ajaxCallback');
        }        
    },
    ajaxCallback:function(bool) {
        gimme('securidBox').style.display = ( bool === '1' ) ? 'block' : 'none';
    }
}

var LoginHelp = {
    init:function() {
        var lh = gimme('loginHelp');
        if ( lh == undefined ) return;

        var toggleLink = '<a href="#" onclick="return LoginHelp.toggleHelp();">';
        lh.innerHTML = '| ' + toggleLink + 'Login Help</a>';

        var lr = gimme('step1');

        var cntnr = document.createElement('div');
        cntnr.style.position = "relative";
        cntnr.style.width = "0px";

        var theDiv = document.createElement('div');
        theDiv.className = "faq shadow";
        theDiv.id = "loginHelpDiv";
        theDiv.style.display = "none";

        theDiv.innerHTML = '<b>Login Help</b><br>When you are invited to a ZipDX conference, ZipDX sends you an ';
        theDiv.innerHTML += 'email containing a 7-digit PIN. Log in here using your email address and that PIN. ';
        theDiv.innerHTML += 'Then you can join WebSharing and access other ZipDX features. If you have changed ';
        theDiv.innerHTML += 'your PIN or selected a different password, use that instead. If you did not receive ';
        theDiv.innerHTML += 'a ZipDX PIN, your meeting host provided you with a six-digit conference code; click ';
        theDiv.innerHTML += '"<i>Join using a six-digit conference code</i>". If you forgot your ZipDX PIN, click ';
        theDiv.innerHTML += '"<i>Forgot Password?</i>".&nbsp;&nbsp;' + toggleLink + 'close</a>';

        lr.parentNode.insertBefore(cntnr, lr.nextSibling);
        cntnr.appendChild(theDiv);
    },

    toggleHelp:function() {
        var lhd = gimme("loginHelpDiv");
        lhd.style.display = ( lhd.style.display == 'none' ) ? 'block' : 'none';

        // collapse numbers before displaying login help to avoid confusion
        gimme('faqNumbers').style.display = 'none';

        return false;
    }
}

var IBOX = {
    ShowF:0,
    HideCount:0,
    infoInit:false,
    lastContent:'',

    //function to hide info divs
    hideInfo:function(e) {
        if ( IBOX.infoInit ) return

        var dolisten  = false
        var pageSpans = document.getElementsByTagName("span"); 

        for (i=0; i<pageSpans.length; i++) { 
            if ( pageSpans[i].className == 'info' ) { 
                var t = pageSpans[i]
                t.style.display='none'; 
                var l = document.createElement('div')
                l.style.display = 'inline';

                var lbl = ( t.title ) ? t.title : '(Explain)';
                l.innerHTML = '&nbsp;&nbsp;<a href="#" class="infobox_link" onclick="return false" onmouseover="IBOX.ShowFloat(\'' + t.id + '\')" onmouseout="IBOX.HideFloat()" id="' + t.id + 'Link' + '">' + lbl + '</a>';

                t.parentNode.insertBefore(l, t)
                dolisten = true
            }
        }

        if ( dolisten ) {
            if (document.addEventListener) document.addEventListener('mousemove', IBOX.getMouseXY, false);  
            else if (document.attachEvent) document.attachEvent('onmousemove', IBOX.getMouseXY);
        }

        var infobox = gimme('infobox');
        infobox.style.opacity = .85;
        infobox.style.filter = 'alpha(opacity=85)';

        IBOX.infoInit = true

        return true
    },

    // Main function to retrieve mouse x-y pos
    getMouseXY:function(e) {
        if ( document.all ) { // grab the x-y pos if browser is IE
            PosX = event.clientX + document.documentElement.scrollLeft
            PosY = event.clientY + document.documentElement.scrollTop
        } else {  // grab the x-y pos if browser is NS
            PosX = e.pageX
            PosY = e.pageY
        }

        // catch possible negative values in NS4
        if (PosX < 0) PosX = 0;
        if (PosY < 0) PosY = 0;  

        if ( IBOX.ShowF == 1 ) {
            IBOX.HideCount = 0;

            offsetX = 20
            if ( PosX + 270 > posRight() ) offsetX = -270;

            offsetY = -50
            if ( PosY - posTop() < 60 )    offsetY = 0;

            var infobox = gimme('infobox');
            infobox.style.left = PosX + offsetX + 'px';
            infobox.style.top = PosY + offsetY + 'px';
        }
        else {
            IBOX.HideCount = IBOX.HideCount + 1;

            if ( IBOX.HideCount >= 5 ) {
                gimme('infobox').style.left = '-1000px';
                IBOX.HideCount = 0;
            }
        }

        return true
    },

    ShowFloat:function(Content) {
        IBOX.ShowF = 1;

        if ( Content != IBOX.lastContent ) {
            if ( IBOX.lastContent ) gimme(IBOX.lastContent).innerHTML = gimme('iContent').innerHTML;
            gimme('iContent').innerHTML = gimme(Content).innerHTML.replace(/^<br>/i, "");
            gimme(Content).innerHTML    = '';

            IBOX.lastContent = Content
        }
    },

    HideFloat:function() { 
        IBOX.ShowF = 0; 
    }
}

var BOOT = {
    _timer:false,

    init:function() {
        // kill the timer for safari
        if ( BOOT._timer ) clearInterval(BOOT._timer);
        SHCD.init();
        if ( gimme("participant_emails") != undefined ) WEE.initParticipantOverlay();
        IBOX.hideInfo();
        if ( gimme("securidBox") != undefined ) SEC.init();
        try { PASS.init(); } catch (e) {}
        JOKER.init();
    },

    strap:function() {
        /* for Safari */
        if (/WebKit/i.test(navigator.userAgent)) { // sniff
            BOOT._timer = setInterval(function() {
                if (/loaded|complete/.test(document.readyState)) {
                    BOOT.init(); // call the onload handler
                }
            }, 10);
        }

        /* for Mozilla/Opera9 */
        else if (document.addEventListener) document.addEventListener("DOMContentLoaded", BOOT.init, false);

        /* for other browsers */
        else window.onload = BOOT.init;
    }
}

BOOT.strap();
