

var _userSeparator = '[us]';
var _itemSeparator = '[is]';
    
// Function Update Recipients with list passed from Compose window
function UpdateRecipientList() {
    $('#hdnChkContacts').val("");               // Reset variable

    var totalRows = $("#ContentHdnRecep").children().length;
    if (totalRows > 0) {
        $("#ContentHdnRecep").children().each(function () {
            var current = this;
            var userId = $(current).children('.IdHdn').html();
            var send = $(current).children('.SendHdn').html();
            var firstName = $(current).children('.FirstNameHdn').html();
            var lastName = $(current).children('.LastNameHdn').html();
            var level = $(current).children('.LevelHdn').html();
            var firstNameHdn = $(current).children('.FFullHdn').html();
            var lastNameHdn = $(current).children('.LFullHdn').html();
            var idEncrypted = $(current).children('.IdEncryptHdn').html();
            createNewRecipient(userId, firstName, lastName, level, send, firstNameHdn, lastNameHdn, idEncrypted); //
            addContactToHdnField(userId);
        });
    }

    enableDisableDoneBtn();
    disableToCCRemoveBtn();
    RecipFirstPageClick();  
}

function disableToCCRemoveBtn() {
    $('#RemoveBtn').attr('disabled', 'disabled');
    $('#RemoveBtn').removeClass('RemoveBtnActive');
    $('#ToBtn').attr('disabled', 'disabled');
    $('#CcBtn').attr('disabled', 'disabled');
}

function enableDisableDoneBtn() {
    $('#AddBtn').addClass('DoneBtnActive');
//    var totpages = $("#RecipientMainDiv").children().length;
//    if (totpages > 0) {
//        $('#AddBtn').removeAttr('disabled');
//        $('#AddBtn').addClass('DoneBtnActive');
//    } else {
//        $('#AddBtn').attr('disabled', 'disabled');
//        $('#AddBtn').removeClass('DoneBtnActive');
//    }
}

function clickCheckBoxContact() {
    if ($('#ContactListArea input[type=checkbox]:enabled:checked').length > 0) {
        $('#ToBtn').removeAttr('disabled');
        $('#CcBtn').removeAttr('disabled');
    } 
    else {
        $('#ToBtn').attr('disabled', 'disabled');
        $('#CcBtn').attr('disabled', 'disabled');
    }
    $('#RemoveBtn').attr('disabled', 'disabled');
    $('#RemoveBtn').removeClass('RemoveBtnActive');
    $('.RecipientPageDiv.current').find('input[type=checkbox]:checked').removeAttr('checked');
}
function clickCheckBoxRecipient() {
    if ($('.RecipientPageDiv.current').find('input[type=checkbox]:checked').length > 0) {
        $('#RemoveBtn').removeAttr('disabled');
        $('#RemoveBtn').addClass('RemoveBtnActive');
    }
    else {
        $('#RemoveBtn').attr('disabled', 'disabled');
        $('#RemoveBtn').removeClass('RemoveBtnActive');
    }
    $('#ToBtn').attr('disabled', 'disabled');
    $('#CcBtn').attr('disabled', 'disabled');
    $('#ContactListArea input[type=checkbox]:enabled').removeAttr('checked');
}

