$(document).ready(function() {
    $(function () {
        $("#menu").remove();
        $("#tabs").tabs({
            collapsible: true
        });

        $(".showSettings").on("click", showSettings);
        $(".hideSettings").on("click", hideSettings);

        $(".notificationRuleRole").on("click", function () { editRule($(this).data("nid"), $(this));
            return false;
        });

        $("#content select").on("change", rulesChanged);
    });
});

function showSettings() {
    $(this).closest('td').next('td').show();
    $(this).hide();

    return false;
}

function hideSettings() {
    var holder = $(this).closest('td');
    holder.hide();
    holder.prev('td').find('.showSettings').show();

    return false;
}

function rulesChanged() {
    $(this).closest('tr.outertr').addClass("changed");
}


function editRule(id, link) {
    var url = base + 'updatesystem.ivp/getNotificationRule/' + id;

    showRulePanel(url, $(link), { nolayout: 'true', timestamp: new Date().toString() })

    return false;
}

function showRulePanel(url, link, params) {

    //Очистим глобальные переменные с прошлого открытия
    oldEmailTemplateId = '';
    oldSMSTemplateId = '';
    savedStatusesArray = new Array();
    smsInheritStatuses = new Array();

    var offset = link.offset();

    if ($('#notificationruleedit').length == 0) $('body').append('<div id="notificationruleedit" class="notificationruleedit hidden"></div>');
    var panel = $('#notificationruleedit');
    panel.load(url, params, function () {

        //инициализация выпадающего списка
        $('#statusid').multipleSelect({});
        unserializeStatusTemplates();
        getSmsInherits();

        panel.addClass('popupwrapper').css('top', offset.top + link.height()).css('left', offset.left );

        //panel.bgiframe().show();
        panel.show();

        initStatusTemplates();
    });
    return false;
}

function initStatusTemplates(noicons) {
    $('div.checklisttitle').find('a').attr('title', NotificationRuleResources.Add).html(NotificationRuleResources.Add);
    var selOptions = $("select[name='statusid'] option:selected");
    var scbhtml = '<ul class="selectedstatuses padded5 indent10" style="position: relative;"></ul>';
    $('#checkedstatuses').append(scbhtml);
    selOptions.each(function (i, el) {
        var statuses = '';
        statuses = initStatus(el.value, el.text, noicons);
        $('.selectedstatuses').append(statuses);
        $('.statusapply').click(applyStatusTemplates);
    });

    $('#statusid').bind('hideChecked', function (event, self) {

        setHeight(self);

    });

    $('#statusid').on('addStatus', function (event, checkbox, select) {
        addStatus(checkbox); setHeight(select);
    });

    $('#statusid').bind('linkTextChanged', function (event, link) { link.attr('title', NotificationRuleResources.Add).html(NotificationRuleResources.Add); });

}

