String.prototype.localize = function() {
    var s = LocalizedStrings[this];
    return ( s ) ? s : this;
}

var CURRENT_FILTER_ROOM_PAGE = 0;
var arrSelectedFilterRooms = [];

// Patient's tooltip
function setVisibility(caller, called, visibility)
{
    var patient = $(caller);
    var patientPosition = patient.cumulativeOffset();
    var menu = $(called);

    if (visibility == 'none')
    {
        menu.style.display = visibility;
        return;
    }

    var patientWidth = 60;  // patient's DIV width in px
    var patientHeight = 77; // patient's DIV height in px
    var menuWidth = 150;    // window width in px
    var menuHeight = 50;    // window height in px

    // horizontal position
    if (patient.parentNode.id.toString() == 'depository')
    {
        menu.style.left = (patientPosition[0] - menuWidth) + "px";
        menu.style.position = "fixed";
    }
    else
    {
        menu.style.left = (patientPosition[0] + patientWidth) + "px";
        menu.style.position = "";
    }

    // vertical position
    menu.style.top = (patientPosition[1] + 10) + "px";

    menu.style.display = visibility;
    setTimeout("$('" + called + "').style.display='none'", 7000);
}
//----------------------------------------------------------------------------------------------------------------

function toggleFilterRoom(element, roomId)
{
    var elementClass = element.className;

    if (elementClass == "roomsNotSelected")
    {
        // select the element
        element.className = "roomsSelected";

        // add the element to the array
        if (arrSelectedFilterRooms.indexOf(roomId) == -1)
            arrSelectedFilterRooms.push(roomId);
    }
    else if (elementClass == "roomsSelected")
    {
        // unselect the element
        element.className = "roomsNotSelected";

        // remove the element from the array
        var index = arrSelectedFilterRooms.indexOf(roomId);
        if (index != -1)
            arrSelectedFilterRooms.splice(index, 1);
    }
    searchData();
}

function getFilterRoomsPageCount()
{
    var dblPageCount = FILTER_ROOM_ELEMENT_COUNT / FILTER_ROOM_PAGE_SIZE;
    var intPageCount = parseInt(dblPageCount);
    return (dblPageCount > intPageCount) ? intPageCount : intPageCount - 1;
}

function moveDown()
{
    if (CURRENT_FILTER_ROOM_PAGE == getFilterRoomsPageCount()) return;

    var segment = CURRENT_FILTER_ROOM_PAGE * FILTER_ROOM_PAGE_SIZE;

    // hide elements on the current page and show the next page
    for (var i = 0 + segment; i < FILTER_ROOM_PAGE_SIZE + segment; i++)
    {
        $("r-" + i).style.display = "none";

        var nextElementId = i + FILTER_ROOM_PAGE_SIZE;
        if (nextElementId < FILTER_ROOM_ELEMENT_COUNT)
        {
            $("r-" + nextElementId).style.display = "inline";
        }
    }
    CURRENT_FILTER_ROOM_PAGE++;
}

function moveUp()
{
    if (CURRENT_FILTER_ROOM_PAGE == 0) return;

    var segment = CURRENT_FILTER_ROOM_PAGE * FILTER_ROOM_PAGE_SIZE;

    // hide elements on the current page and show the next page
    for (var i = FILTER_ROOM_PAGE_SIZE + segment; i >= 0 + segment; i--)
    {
        if (i < FILTER_ROOM_ELEMENT_COUNT)
        {
            $("r-" + i).style.display = "none";
        }

        var nextElementId = i - FILTER_ROOM_PAGE_SIZE;
        $("r-" + nextElementId).style.display = "inline";

    }
    CURRENT_FILTER_ROOM_PAGE--;
}

function periodical()
{
    var url = "gui_check_pending.php?u=" + UNIT_ID;

    new Ajax.Request(url,
    {
        onSuccess: function(transport)
        {
            updatePending(transport.responseText.evalJSON(true));
        },

        onException: function(req, exception) {
            alert("Failed check pending".localize() + ":\n\n" + exception);
            window.location.reload();
        },

        onFailure: function(req) {
            alert("Failed check pending".localize() + ":\n\n" + req.statusText);
            window.location.reload();
        }
    });
}