function addToRecipientList(send) {
    var allCheckedIds = '';
    $("#ContactListArea input:checked").each(function () {
        var current = this;
        var userIdLevel = $(current).val();
        var idlevel = userIdLevel.split(_userSeparator);
        allCheckedIds += idlevel[0] + ',';
        if (!existContactInHdnField(userIdLevel)) {
            var firstName = $(current).closest('.ItemRow').children('.ContactListFirstName').html();
            var lastName = $(current).closest('.ItemRow').children('.ContactListLastName').html();
            var level = $(current).closest('.ItemRow').children('.ContactListLevel').html();
            var firstNameHdn = $(current).closest('.ItemRow').children('.ContactListFirstHdn').html();
            var lastNameHdn = $(current).closest('.ItemRow').children('.ContactListLastHdn').html();
            var idEncryptHdn = $(current).closest('.ItemRow').children('.ContactListIdEncHdn').html();

            $(current).closest('.ItemRow').find('input, span').attr('disabled', 'disabled');                                    // Disable row
            createNewRecipient(userIdLevel, firstName, lastName, level, send, firstNameHdn, lastNameHdn, idEncryptHdn);                                                       //
            addContactToHdnField(userIdLevel);
        }
    });
    // Mark all the same users Id disable (with other levels)
    if (allCheckedIds != '') {
        $("#ContactListArea input:not(:checked)").each(function () {
            var current = this;
            var userIdLevel = $(current).val();
            var idlevel = userIdLevel.split(_userSeparator);
            var idsArray = allCheckedIds.split(',');
            $.each(idsArray, function (index, value) {
                if (value == idlevel[0]) {
                    $(current).closest('.ItemRow').find('input, span').attr('disabled', 'disabled');                                    // Disable row
                    $(current).closest('.ItemRow').find('input').prop('checked', true);
                }
            });
        });
        
    }
    disableToCCRemoveBtn();
    RecipLastPageClick();       //to make sure go to last page
}
function addContactToHdnField(userId) {
    $('#hdnChkContacts').val($('#hdnChkContacts').val() + userId + _itemSeparator);
}
function existContactInHdnField(userIdLevel) {
    var userId = userIdLevel.split(_userSeparator);

    var exist = false;
    var contactArray = $('#hdnChkContacts').val().split(_itemSeparator);
    $.each(contactArray, function (index, value) {
        var valueId = value.split(_userSeparator);  // Compare only Id (not level)
        if (valueId[0] == userId[0])
            exist = true;
    });
    return exist;
}

function removeContactFromHdnField(userId) {
    var contactArray = $('#hdnChkContacts').val().split(_itemSeparator);
    contactArray.splice($.inArray(userId, contactArray), 1);        //Remove userId from array
    //Not works because spearator is not ',' anymore -> $('#hdnChkContacts').val(contactArray + "");                  //Convert Array to string and assign to hidden field value
    var contacts = "";
    $.each(contactArray, function (index, value) {
        if (value != "")
         contacts += value + _itemSeparator;
    });
    $('#hdnChkContacts').val(contacts);

}

function enableContactItem(userIdLevel) {
    var userId = userIdLevel.split(_userSeparator);
    enableId(userId[0] + _userSeparator + 'F');        //Enable for userId for Faculty
    enableId(userId[0] + _userSeparator + 'P');        //Enable for userId for Provider
    enableId(userId[0] + _userSeparator + 'A');        //Enable for userId for Admin
}
function enableId(userIdLevel) {
    var current = $('#ContactListArea input[value="' + userIdLevel + '"]');
    $(current).prop('checked', false);
    $(current).closest('.ItemRow').find('input, span').removeAttr('disabled');                                              // Enable row
}

// Create a new Recipient Page (if is neccesary) and create a Item Row
function createNewRecipient(userId, firstName, lastName, level, send, firstNameHdn, lastNameHdn, idEncrypted) {
    var totalDivPages = $("#RecipientMainDiv").children().length;                                                           // Get total of divs which name contain 'RecipientPageDiv'  var totalDivPages = $("#RecipientMainDiv div[id^='RecipientPageDiv']").length;

    var divPag;
    if (totalDivPages == 0) {
        divPag = createContent("RecipientMainDiv", "RecipientPageDiv_" + totalDivPages, "RecipientPageDiv current");                // Create a new page div RecipientPageDiv_number; number begin with cero
        totalDivPages++;
    }
    else {
        divPag = $("#RecipientMainDiv").children().last();
        var totalDivRow = $(divPag).children().length;
        if (totalDivRow >= 10) {
            $(".RecipientPageDiv").removeClass("current").last();
            divPag = createContent("RecipientMainDiv", "RecipientPageDiv_" + totalDivPages, "RecipientPageDiv current");       // Create a new Page div RecipientPageDiv_number; number begin with cero
            totalDivPages++;
        }
    }
    // Create a new ItemRow and all the elements for this ItemRow
    if (divPag != null) {
        var rowDiv = createContent($(divPag).attr("id"), "RecipientRow_" + userId, "ItemRow"); // Create a new page div
        var checkBox = createCheckbox(rowDiv.id, "checkBoxCtl_" + userId, "CheckBox ContactListCheckBox", userId);
        $(checkBox).on('click', function () {     // AX-24898.24919.2 $(checkBox).bind('click', function () { 
            clickCheckBoxRecipient();
        });
        createSpan(rowDiv.id, "SendOutput_" + userId, "ContactListSend", send == 'to' ? 'To' : 'Cc');
        createSpan(rowDiv.id, "FirstOutput_" + userId, "ContactListFirstName", firstName);
        createSpan(rowDiv.id, "LastOutput_" + userId, "ContactListLastName", lastName);
        createSpan(rowDiv.id, "LevelOutput_" + userId, "ContactListLevel", level);
        createSpan(rowDiv.id, "FirstFullHdn_" + userId, "ContactListFirstHdn", firstNameHdn);
        createSpan(rowDiv.id, "LastFullHdn_" + userId, "ContactListLastHdn", lastNameHdn);
        createSpan(rowDiv.id, "IdEncrHdn_" + userId, "ContactListIdEncHdn", idEncrypted);
    }
    setRecipientsNavigBtns();
    enableDisableDoneBtn();
}