function initStatus(value, text, noicons) {
    var scbhtml = '';
    var templateDictionary = $("select[name='templates'] option");
    var smsTemplateDictionary = $("select[name='defaultsmstemplates'] option");
    var hasTemplate = null;
    var imgTemplate = null;
    var titleTemplate = null;
    var templateText = null;

    var result = generateSelect(templateDictionary, 'emailtemplates', value, true);
    var emailSelect = result[0];
    templateText = result[1];
    result = generateSelect(smsTemplateDictionary, 'smstemplates', value, false, ($('#tariff').val() != "SaaSPlus" && $('#tariff').val() != "Enterprise") ? "hidden" : "");
    var smsSelect = result[0];
    var smsTemplateText = result[1];

    if (templateText != null && templateText != '') {
        imgTemplate = 'img/mailtemplate.png';
        titleTemplate = NotificationRuleResources.UsingTemplate + templateText + NotificationRuleResources.ChangeTemplate;
    }
    else {
        imgTemplate = 'img/nomailtemplate.png';

        if ($('#notificationruleform #workflowid').val() == '')
            titleTemplate = NotificationRuleResources.InheritedTemplate;
        else
            titleTemplate = NotificationRuleResources.UseDefaultTemplate;
    }

    var smsSpan = '';

    if (smsTemplateText != null && smsTemplateText != '') {
        smsTemplateText = NotificationRuleResources.UsingTemplate + templateText + NotificationRuleResources.ChangeTemplate;
        smsSpan = '<span id="spanstatus_' + value + '" class="smsnotify" title="' + smsTemplateText + '"> + SMS</span>';
    }
    else {
        if ($.inArray(value, smsInheritStatuses) > -1) {
            smsTemplateText = NotificationRuleResources.InheritedTemplate;
            smsSpan = '<span id="spanstatus_' + value + '" class="smsnotify darkgrey" title="' + smsTemplateText + '"> + SMS</span>';
        }
        else {
            smsSpan = '<span id="spanstatus_' + value + '" class="smsnotify hidden"> + SMS</span>';
        }
    }

    scbhtml += '<li id="listatus">';
    if (!noicons)
        scbhtml += '<a href="#" class="showTemplate" onclick="showTemplatePopup(\'#nstatus_' + value + '\', false); return false;"><img class="middle" src="img/edit.gif" title="' + CommonResources.Change + '"></a>';
    scbhtml += '<a class="dellink" id="delstatus_' + value + '" href="#" onclick="removeSelectedStatus(this,\'' + value + '\'); return false;"><img class="dellink" src=img/trash.gif title="' + NotificationRuleResources.Delete + '"></a><span class="inline-block margin-right10px">' + text + '</span>';

    if (!noicons) {
        scbhtml += '<a id="nastatus_' + value + '"href="#" class="mlink nounderline nastatus" onclick="showTemplatePopup(\'#nstatus_' + value + '\', false); return false;">';
        scbhtml += '<img id="imgstatus_' + value + '" src="' + imgTemplate + '" title="' + titleTemplate + '">' + smsSpan + '</a>';
        scbhtml += '<div class="clear"></div><div id="nstatus_' + value + '" class="nstatus popupwrapperdown indent20 hidden" ><div class="popupdown">';
        scbhtml += '<label for="statustemplateid">' + NotificationRuleResources.EmailTemplate + '</label>';

        scbhtml += emailSelect;

        scbhtml += '<label for="smstemplateid">' + NotificationRuleResources.SmsTemplate + '</label>';

        scbhtml += smsSelect;
        if ($('#tariff').val() != "SaaSPlus" && $('#tariff').val() != "Enterprise")
            scbhtml += '<span>' + NotificationRuleResources.DisabledInThisTariff + '</span>';

        scbhtml += '<div class="spacer10"></div>';
        scbhtml += '<span class="small">' + NotificationRuleResources.TemplateHint + '</span>';

        scbhtml += '<div class="spacer10"></div><a href="#" class="button statusapply">';
        scbhtml += '<img src="img/accept.png" class="icons16">' + NotificationRuleResources.Save;
        scbhtml += '</a>';

        scbhtml += '<a href="#" class="button" onclick="cancelPopup(\'#nstatus_' + value + '\', false); return false;">';
        scbhtml += '<img src="img/delete.gif" class="icons16">' + NotificationRuleResources.Cancel;
        scbhtml += '</a>';

        scbhtml += '</div></div>';
    }
    scbhtml += '<div class="spacer5"></div>';
    scbhtml += '</li>';
    return scbhtml;
}

function serializeStatusTemplates() {
    var result = '';
    var $statuses = $('#statusid option');

    $statuses.each(function (i, status) {
        var etid = $('select[name="emailtemplates"][statusid="' + $(status).val() + '"] option:selected').val();
        var sid = $('select[name="smstemplates"][statusid="' + $(status).val() + '"] option:selected').val();
        if (result != '' && ((etid != null && etid != '') || (sid != null && sid != ''))) result += ',';
        if ((etid != null && etid != '') || (sid != null && sid != '')) {
            result += 'statusid:' + $(status).val();
        }
        if (etid != null && etid != '')
            result += '|templateid:' + etid;
        if (sid != null && sid != '')
            result += '|smstemplateid:' + sid;
    });
    $('#statustemplate').val(result);
    return false;
}


function unserializeStatusTemplates() {
    var split = $('#statustemplate').val() ? $('#statustemplate').val().split(',') : new Array();

    split.forEach(function (el, i, array) {
        var statusid = '';
        var templates = new Array();

        var splitVert = el.split('|');
        splitVert.forEach(function (elsv, isv, arraysv) {
            if (elsv.startsWith('statusid:'))
                statusid = elsv.replace('statusid:', '');
            if (elsv.startsWith('templateid:'))
                templates['templateid'] = elsv.replace('templateid:', '');
            if (elsv.startsWith('smstemplateid:'))
                templates['smstemplateid'] = elsv.replace('smstemplateid:', '');
        });
        if (statusid != '') {
            savedStatusesArray['"' + statusid + '"'] = templates;
        }
    });
    $('#statustemplate').val('');
    return false;
}

function getSmsInherits() {
    smsInheritStatuses = $('#smsinherits').val().split(',');
    return false;
}

function generateSelect(dictionary, name, statusid, email, classes) {
    var select = '<select class="px200 ' + classes + '" name="' + name + '" id="' + name + statusid + '" statusid="' + statusid + '">@options</select>';
    var options = null;
    var text = null;

    var assignedTemplateId = templateAssignedToStatus(statusid, dictionary, email);
    dictionary.each(function (i, e) {
        if ($(e).val() == assignedTemplateId) { text = e.text; options += '<option selected="true" value="' + $(e).val() + '">' + e.text + '</option>'; }
        else
            options += '<option value="' + $(e).val() + '">' + e.text + '</option>';
    });

    select = select.replace('@options', options);
    return [select, text];
}