function updatePending(patientArray)
{
    patientArray.each(function(patient) {
        if ($("p" + patient.patient_id) == null) // New unit patient
        {
            createTooltip(patient.patient_id, patient.ssn, patient.first_name, patient.last_name);
            patientOnBed(createPatient(patient.patient_id, false, false), $('depository'));
            createMenu(patient.patient_id, false);

            $("p" + patient.patient_id).appear({ duration: 1.0 });
        }
    });

    if (patientArray.size() > 0) // Sound alarm
    {
        Sound.play('images/alarm.mp3');
    }
}

function putPatientOnBed(patient, bed)
{
    if (GPARENT == null)
    {
        GPARENT = $("depository");
    }

    if (GPARENT.id.toString() != "depository")
    {
        Droppables.add(
            GPARENT.id,
            {
                accept: 'patient',
                hoverclass: 'patientAccept',
                onDrop: patientOnBed
            });
    }

    if (bed.id.toString() == "depository")
    {
        patient.style.left = '0px';
    }
    else
    {
        Droppables.remove(bed.id);
        patient.style.left = '30px';
    }

    patient.style.top = '0px';

    bed.appendChild(patient);
}

function patientOnBed(patient, bed)
{
    putPatientOnBed(patient, bed);
    updatePatient(patient, bed);
}

function updatePatient(patient, bed)
{
    var url = 'guiupdate.php?p=' + patient.id.substring(1) + '\&b=' + (bed.id.startsWith('b') ? bed.id.substring(1) : bed.id) + '\&u=' + UNIT_ID;
    createAjaxRequest(url, "Failed assignment".localize());
}

function confirmOrRejectPatient(patient, confirm)
{
    var url = "guiconfirm.php?p=" + patient + "\&u=" + UNIT_ID + "&c=" + (confirm == true ? 1 : 0);
    createAjaxRequest(url, "Failed confirm".localize());
}

function searchData()
{
    var url = "guifilter.php?u=" + UNIT_ID +
        "&r=" + arrSelectedFilterRooms +
        "&a=" + ($("ddlAge").value == -1 ? "" : $("ddlAge").value) +
        "&s=" + ($("ddlSex").value == -1 ? "" : $("ddlSex").value) +
        "&rt=" + ($("ddlRoomType").value == -1 ? "" : $("ddlRoomType").value) +
        "&bt=" + ($("ddlBedType").value == -1 ? "" : $("ddlBedType").value) +
        "&bs=" + ($("ddlBedStatus").value == -1 ? "" : $("ddlBedStatus").value);

    new Ajax.Request(url,
    {
        onSuccess: function(transport)
        {
            fillRooms(transport.responseText.evalJSON(true));
        }
    });
}

function hideAllRooms()
{
    var childList = $("mainContainer").childNodes;

    for (var i = 0; i < childList.length; i++)
    {
        if (childList[i].tagName == "DIV" && childList[i].id.toString() != "depository")
        {
            childList[i].style.display = "none";
        }
    }
}

function ClearAllFilters()
{
    var childList = $("filterRooms").childNodes;

    for (var i = 0; i < childList.length; i++)
    {
        if ((childList[i].tagName == "DIV") && (childList[i].className == "roomsSelected"))
        {
            childList[i].className = "roomsNotSelected";
        }
    }

    $("ddlAge").value = -1;
    $("ddlSex").value = -1;
    $("ddlRoomType").value = -1;
    $("ddlBedType").value = -1;
    $("ddlBedStatus").value = -1;

    arrSelectedFilterRooms = [];
    searchData();
}

function fillRooms(dataArray)
{
    hideAllRooms();

    for (var i = 0; i < dataArray.length; i++)
    {
        var room = $("r" + dataArray[i].room_id);
        room.style.display = "block";  //"inline"
    }
}

function triggerAddNewPatient(sourceBed)
{
    if (sourceBed.className == "pictureBox pictureBedService") // Bed maintenance
        return;

    var list = sourceBed.childNodes;

    for (var i = 0; i < list.length; i++)
    {
        if (list[i].className == "patient patientDiv") // Patient on bed
            return;
    }

    Shadowbox.open({
        player:     'iframe',
        content:    "gui_patient_add.php?bed_id=" + sourceBed.id.substring(1) + "&unit_id=" + UNIT_ID,
        height:     100,
        width:      300
    });
}

function bedUpdated(bed_id, bed_status, color, equipment)
{
    Shadowbox.close();
    var bedId = "b" + bed_id;

    $(bedId).className = "pictureBox " + (bed_status == 3 ? "pictureBedService" : "pictureBed");

    if (bed_status == 3)
    {
        Droppables.remove(bedId);
    }
    else
    {
        Droppables.add(
            bedId,
            {
                accept: 'patient',
                hoverclass: 'patientAccept',
                onDrop: patientOnBed
            });
    }

    $(bedId).style.backgroundColor = color;
    setEquipment(bed_id, equipment);
}

