var $list_macross = $('#ulmacros');

var lastFocused;
$(document).ready(function () {

    $(".last-focused").focus(function () {
        lastFocused = document.activeElement;        
    });

    $('#setattachment').change(function () {
        if ($('input#setattachment').prop('checked')) {
            $('#attachmenttype').show();
        } else {
            $('#attachmenttype').hide();
        }

    });

    $('.insert-macross').click(function () {       
        var text = $(this).attr('text');
        insertText(text);
    })
    $('#find-macros').keyup(function () {        
        var val = $(this).val();
        if(val != null && val != undefined && val !="")
            findMacros(val);
        else {          
            if ($list_macross.attr('issearch'))
                clearSearch();
        }
    })

});



$(function () {
    $('#typeid').change(changeType);
    changeType();
    $('#setattachment').change();
});

function findMacros(search) {
    $list_macross.attr('issearch', true);
    $list_macross.find('li').hide();
    var search_el = $('.insert-macross:containsIN(' + search + ')');
    if (search_el.length)
        search_el.show();
    else
        $('.not-search').show();
}
function clearSearch() {
    $list_macross.attr('issearch', false);
    $('.not-search').hide();   
    $list_macross.find('.insert-macross').show();
}

$.extend($.expr[":"], {
    "containsIN": function (elem, i, match, array) {
        return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});

function expandTextArea(id) {
    var rows = $(id).attr('rows');
    var labelName = $(id + 'expand').html();

    if (rows == 24) {
        rows = 40;
        labelName = NotificationTemplateResources.Collapse;
    }
    else {
        rows = 24;
        labelName = NotificationTemplateResources.Expand;
    }

    $(id).attr('rows', rows);
    $(id + 'expand').html(labelName);

    return false;
}

function showPreview() {
    var action = base + "notificationtemplate.ivp/preview";
    var form = $(document.createElement('form')).attr('action', action).attr('method', 'POST');
    $('body').append(form);
    $(form).submit(function () {
        window.open('', 'formpopup', 'width=800,height=600,scrollbars=1');
        this.target = 'formpopup';
    });
    $(document.createElement('input')).attr('type', 'hidden').attr('name', 'messageBody').attr('value', $('#message').val()).appendTo(form);
    $(form).submit();
    return false;
}

function changeType() {
    defaultForm();
    switch ($('#typeid').val()) {
        case '1':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list.html'); return false; });
            break;
        case '2':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_user.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_user.html'); return false; });
            break;
        case '3':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_newsletter.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_newsletter.html'); return false; });
            break;
        case '4':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_usercard.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_usercard.html'); return false; });
            break;
        case '6':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_external_list.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_external_list.html'); return false; });
            break;
        case '7':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list.html'); return false; });
            handleSms();
            break;
        case '8':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_subscriptions.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_subscriptions.html'); return false; });
            break;
        case '9':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_lowmark.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_lowmark.html'); return false; });
            break;
        case '10':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_taskcreateblock.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_taskcreateblock.html'); return false; });
            break;
        case '12':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_userschedule.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_userschedule.html'); return false; });
            break;
        case '13':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list.html'); return false; });
            handlePush();
            break;
        case '14':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_user_restorepassword.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_user_restorepassword.html'); return false; });
            break;
        case '15':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_remind.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_remind.html'); return false; });
            break;
        case '16':
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list_asset.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list_asset.html'); return false; });
            break;
        default:
            $('#helplink').attr('href', $('#helplink').attr('startpath') + 'macros_list.html');
            $('#helplink').unbind('click').click(function () { openDialog($('#helplink').attr('startpath') + 'macros_list.html'); return false; });
            break;
    }
}

function handleSms() {
    $('#subject').removeClass('required').parent().hide();
    $('#cutmessagefield').show();
    $('#cutPush').hide();
    $('#cutSMS').show();
    if ($('#id').val() == '0') {
        $('#cutmessage').attr('checked', true);
        $('#message').val('Заявка #%fullid%. %shortdescription%');
    }
}

function handlePush() {
    $('#subject').removeClass('required').parent().hide();
    $('#cutmessagefield').show();
    $('#cutPush').show();
    $('#cutSMS').hide();
    if ($('#id').val() == '0') {
        $('#cutmessage').attr('checked', true);
    }
}

function defaultForm() {
    $('#subject').addClass('required').parent().show();
    $('#cutmessagefield').hide();
}

function setDefault(checkbox) {
    if (checkbox.checked && $("#anydefault").val() == "True") {
        if (!confirm(NotificationTemplateResources.Alert)) {
            console.log('removed');
            $("#isdefault").removeAttr('checked');
        }
    }
}

function selectTemplateMessageLanguage() {
    var url = 'fieldlanguage.ivp/load?textarea=true&required=true&table=NotificationTemplates&field=MessageXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}


function selectTemplateSubjectLanguage() {
    var url = 'fieldlanguage.ivp/load?required=true&table=NotificationTemplates&field=SubjectXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}


function selectTemplateNameLanguage() {
    var url = 'fieldlanguage.ivp/load?required=true&table=NotificationTemplates&field=NameXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}


function insertText(text) {
    var input = lastFocused;    
    if (input == undefined) {
        alert(MacrosResources.NotSelectArea)
        return;
    }
    var scrollPos = input.scrollTop;
    var pos = 0;
    var browser = ((input.selectionStart || input.selectionStart == "0") ?
      "ff" : (document.selection ? "ie" : false));
    if (browser == "ie") {
        input.focus();
        var range = document.selection.createRange();
        range.moveStart("character", -input.value.length);
        pos = range.text.length;
    }
    else if (browser == "ff") { pos = input.selectionStart };

    var front = (input.value).substring(0, pos);
    var back = (input.value).substring(pos, input.value.length);
    input.value = front + text + back;
    pos = pos + text.length;
    if (browser == "ie") {
        input.focus();
        var range = document.selection.createRange();
        range.moveStart("character", -input.value.length);
        range.moveStart("character", pos);
        range.moveEnd("character", 0);
        range.select();
    }
    else if (browser == "ff") {
        input.selectionStart = pos;
        input.selectionEnd = pos;
        input.focus();
    }
    input.scrollTop = scrollPos;
}