(function ($) {
    $.fn.loadTM = function (options) {
        var settings = $.extend({
            // These are the defaults.
            backgroundColor: "white",
            width: "240px",
            allowadd: true,
            allowedit: true
        }, options);
        var idbase = this.attr('id').replace('Div', '');
        var curVal = "";
        var curItm = "";
        var valData = this.attr('val');
        var fieldType = this.attr('ft');
        if (valData != null && valData != "0" && valData.replace(/\s*$/, "") != '0·') {
            if (valData.indexOf("'") > -1) {
                curVal = "value='" + valData.split('·')[1].replace(/'/g, ''') + "' val='" + valData.split('·')[0] + "'";
            }
            else {
                curVal = "value='" + valData.split('·')[1] + "' val='" + valData.split('·')[0] + "'";
            }
            curItm = "
" + valData.split('·')[1] + "
";
        }
        else {
            curVal = "value='' val='0'";
        }
        var disabled = "";
        if (this.attr('disabled') != null) {
            disabled = " readonly ";
        }
        this.html("" + 
            "");
        this.attr("initd", "y");
        return this;
    };
}(jQuery));
var TMData = [];
var openTM = "";
$(window).click(function (e) {
    if (openTM != "") {
        if (e.target.id != "" && openTM.indexOf(e.target.id + ',') > 0) {
        }
        else {
            HideTM($('#' + openTM.split(',')[0]));
        }
    }
});
$(window).on('keyup', function (e) {
    if (e.which == 9) {
        if (openTM != "") {
            if (e.target.id != "" && openTM.indexOf(e.target.id + ',') > 0) {
            }
            else {
                HideTM($('#' + openTM.split(',')[0]));
            }
        }
    }
});
function EvalTMShow(n) {
    if (openTM != "") {
        if (openTM.indexOf($(n).attr('id') + ',') > 0) {
        }
        else {
            console.log('evalshow');
        }
    }
    else {
        if ($(n).attr('val') == '' || $(n).attr('val') == '0') {
            ShowTM($(n));
        }
    }
}
function LoadTMData(mod, fld, fldType, gid, dir, naa, co, refid) {
    var dv = $('#' + fld + 'Div');
    $.post('../handlers/HTMLCRUD.ashx?pageaction=loadTMData', { mod: mod, fldT: fldType, gid: gid, dir: dir, naa: naa, co: co, refid: refid }, function (data) {
        $(dv).find('.TeamAELData').html('');
        $(dv).attr('activestatus', 'loaded');
        GetTMData(fld);
    });
   
}
function ShowTM(n) {
    // 'n' is the element that triggered the show. could be either the textbox or the image to the right of it
    var imgArr = $('#' + $(n).attr('id'));
    var d = $('#' + $(n).attr('id').replace('Img', '') + 'Mnu');  //menu
    if (openTM != "") {
        if (openTM.indexOf($(d).attr('id') + ',') < 0) {
            HideTM($('#' + openTM.split(',')[0]));
        }
    }
    var r = $(n).closest('tr');
    var dv = $(r).closest('div');
    if ($(dv).attr('disabled') != null) {
        if ($(dv).attr('disabled') == 'disabled') {
            return;
        }
    }
    var menuParent = $(d).parent();
    menuParent.width($(r).width() - 2);
    var theTR = r.parent();
    var positionMenu = function () {
        menuParent.position({
            my: "left top",
            at: "left bottom",
            of: theTR,
            collision: "none"
        });
    };
    // we need to show the element before positioning it, but we want to animate it when it's actually shown...but it needs to animate once it's been positioned
    // so make it invisible and "show" it now for the purpose of positioning it, then hide it again and then we'll show it with the animation now that it's positioned
    menuParent.css({
        visibility: 'hidden'
    });
    menuParent.show();
    positionMenu();
    menuParent.hide();
    menuParent.css({
        visibility: 'visible'
    });
    // need to reposition upon scroll, but only if the dvFormContents div actually exists
    var scrollingDiv = $('#dvFormContents');
    if (scrollingDiv.length) {
        scrollingDiv.on('scroll.teamael', function () {
            positionMenu();
        });
    }
    // now we can actually show with the animation
    menuParent.show('blind');
    var m = 0;
    var ft = '';
    var dir = '';
    var fld = '';
    var smm = '';
    var gid = 0;
    var naa = 0;   //disable auto assign [owner related]
    var co = '';   //config option [owner related]
    var hostsid = 0;  //hostmodule refid
    m = $(dv).attr('mod');
    ft = $(dv).attr('ft');
    fld = $(dv).attr('id').replace('Div','');
    smm = $(dv).attr('srch');  //Search Method
    gid = $(dv).attr('gid');
    dir = $(dv).attr('dir');  //name display direction.  "" = first last, "r" = "last, first"
    if ($(dv).closest('table').closest('td').find('.hypMTM').length > 0) {
        hostsid = $(dv).closest('table').closest('td').find('.hidModRefId').val();
    }
    if ($(dv).attr('naa') != null) {
        naa = $(dv).attr('naa');
    }
    if ($(dv).attr('item') != null) {
        co = $(dv).attr('item');
    }
    if ($(dv).attr('activestatus') == 'load') {  //load the data the first time the control is interacted with
        setTimeout(function () {
            LoadTMData(m, fld, ft, gid, dir, naa, co, hostsid);
        });
    }
    
    $(r).find('input').on('change keyup', function (e) {
        if (e.type == "keyup") {
            if (e.which == 38 || e.which == 40) {
                if (e.timeStamp != eTimeStamp) {
                    ArrowsTM($(r), e.which);
                    eTimeStamp = e.timeStamp;
                }
                return;
            }
            if (e.which == 8 || e.which == 46) {
                $(this).attr('val', '');
            }
        }
        
        setTimeout(function () {
            GetTMData(fld);
        }, 500);
        
    });
    if ($(r).find('input').attr('val') != null) {
        if ($(r).find('input').attr('val') != '') {
            $(r).closest('div').find('.mnuTeamAEL').find('div').removeClass('seldDrop');
            var seld = $(r).closest('div').find('.mnuTeamAEL').find('div[val="' + $(r).find('input').attr('val') + '"]');
            $(seld).addClass('seldDrop');
        }
    }
    openTM = $(d).attr('id') + ',' + $(r).find('input').attr('id') + ',' + $(r).find('.tdTeamAEL').find('img').attr('id') + ',' + $(r).find('.clrTeamAEL').find('img').attr('id') + ',';
    if ($(d).html() == '') {
        if ($(dv).attr('filter') == '') {
            $(d).prepend('Loading...
');
        }
        $(r).find('input').change();
    }
    if (window.top.$('.e-iframe:visible').length == 0) {
        if (window.top.$('.ifrm').length > 0) {
            if ($(d).parent().position().top + $(d).height() > window.top.$('.ifrm').height()) {
                var hght = window.top.$('.ifrm').height() - ($(d).parent().position().top + 10);
                $(d).css('height', hght);
            }
        }
    }
    else {
        if (window.top.$('.e-iframe:visible').length > 0) {
            if ($(d).parent().position().top + $(d).height() > window.top.$('.e-iframe').height()) {
                var hght = window.top.$('.e-iframe').height() - ($(d).parent().position().top + 10);
                $(d).css('height', hght);
            }
        }
    }
    if (ft != 'm2m' && ft != 'atm') {
        $(d).closest('.TeamAEL').find('.inpTeamAEL').blur(function () {
            var mnu = $(this).closest('.TeamAEL').find('.mnuTeamAEL');
            if ($(this).val() != "" && ($(this).attr('val') == '0' || $(this).attr('val') == '')) {
                if ($(mnu).find('.dditem').length > 0) {
                    if ($(mnu).find('.seldDrop').length == 0) {
                        $(mnu).find('.dditem').first().click();
                    }
                }
            }
        });
    }
}
function sortProperties(obj) {
    // convert object into array
    var sortable = [];
    for (var key in obj)
        if (obj.hasOwnProperty(key))
            sortable.push([key, obj[key]]); // each item is an array in format [key, value]
    // sort items by value
    sortable.sort(function (a, b) {
        var x = a[1].toLowerCase(),
            y = b[1].toLowerCase();
        return x < y ? -1 : x > y ? 1 : 0;
    });
    return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}
 
function GetTMData(fld) {
    var obj = TMData[fld + 'Data'];
    $('#' + fld + 'Mnu').empty();
    var inp = $('#' + fld).val();
    var arr = sortProperties(obj);
    arr.forEach(function (item) {
        var iVal = item[1];
        var iKey = item[0];
        if (inp != '') {
            if (iVal.toLowerCase().indexOf(inp.toLowerCase()) > -1) {
                $('#' + fld + 'Mnu').append('' + iVal + '
');
            }
        }
        else {
            $('#' + fld + 'Mnu').append('' + iVal + '
');
        }
    });
    //for (var key in obj) {
    //    if (obj.hasOwnProperty(key)) {
    //        if (inp != '') {
    //            if (obj[key].toLowerCase().indexOf(inp.toLowerCase()) > -1) {
    //                $('#' + fld + 'Mnu').append('' + obj[key] + '
');
    //            }
    //        }
    //        else {
    //            $('#' + fld + 'Mnu').append('' + obj[key] + '
');
    //        }
    //    }
    //}
    SelectTMFirst($('#' + fld));
}
function SelectTMFirst(r) {
    $(r).closest('div').find('.mnuTeamAEL').find('div').removeClass('seldDrop');
    var seld = $(r).closest('div').find('.mnuTeamAEL').find('.dditem').first();
    $(seld).addClass('seldDrop');
}
function clearTMVal(n) {
    var r = $(n).closest('tr');
    if ($(r).closest('div').attr('disabled') == 'disabled') {
        return;
    }
    $(r).find('input').val('');
    $(r).find('input').attr('val', '');
    $(r).closest('div').find('.mnuTeamAELWrap').find('.mnuTeamAEL').html('');
    ShowTM($(r).find('input'));
}
function SetTMVal(n) {
    var inp = $(n).parent().parent().parent().find('input');
    var dv = $('#' + $(inp).attr('id') + 'Div');
    if ($(dv).attr('ft') == 'm2m') {
        //$(n).parent().find('div').removeClass('seldDrop');
        var fldName = $(inp).attr('id');
        var modid = $(dv).attr('mod');
        var relmod = $(dv).attr('item');
        var modrefid = $(dv).closest('table').closest('td').find('.hidModRefId').val();
        var selVal = $(n).attr('val');
        var selText = $(n).html();
        if (fldName.indexOf('_') > -1) {
            fldName = fldName.split('_')[1];
        }
        var addPos = 'After';
        if (window.top.location.href.indexOf('profile.aspx') > -1) {
            addPos = 'Before';
        }
        SaveManyToManyFromPlugin(selVal, selText, fldName, modid, modrefid, relmod, addPos);
    }
    else if ($(dv).attr('ft') == 'atm') {
        $(n).parent().find('div').removeClass('seldDrop');
        var fldName = $(inp).attr('id');
        var selVal = $(n).attr('val');
        AddTeammemberFromPlugin($('#' + fldName),selVal);
    }
    else {
        $(inp).attr('val', $(n).attr('val'));
        if ($('#' + $(inp).attr('id') + '_rel').length > 0) {
            $('#' + $(inp).attr('id') + '_rel').val($(n).attr('val'));
        }
        if ($(n).html() == '') {
            $(inp).val('');
        }
        else {
            $(inp).val($(n).html());
        }
        $(n).parent().find('div').removeClass('seldDrop');
        $(n).addClass('seldDrop');
        if ($(inp).parent().closest('div').attr('trig') != null) {
            RepopDTTs($(inp));
        }
    }
    //if ($(n).closest('.TeamAEL').attr('elid') != -1 &&
    //    $(n).attr('val') != '0' &&
    //    $(n).attr('val') != '') {
    //    $(n).closest('.TeamAEL').find('a').show();
    //}
    //else {
    //    $(n).closest('.TeamAEL').find('a').hide();
    //}
    $(inp).change();
}
function ArrowsTM(r, val) {
    switch (val) {
        case 38:
            var sd = $(r).find('input').closest('div').find('.seldDrop');
            if (sd.length == 0) {
                SetTMVal($(r).find('input').closest('div').find('.dditem').first());
                event.preventDefault();
                return false;
            }
            else {
                sd = $(sd).prev();
                if (sd.length != 0) {
                    SetTMVal($(sd));
                    event.preventDefault();
                    return false;
                }
            }
            break;
        case 40:
            var sd = $(r).find('input').closest('div').find('.seldDrop');
            if (sd.length == 0) {
                SetTMVal($(r).find('input').closest('div').find('.dditem').first());
                event.preventDefault();
                return false;
            }
            else {
                sd = $(sd).next();
                if (sd.length != 0) {
                    SetTMVal($(sd));
                    event.preventDefault();
                    return false;
                }
            }
            break;
    }
}
function HideTM(n) {
    openTM = "";
    $(n).parent().hide('blind');
    // need to turn off the scroll event, but only if this div exists
    var scrollingDiv = $('#dvFormContents');
    if (scrollingDiv.length) {
        $('#dvFormContents').off('scroll.teamael');
    }
    if ($(n).closest('.TeamAEL').attr('elid') != -1 &&
        $(n).closest('.TeamAEL').find('input').attr('val') != '0'
        && $(n).closest('.TeamAEL').find('input').attr('val') != '') {
        $(n).closest('.TeamAEL').find('a').show();
    }
    else {
        $(n).closest('.TeamAEL').find('a').hide();
    }
}