function setEquipment(bed_id, equipment)
{
    var eqId = $("e" + bed_id);
    var bedId = $("b" + bed_id);

    if (equipment == "" && eqId != null)
        eqId.remove();
    else if ($(eqId) == undefined)
        bedId.insert({after : equipment});
    else
        eqId.replace(equipment);

    setRoomWidth(bedId.parentNode.parentNode.parentNode.id.toString().substring(1));
}

function createPatient(patient_id, confirmed, display)
{
    GPARENT = null;

    // create DIV
    var patientId = "p" + patient_id;
    var div = document.createElement("div");
    div.id = patientId;
    div.className = "patient patientDiv";
    div.style.position = "relative";
    div.style.height = "77px";
    if (!display)
        div.style.display = "none";
    div.onmouseover = function() { setVisibility(patientId, 'patientDescr-' + patient_id, 'inline'); };
    div.onmouseout = function() { setVisibility(patientId, 'patientDescr-' + patient_id, 'none'); };
    div.innerHTML = "<img src=\"images/" +
        (confirmed ? "icon-patient.png" : "icon-patient-standby.png") + "\" />";

    new Draggable(div,
    {
        onStart: dragStart,
        onEnd: dragEnd,
        revert: revertOnError,
        scroll: window,
        snap: false
    });

    return div;
}

// Must be called after patient div is appended
function createMenu(patientId, confirmed)
{
    if (confirmed)
        protoMenu = newMenu(protoMenu.options.selector + ", #p" + patientId, patientMenu);
    else
        pendingMenu = newMenu(pendingMenu.options.selector + ", #p" + patientId, pendingPatientMenu);
}

function newMenu(menuSelector, items)
{
    return new Proto.Menu({
        selector: menuSelector,
        className: 'menu desktop',
        menuItems: items
    });
}

function createTooltip(patient_id, ssn, first_name, last_name)
{
    var tooltip = document.createElement("div");
    tooltip.id = "patientDescr-" + patient_id;
    tooltip.className = "patientDescription";
    tooltip.innerHTML = "SSN".localize() + ": " + ssn;
    if (first_name != null && last_name != null)
        tooltip.innerHTML += "<br>\n" + "Name".localize() + ": " + first_name + " " + last_name;

    $("mainBody").appendChild(tooltip);
}

function newPatientAdded(patient_id, bed_id, ssn)
{
    Shadowbox.close();

    createTooltip(patient_id, ssn, null, null);

    bed = $(bed_id == "depository" ? bed_id : ("b" + bed_id));
    patientOnBed(createPatient(patient_id, true, false), bed);
    createMenu(patient_id, true);

    $("p" + patient_id).appear({ duration: 1.0 });
}

function patientEditResize()
{
    $("shadowbox").style.height = "600px";
    $("shadowbox").style.width  = "400px";
    $("shadowbox_body").style.height = "100%";
}

function patientUpdated(patient_id, ssn, first_name, last_name)
{
    Shadowbox.close();

    var tooltip = $("patientDescr-" + patient_id);
    tooltip.innerHTML = "ID: " + ssn + "<br />" + "Name".localize() + ": " + first_name + " " + last_name;
}

function dragStart(item)
{
    var child = item.element;
    GPARENT = child.parentNode;

    $('mainBody').appendChild(child);

    if (GPARENT.id == 'depository')
       child.style.position = 'fixed';
}

function dragEnd(patient, event)
{
    var child = patient.element;
    child.style.position = 'relative';

    var d = $('depository');
    var dimension = d.getDimensions();
    var offset = d.cumulativeOffset();

    if (offset.left < event.clientX &&
        offset.top < event.clientY &&
        offset.left + dimension.width > event.clientX &&
        offset.top + dimension.height > event.clientY)
    {
        patientOnBed(child, d);
    }

    if (child.parentNode.id == 'mainBody')
    {
        GPARENT.appendChild(child);
    }
}

function revertOnError(patient)
{
    patient.style.left = patient.parentNode != $("depository") ? "30px" : "0px";
    patient.style.top = '0px';
}