function removeRecipient(userId) {
    $('.RecipientPageDiv.current input[value="' + userId + '"]').parent().remove();     // Remove RecipientRow

    var end = $("#RecipientMainDiv").children().length;
    var current = $(".RecipientPageDiv.current").index();
    // if current page is last then check is not only  move an item row from next page to current
    if (current == (end - 1)) {
        if ($(".RecipientPageDiv.current").children().length == 0) {
            $(".RecipientPageDiv.current").remove();                             // Remove current page if is empty
            if (current > 0)
                $("#RecipientMainDiv").children().eq(current - 1).addClass("current");
        }
    } else {    // if current page is not last then move an item row from next page to current
        while (current < (end - 1)) {
            var currPage = $("#RecipientMainDiv").children().eq(current);
            var nextPage = $("#RecipientMainDiv").children().eq(current + 1);
            var newItem = nextPage.children().first().clone();                  // Clone first item from next page

            newItem.find('input[type=checkbox]').on('click', function () {    // AX-24898.24919.2 newItem.find('input[type=checkbox]').bind('click', function () {
                clickCheckBoxRecipient();
            });

            currPage.append(newItem);                                           // Append cloned item to current page

            nextPage.children().first().remove();                               // Remove first item from next page
            if (nextPage.children().length == 0)
                nextPage.remove();                                              // Remove page if is empty
            current++;
        }
    }
    setRecipientsNavigBtns();
    enableDisableDoneBtn();
}

// Remove from Recipient list
function removeFromRecipientList() {
    $(".RecipientPageDiv.current input:checked").each(function () {
        var current = this;
        var userId = $(current).val();
        removeContactFromHdnField(userId);                          // Remove selected Recipient from hdnChkContacts field
        enableContactItem(userId);                                  // Enable User and uncheck in Contact List
        removeRecipient(userId);                                    // Remove recipient from Recipient List
    });
    disableToCCRemoveBtn();
}

