var departments = {

    "Billing": {
        use_new_chat: true,
        schedule: [null, "8-19", "8-19", "8-19", "8-19", "8-19", null],
        class_selector: "billing",
        id: 4
    },
    "Business Account Management": {
        use_new_chat: true,
        schedule: [null, "8:30-17", "8:30-17", "8:30-17", "8:30-17", "8:30-17", null],
        class_selector: "bus_acct_manage",
        id: 6
    },
    "Business Sales": {
        use_new_chat: true,
        schedule: [null, "8:30-17", "8:30-17", "8:30-17", "8:30-17", "8:30-17", null],
        class_selector: "bus_sales",
        id: 7
     },
    "Business Technical Support": {
        use_new_chat: true,
        schedule: ["0-24", "0-24", "0-24", "0-24", "0-24", "0-24", "0-24"],
        class_selector: "bus_tech_support",
        id: 1
    },
    "Residential Sales": {
        use_new_chat: true,
        schedule: [null, "8:30-17", "8:30-17", "8:30-17", "8:30-17", "8:30-17", null],
        class_selector: "res_sales",
        id: 2
    },
    "Residential Technical Support": {
        use_new_chat: true,
        schedule: ["0-24", "0-24", "0-24", "0-24", "0-24", "0-24", "0-24"],
        class_selector: "res_tech_support",
        id: 1
    }
};

var aliases = {
    "Accounting":      "Billing",
    "Residential":     "Residential Sales",
    "Helpdesk":        "Residential Technical Support",
    "Corp Support":    "Business Technical Support",
    "Account Support": "Business Account Support"
};

var department_status = {};
var department_status_last_load = null;

var ChatBox  = null;

$(document).ready(function () {

    /*
    Find and subvert a link with id 'live_chat'.
        * Replace actual href with # so clicks no longer redirect.
        * Set link class to reflect department availability.
            (chat is available if any department is available)
        * Add "online" or "offline" to link content.
        * Register a new click event that,
            * pulls the original href location into a Boxy popup window.
        * Load a hash of department statuses with /myexeculink/chat/departments
          into department_status.
    */
    
    $("a.live_chat").each(function () {

        var href  = $(this).attr("href"); if ( href != '#' ) { 
        var title = $(this).attr("title");

            $(this).attr("href", "#");
            $(this).click(function () {

                jQuery.ajax({url: href, dataType: "html", complete: function (jqXHR, textStatus) {
//              jQuery.ajax(href, { complete: function (jqXHR, textStatus) { // doesn't work in jquery.1.4.x

                    var content = $("<div>").append(jqXHR.responseText).find("#body");

                    ChatBox = new Boxy(content);
                    ChatBox.center("x").moveTo(null, 32);

                    // disable all options until statuses have been loaded.
                    $(content).find("input.department").each(function () {

                        $(this).attr("disabled", true);
                    });

                    var close = document.createElement("input");  
                        close.setAttribute("id", "chat_close_button");
                        close.setAttribute("type", "button");
                        close.setAttribute("value", "Loading...");
                      $(close).click(function () {
                      
                          $(".boxy-wrapper").fadeOut(function () {ChatBox.unload()});
                      });

                    $(content).append(close); 
                    $("#body").css("font-size", "1.00em");

                    load_department_status(function () {

                        close.setAttribute("value", "Cancel");
                    
                        // re-enable all radio options
                        $(content).find("input.department").each(function () {

                            $(this).attr("disabled", false);
                        });
                    });
                }});
            });
        }

        return;
    });
});

function load_department_status (on_success) {

    jQuery.getJSON("/shared/departments", function (data) {

        $.each(data, function (k, v) {

            var online = v == 'online' ? true : false;

            //if ( departments[k].use_new_chat ) {

                // If we're using the new chat interface for this department,
                // we need to determine availability by the current time, 
                // rather than the status returned by the server (which is 
                // getting its information from the old chat interface.

                online = is_department_available_by_time(k);
            //}

            department_status[k] = online;

            var li = $("li."+departments[k].class_selector);
                li.addClass("icon-right");
                li.addClass(online ? "chat" : "no_chat");
        });

        department_status_last_load = new Date();

        if ( on_success ) on_success();
    });        
}

function launch_chat () {

    var party      = $("#party_name").val();
    var department = $("#selected_department").val();

    if ( ! party      ) return alert("Please provide your name to start chatting.");
    if ( ! department ) return alert("Please select a department.");

    if ( ChatBox ) { ChatBox.unload(); }

    var department_id = departments[department].id;

    if (departments[department].use_new_chat) {

        return launch_new_chat(department_id, party);
    }

    return launch_old_chat(department_id, party);
}

function launch_new_chat (department, party_name) {

    var url = "http://wiretap.lan.execulink.com/i3root/member_chat.html";
        url = url + "?name=" + party_name + "&department=" + department;
        url = url + "&u=" + document.location;

    window.open(url, "Execulink_Member_Chat", 'height=360,width=400,scrollbars=0,location=no');
    return;
}

function launch_old_chat (department, party_name) {

    var url = "http://livechat.golden.net/request.php?l=phplive&x=1&action=request";
        url = url + "&from_screen_name=" + party_name + "&deptid=" + department;

    window.open(url, "Execulink_Member_Chat", 'height=360,width=400,scrollbars=0,location=no');
    return;
}

function select_department ( option ) {

    var value = $(option).val();

     $("#chat_options").hide();
    $("#email_options").hide();
    $("#selected_department").val(value); 

    var available = is_department_available(value);
    $(( available ? "#chat" : "#email")+"_options").fadeIn();

    return;
}

function is_department_available ( name ) {

    if ( departments[name].use_new_chat ) {

        return is_department_available_by_time(name);
    }

    return is_department_available_for_real(name);
}

function is_department_available_for_real (name) {

    return department_status[name];
}

function is_department_available_by_time ( name ) {

    var alias  = aliases[name];
    if (alias != null ) name = alias;

    var now        = new Date;
    var dow_index  = now.getDay();

    var  schedule = departments[name].schedule;
    if (!schedule) return;

    var  for_day = schedule[dow_index];
    if (!for_day) return;

    var times = for_day.split("-"); 

    var start_hour = times[0].split(":");
    var start = new Date;
        start.setHours(start_hour[0]);
        start.setMinutes(start_hour[1] || 0);
        start.setSeconds(0);

    var end_hour = times[1].split(":");
    var end_min = end_hour[1] || 0;
    // five minutes before close, unless 24 support
    if (end_hour[0] != "24") end_min = end_min - 5;
    var end = new Date;
        end.setHours(end_hour[0]);
        end.setMinutes(end_min);
        end.setSeconds(0);

    if ( now.getTime() > start.getTime() && now.getTime() < end.getTime() ) {

        return true;
    }

    return false;
}

function validate_email () {

    var from_address = $("#from_address").val();

    if ( ! from_address ) {

        alert("Please provide your email address.");
        return false;
    }

    if ( ! from_address.match(/\w@\w/) ) { 
        // pretty weak validation, but it will work for now.
        alert("Please provide a valid email address.");
        return false;
    }

    if ( ! $("#subject").val() ) {

        alert("Please provide a subject.");
        return false;
    }

    if ( ! $("#email_message").val() ) {

        alert("Please provide your message.");
        return false;
    }

    return true;
}