function movePatientToDepository(object)
{
    var patient = object.target.parentNode;

    // if the patient is already in the depository, do nothing
    if (patient.parentNode.id == "depository") return;

    GPARENT = patient.parentNode;
    patientOnBed(patient, $("depository"));
}

function dischargePatient(object)
{
    if (confirm("Discharge patient?".localize()))
    {
        var patient = object.target.parentNode;
        var url = "gui_patient_discharge.php?p=" + patient.id.substring(1);
        createAjaxRequest(url, "Failed assignment".localize());

        var parent = patient.parentNode;

        // make parent droppable again
        Droppables.add(
            parent.id,
            {
                accept: 'patient',
                hoverclass: 'patientAccept',
                onDrop: patientOnBed
            });

        // remove child
        $(patient.id).fade({ duration: 1.0, afterFinish: function() {
                 parent.removeChild(patient);
             }});
    }
}

function confirmPatient(object)
{
    var patient = object.target.parentNode;
    var patient_id = patient.id.substring(1);

    patient.parentNode.removeChild(patient);
    putPatientOnBed(createPatient(patient_id, true, true), $('depository'), true);
    createMenu(patient_id, true);

    confirmOrRejectPatient(patient_id, true);
}

function rejectPatient(object)
{
    if (confirm("Turn down patient?".localize()))
    {
        var patient = object.target.parentNode;

        $(patient.id).fade({ duration: 1.0, afterFinish: function() {
                 patient.parentNode.removeChild(patient);
                 confirmOrRejectPatient(patient.id.substring(1), false);
             }});
    }
}

function movePatient(object)
{
    if (confirm("Move patient?".localize()))
    {
        var patient = object.target.parentNode;
        var url = "gui_patient_move.php?p=" + patient.id.substring(1) + "&u=" + UNIT_ID;
        createAjaxRequest(url, "Failed move".localize());
    }
}

function createAjaxRequest(url, err_msg)
{
    new Ajax.Request(url,
        {
            onException: function(req,exception) {
                alert(err_msg + ":\n\n" + exception);
                window.location.reload();
            },

            onFailure: function(req) {
                alert(err_msg + ":\n\n" + req.statusText);
                window.location.reload();
            },

            onComplete: function(req) {
                if (req.responseText == "nosession")
                {
                    window.location.reload();
                    return;
                }

                if (req.responseText != "true") {
                    alert(err_msg);
                    window.location.reload();
                }
            }
        });
}

function editPatientsData(object)
{
    var patient = object.target.parentNode;

    Shadowbox.open({
        player:  'iframe',
        content: "gui_patient_edit.php?patient_id=" + patient.id.substring(1) + "&unit_id=" + UNIT_ID,
        height:  600,
        width:   400
    });
}

function editBedProperties(object)
{
    var bed = object.target;

    Shadowbox.open({
        player:  'iframe',
        content: "gui_bed_properties.php?bed_id=" + bed.id.substring(1),
        height:  250,
        width:   450
    });
}

function setRoomWidth(roomId)
{
    var roomDescr = $('roomDescr' + roomId);

    //find the div id='screenThumb' which contains the beds and the equipment
    for (var i = 0; i < roomDescr.childNodes.length; ++i)
    {
        if (roomDescr.childNodes[i].id == 'screenThumb')
        {
            setScreenThumbWidth(roomDescr.childNodes[i]);
            break;
        }
    }
}

function setScreenThumbWidth(screenThumb)
{
    // calculate the total width
    var sumWidth = 0;

    for (var i = 0; i < screenThumb.childNodes.length; ++i)
    {
        if (!isNaN(screenThumb.childNodes[i].offsetWidth))
        {
            sumWidth += screenThumb.childNodes[i].offsetWidth;
            if (screenThumb.childNodes[i].className == "bedBox") // Equipment
                sumWidth += 5;
        }
    }

    screenThumb.style.width = sumWidth + 'px';
}

// Scroll for all the rooms
// scroll the element horizontally based on its width and the slider maximum value
function scrollHorizontal(value, element, slider) {
    element.scrollLeft = Math.round(value/slider.maximum*(element.scrollWidth-element.offsetWidth));
}

function searchEnter(event)
{
    if (event && event.keyCode == 13)
    {
        searchPatient();
        event.cancel = true;
    }
}

function searchPatient()
{
    var value = $('searchField').value;
    if (value == '')
        return;

    window.open("unit_search.php?u=" + UNIT_ID + "&s=" + value,null,'height=180,width=340,left=500,top=200,location=0,scrollbars=1');
}