// Click Recipient FirstPage button
function RecipFirstPageClick() {
    $('.RecipientPageDiv.current').find('input[type=checkbox]:checked').removeAttr('checked');      // Uncheck checkboxes from current page

    $("#RecipientMainDiv").children().removeClass("current").first().addClass("current");
    setRecipientsNavigBtns();
}
// Click Recipient LastPage button
function RecipLastPageClick() {
    $('.RecipientPageDiv.current').find('input[type=checkbox]:checked').removeAttr('checked');      // Uncheck checkboxes from current page

    $("#RecipientMainDiv").children().removeClass("current").last().addClass("current");
    setRecipientsNavigBtns();
}
// Click Recipient NextPage button
function RecipNextPageClick() {
    $('.RecipientPageDiv.current').find('input[type=checkbox]:checked').removeAttr('checked');      // Uncheck checkboxes from current page

    var end = $("#RecipientMainDiv").children().length;
    var current = $(".RecipientPageDiv.current").index();

    if (current < end) {
        $(".RecipientPageDiv.current").removeClass("current").next().addClass("current");
    } else {
        $(".RecipientPageDiv").removeClass("current").last().addClass("current");
    }
    setRecipientsNavigBtns();
}
// Click Recipient PrevPage button
function RecipPrevPageClick() {
    $('.RecipientPageDiv.current').find('input[type=checkbox]:checked').removeAttr('checked');      // Uncheck checkboxes from current page

    var begin = 1;
    var current = $(".RecipientPageDiv.current").index();

    if (current > begin) {
        $(".RecipientPageDiv.current").removeClass("current").prev().addClass("current");
    } else {
        $(".RecipientPageDiv").removeClass("current").first().addClass("current");
    }
    setRecipientsNavigBtns();
}
// Enable or disable pagination buttons for Recipient list
function setRecipientsNavigBtns() {
    var end = $("#RecipientMainDiv").children().length;
    var current = $(".RecipientPageDiv.current").index();
    if (end > 1)
        $('.RecipientBtnsDiv').addClass("current");                         // Show buttons div
    else
        $('.RecipientBtnsDiv').removeClass("current");                      // Hide buttons div

    if (current > 0) {
        $('#RecipFirstPageBtn').removeAttr('disabled');
        $('#RecipPrevPageBtn').removeAttr('disabled');
    } else {
        $('#RecipFirstPageBtn').attr('disabled', 'disabled');
        $('#RecipPrevPageBtn').attr('disabled', 'disabled');
    }
    if (current < end - 1) {
        $('#RecipNextPageBtn').removeAttr('disabled');
        $('#RecipLastPageBtn').removeAttr('disabled');
    } else {
        $('#RecipNextPageBtn').attr('disabled', 'disabled');
        $('#RecipLastPageBtn').attr('disabled', 'disabled');
    }

    if (end > 0)
        $('#RecipPageNumber').text('Page ' + ++current + ' of ' + end);
    else
        $('#RecipPageNumber').text('');
}

function addRecipientsToContactPage() {
    var toTxt = "";
    var ccTxt = "";
    var toIds = "";
    var ccIds = "";
    var idsEncrypt = "";
    var sepItem = $('#hdSepId').text();
    
    $("#RecipientMainDiv .ItemRow").each(function () {
        var current = this;
        var userId = $(current).children('.CheckBox').val();

        var sender = $(current).children('.ContactListSend').html();
        var firstName = $.trim($(current).children('.ContactListFirstHdn').html());
        var lastName = $.trim($(current).children('.ContactListLastHdn').html());
        var completeName = firstName + ((firstName.length > 0 && lastName.length > 0) ? " " : "") + lastName + ((firstName.length > 0 || lastName.length > 0) ? "; " : "");
        //var level = $(current).children('.ContactListLevel').html();
        if (sender == "To") {
            toTxt += completeName;
            toIds += userId + _itemSeparator;
        } else {
            ccTxt += completeName;
            ccIds += userId + _itemSeparator;
        }
        idsEncrypt += ($(current).children('.ContactListIdEncHdn').html() + sepItem);
    });
    toTxt = $('<div/>').html(toTxt).text();                                 // Similar to Html.Decode
    ccTxt = $('<div/>').html(ccTxt).text();                                 // Similar to Html.Decode
    toTxt = toTxt.replace(/;?\s+$/, "");                                    // Trim blank and ; 
    ccTxt = ccTxt.replace(/;?\s+$/, "");                                    // Trim blank and ;
    var frameWin = $('#hdPageTypeId').text() == "3" ? 'AppointListId' : $('#hdPageTypeId').text() == "4" ? 'UpcomeApptId' : 'messageIframeId';
    callParentIframe(frameWin, toTxt, ccTxt, toIds, ccIds, idsEncrypt);        // The frame is MessageList because MessageCompose.aspx is called using Response.Redirect and is form inside the MessageView frame (for appointments is AppointListId) 
    //callParentIframe('messageComposeIframeId', toTxt, ccTxt, toIds, ccIds);//This was used before, when Compose Window was a logic element (defined in CSS)
    closeContactDetailPage();
}

function closeContactDetailPage() {
    window.parent.closeIframe('windowMedium', 'windowMedium');          // Close popup window
}