function templateAssignedToStatus(statusid, templateDictionary, isEmail) {
    var id = null;
    if (savedStatusesArray['"' + statusid + '"'] == null) return null;
    templateDictionary.each(function (i, t) {
        if (isEmail) {
            if (savedStatusesArray['"' + statusid + '"']['templateid'] == t.value) {
                id = t.value;
                return false;
            }
        }
        else {
            if (savedStatusesArray['"' + statusid + '"']['smstemplateid'] == t.value) {
                id = t.value;
                return false;
            }
        }

    });
    return id;
}

function applyStatusTemplates() {
    var $emailselect = $(this).closest('.popupdown').find('select[name="emailtemplates"]');
    var $smsselect = $(this).closest('.popupdown').find('select[name="smstemplates"]');
    var $img = $('#imgstatus_' + $emailselect.attr('statusid'));
    var $sms = $('#spanstatus_' + $smsselect.attr('statusid'));

    if ($emailselect.find('option:selected').text() != '') {
        $img.attr("src", "img/mailtemplate.png").attr("title", NotificationRuleResources.UsingTemplate + $emailselect.find('option:selected').text() + NotificationRuleResources.ChangeTemplate);
    }
    else {
        $img.attr("src", "img/nomailtemplate.png");
        if (!$('#notificationruleform #workflowid').val() == '')
            $img.attr("title", NotificationRuleResources.UseDefaultTemplate);
        else
            $img.attr("title", NotificationRuleResources.InheritedTemplate);
    }


    if ($smsselect.find('option:selected').text() != '') {
        $sms.attr('title', NotificationRuleResources.UsingTemplate + $smsselect.find('option:selected').text() + NotificationRuleResources.ChangeTemplate).removeClass('darkgrey').show();
    }
    else {
        if ($.inArray($smsselect.attr('statusid'), smsInheritStatuses) > -1) {
            $sms.attr('title', NotificationRuleResources.InheritedTemplate).addClass('darkgray').show();
        }
        else {
            $sms.hide();
        }
    }

    $(this).closest('.popupwrapperdown').hide();
    return false;
}

function saveNotificationRule() {
    $('#notificationruleedit').hide();
    serializeStatusTemplates();
    $.post(base + 'notificationrule.ivp/save/', $('#notificationruleform').serializeArray(), function () { });
    $('#notificationruleedit').remove();
    return false;
}

function showTemplateIcon(checkbox, event, workflow) {
    var link = "#na" + event;
    var editlink = "#nae" + event;
    if (checkbox.checked) {
        $(link).show();
        $(editlink).show();
    }
    else {
        removeTemplate(event);
        changeNotificationTemplateIcon(event, workflow);
        $(link).hide();
        $(editlink).hide();
    }
}

function removeTemplate(event) {
    var popupEvent = "#n" + event;
    var selectEmail = $(popupEvent).find('select#templateid');
    var selectSMS = $(popupEvent).find('select#smstemplateid');
    selectEmail.find('option:first').attr('selected', 'selected');
    selectSMS.find('option:first').attr('selected', 'selected');
    return false;
}

function changeNotificationTemplateIcon(event, workflow) {
    var imgEvent = "#img" + event;
    var popupEvent = "#n" + event;
    var smsEvent = "#smsn" + event;
    var selectEmail = $(popupEvent).find('select#templateid');
    var selectSMS = $(popupEvent).find('select#smstemplateid');

    if (selectEmail.val() != '') {
        $(imgEvent).attr("src", "img/mailtemplate.png").attr("title", NotificationRuleResources.UsingTemplate + selectEmail.find('option:selected').text() + NotificationRuleResources.ChangeTemplate);
    }
    else {
        $(imgEvent).attr("src", "img/nomailtemplate.png");
        if (workflow == "True")
            $(imgEvent).attr("title", NotificationRuleResources.UseDefaultTemplate);
        else
            $(imgEvent).attr("title", NotificationRuleResources.InheritedTemplate);
    }
    if (selectSMS.val() != '') {
        $(smsEvent).removeClass('darkgrey').attr("title", NotificationRuleResources.UsingTemplate + selectSMS.find('option:selected').text() + NotificationRuleResources.ChangeTemplate).show();
    }
    else {
        if ($(smsEvent).attr('inheritprop') == "False")
            $(smsEvent).hide();
        else
            $(smsEvent).addClass('darkgrey').attr("title", NotificationRuleResources.InheritedTemplate);
    }
    oldEmailTemplateId = '';
    oldSMSTemplateId = '';
    $(popupEvent).hide();

    return false;
}

