/**
 * Routines for interacting with Instant Service.
 *
 * Department codes:
 *
 *                  Anyone:  Default
 *                   Sales:  19763
 *       Technical Support:  19764
 *        Customer Service:  19765
 *
 * 
 * 
 * 
 * 
 * @copyright   Silicon Mechanics
 * @license     LGPL
 *
 * @package     SiMech
 * @subpackage  Javascript
 *
/**/

//window.dev_domain = true;

// Eww.
    if(typeof(sc3) == 'undefined')
        sc3 = null;

    function open_chat_window(domain) {
    // If we're on a page with a system configurator, we need to cause a post...
        update_button = $('chat-update-button');
        if(sc3 && update_button) {
            update_button.click();
        } // end if
        window.open('https://'
                    + domain
                    + '/chat.php',
                    'simechchatclient',
                    'width=500,height=400,scrollbars=1');
        return false;
    } // end open_chat_window

    function chat_available() {
        $('chat_available').style.display = '';
		document.fire('chat:ready');
    }

    function chat_offline() {
        $('chat_offline').style.display = '';
    }

    function handle_enter() {
        if ($('password_box').style.display == '') {
            ajax_login();
        }
    }

    function ajax_login() {
    // Easy checks
        if ($F('email').trim().length < 1) {
            alert('Please enter your email address.');
            return false;
        }
        if ($F('password').trim().length < 1) {
            alert('Please enter your password.');
            return false;
        }
    // Send the login information
        var req = new Ajax.Request('/chat.php?ajax',
                        {
                            parameters: 'login=1'
                                        +'&email='+encodeURIComponent($F('email'))
                                        +'&pass='+encodeURIComponent($F('password')),
                                method: 'post',
                          asynchronous: false
                        }
                  );
        var user = req.transport.responseText.evalJSON();
    // Success!
        if (user.login) {
        // Reset the password field to blank, for good measure
            $('password').value = '';
        // Update the page display fields
            handle_email_change(user);
        }
    // Something that should never happen.
        else if (user.bad.email || !user.bad.pass || user.err.length < 1) {
            alert("Something unexpected has happened on the server.\n"
                 +"Please reload this page and try again.");
        }
    // Any errors?
        else {
            alert(user.err.join("\n"));
            set_selection($('password'), 0, -1);
        }
    }

    function handle_email_keyup() {
        if ($('email').last_value == $F('email')) {
            return;
        }
        if ($('email').change_timeout) {
            clearTimeout($('email').change_timeout);
        }
        $('email').change_timeout = setTimeout(handle_email_change, 250);
        $('email').last_value     = $F('email')
        $('email').cursor_start   = get_cursor_start($('email'));
        $('email').cursor_end     = get_cursor_end($('email'));
    }

    function handle_email_keydown() {
        if ($('email').change_timeout) {
            clearTimeout($('email').change_timeout);
        }
    }

    function handle_email_blur() {
        if ($('email').change_timeout) {
            clearTimeout($('email').change_timeout);
        }
        $('email').cursor_start = null;
        $('email').cursor_end   = null;
    }

    function handle_email_change(user) {
    // Reset some hidden fields
        $('optionaldata').value = '';  // Company Name
        $('account_url').value  = '';  // Account URL
        $('customer_url').value = '';  // Customer URL
        $('logged_in').value    = '0'; // Logged in
    // Unlock certain fields, in case they were disabled.
        $('email').readonly = false;
        $('email').removeClassName('sc_disabled');
        $('fname').readonly = false;
        $('fname').removeClassName('sc_disabled');
        $('lname').readonly = false;
        $('lname').removeClassName('sc_disabled');
        $('phone').readonly = false;
        $('phone').removeClassName('sc_disabled');
        $('optional_phone').style.display = '';
    // Ignore empty data, but make sure to reset the display mode accordingly.
        if ($F('email').trim().length < 1) {
            set_display_mode();
            return;
        }
    // Look up the customer, if necessary (check for "email" instead of blank
    // because the variable might be "event", depending on how this function is
    // called).
        if (!user || !user.email) {
            var req = new Ajax.Request('/chat.php?ajax',
                            {
                                parameters: 'check_email=1'
                                            +'&email='+encodeURIComponent($F('email')),
                                    method: 'post',
                              asynchronous: false
                            }
                      );
            user = req.transport.responseText.evalJSON();
        }
    // Unknown user?
        if (!user || !user.email) {
            set_display_mode();
        }
    // Logged in?
        else if (user.login) {
            set_display_mode('user');
        // Lock down the normally-editable fields, since we now have
        // trustworthy data.
            $('email').readonly = true;
            $('email').addClassName('sc_disabled');
            $('fname').readonly = true;
            $('fname').addClassName('sc_disabled');
            $('lname').readonly = true;
            $('lname').addClassName('sc_disabled');
            $('phone').readonly = true;
            $('phone').addClassName('sc_disabled');
            $('optional_phone').style.display = 'none';
        // Set the known values
            $('email').value = user.email;
            $('fname').value = user.name;
            $('lname').value = user.surname;
            $('phone').value = user.phone;
        // And some additional hidden info to help the chat agents
            $('optionaldata').value = user.company_name;
            $('account_url').value  = user.account_url;
            $('customer_url').value = user.customer_url;
            $('logged_in').value    = user.login;
            $('item_id').value      = user.item_id;
            $('config_id').value    = user.config_id;
        }
    // Show the login form
        else {
            set_display_mode('login');
        }
    // Refocus, if necessary
        if ($('email').cursor_start != null || $('email').cursor_end != null) {
            set_selection($('email'), $('email').cursor_start, $('email').cursor_end);
        }
        else if ($('password_box').style.display == '') {
            set_selection($('password'), 0, -1);
        }
    }

    function set_display_mode(mode) {
        if (mode == 'login') {
            $('password_box').style.display = '';
            $('start_chat').style.display   = 'none';
        }
        else if (mode == 'user') {
            $('password_box').style.display = 'none';
            $('start_chat').style.display   = '';
        }
        else {
            $('password_box').style.display = 'none';
            $('start_chat').style.display   = '';
        }
    }

    function change_chat_req(which) {
        handle_chat_req_change(true);
    }

    function handle_chat_req_change(focus, sync_ajax) {
        dept = 'sales';
        $('chat_reason').value = 'General Sales';
        return dept;
    }

    function submit_chat(dept) {
    // If no user fields are shown, just return
        if ($('user_fields').style.display == 'none')
            return;
    // Make sure the name fields have been filled in
        if ($F('fname').trim().length < 2) {
            alert('Please provide your first name.');
            return;
        }
        if ($F('lname').trim().length < 2) {
            alert('Please provide your last name.');
            return;
        }
    // Make sure that a chat-reason has been selected
        if (!handle_chat_req_change(false, true)) {
            alert('Please tell us what you would like to chat about.');
            return;
        }
    // Submit
        submit_form('di', '19763', 'chat_form');

    }