function setHeight(mselect) {
    $(mselect.list).parent().parent().removeClass("popupwrapper").addClass("popupwrapperdown");
    $(mselect.list).parent().find(".mshidelink").removeClass("mshidelink").addClass("mshidelinkbottom");
    $(mselect.list).parent().removeClass("popup").addClass("popupdown");
    $(mselect.list).parent().parent().css('margin-top', -1 * $(mselect.list).parent().parent().height() - 23);
}

function addStatus(checkbox) {
    var parent = $(checkbox).parent();
    if (checkbox.checked) {
        var scbhtml = '';
        scbhtml = initStatus($(checkbox).val(), parent.text());
        $('.selectedstatuses').append(scbhtml);
        $('.statusapply').click(applyStatusTemplates);
    }
    else {
        var delId = "#delstatus_" + $(checkbox).val();
        removeSelectedStatus($(delId), $(checkbox).val());
    }
}

function showTemplatePopup(popup, isEvent) {
    $("#notificationruleform").find(".popupwrapperdown").hide();
    if ($(popup + ' #templateid').val() == '' || $(popup + ' #smstemplateid').val() == '' || $(popup + ' select[name="emailtemplates"]').val() == '' || $(popup + ' select[name="smstemplates"]').val() == '') {
        var eventid = $(popup + ' #templateid').attr('eventid');
        var statusid = $(popup + ' select[name="emailtemplates"]').attr('statusid');
        getTemplateInherits((eventid != null) ? eventid : '', (statusid != null) ? statusid : '', popup);
    }
    else
        $(popup).css('margin-top', -1 * $(popup).height() - 23).show();


    oldEmailTemplateId = (isEvent) ? $(popup).find('select#templateid').val() : $(popup).find('select[name="emailtemplates"]').val();
    oldSMSTemplateId = (isEvent) ? $(popup).find('select#smstemplateid').val() : $(popup).find('select[name="smstemplates"]').val();
}

function getTemplateInherits(eventid, statusid, popup) {
    $.getJSON(base + 'notificationrule.ivp/gettemplateinherits', { roleid: $('#roleid').val(), userid: $('#userid').val(), serviceid: $('#serviceid').val(), workflowid: $('#workflowid').val(), eventid: eventid, statusid: statusid }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
            return false;
        }
        if (result.length > 0) {
            if ($(popup + ' #templateid').val() == '') {
                $(popup + ' #templateid option[value="' + result[1] + '"]').attr('selected', true);
            }
            if ($(popup + ' #smstemplateid').val() == '' && result[0] != 0) {
                $(popup + ' #smstemplateid option[value="' + result[0] + '"]').attr('selected', true);
            }

            if ($(popup + ' select[name="emailtemplates"]').val() == '') {
                $(popup + ' select[name="emailtemplates"] option[value="' + result[1] + '"]').attr('selected', true);
            }
            if ($(popup + ' select[name="smstemplates"]').val() == '' && result[0] != 0) {
                $(popup + ' select[name="smstemplates"] option[value="' + result[0] + '"]').attr('selected', true);
            }
        }
        $(popup).css('margin-top', -1 * $(popup).height() - 23).show();
    });
}

function cancelPopup(popup, isEvent) {
    if (isEvent) {
        $(popup).find('select#templateid').find('option:selected').removeAttr('selected');
        $(popup).find('select#templateid').find('option[value="' + oldEmailTemplateId + '"]').attr('selected', true);
        $(popup).find('select#smstemplateid').find('option:selected').removeAttr('selected');
        $(popup).find('select#smstemplateid').find('option[value="' + oldSMSTemplateId + '"]').attr('selected', true);
    }
    else {
        $(popup).find('select[name="emailtemplates"]').find('option:selected').removeAttr('selected');
        $(popup).find('select[name="emailtemplates"]').find('option[value="' + oldEmailTemplateId + '"]').attr('selected', true);
        $(popup).find('select[name="smstemplates"]').find('option:selected').removeAttr('selected');
        $(popup).find('select[name="smstemplates"]').find('option[value="' + oldSMSTemplateId + '"]').attr('selected', true);
    }
    oldEmailTemplateId = '';
    oldSMSTemplateId = '';
    $(popup).hide();
    return false;
}

function removeSelectedStatus(delLink, statusid) {
    $("#addstatus").find("select#statusid option[value='" + statusid + "']").removeAttr("selected");
    $("#addstatus .popupwrapperdown .msitems .checklist input[value='" + statusid + "']").removeAttr("checked").parent().parent().show();

    $(delLink).parent().remove();
}
