﻿
jQuery.facebookCache = [];
jQuery.facebooklist = function(elem, list, complete, ajax, height, filter, newel) {
    var keyEnter = 13;
    var keySemiCollon = 59;
    var keyCollon = 188;
    var keySpace = 32;
    var keyBackspace = 8;
    var exceptionAutoComplete = [];
    var addHiddenInput = function(value) { var input = document.createElement('input'); $(input).attr({ 'type': 'hidden', 'name': (elem.attr('id') + '[]'), 'id': (elem.attr('id') + '[]'), 'value': value }); return input; }
    var getChar = function(e) {
        if (window.event) { keynum = e.keyCode; }
        else
            if (e.which) { keynum = e.which; }
        if (keynum == 8)
            return ''; return String.fromCharCode(keynum);
    }
    var addItem = function(item, preadded) {
        //        var title = item.text();
        //        var value = title;
        var title = item.text().replace(/\&nbsp;/ig, '');
        var value = (item.attr('title') && item.attr('title') != -1 ? item.attr('title') : title);
        var li = document.createElement('li');
        var txt = document.createTextNode(value);
        var aclose = document.createElement('a');
        var input = addHiddenInput(value);

        var hasSelected = false;
        $("#ceeYourContactList div.list div[title=" + title.toLowerCase() + "]").each(function() {
            if ($(this).hasClass('selected')) hasSelected = true;
            else $(this).addClass('selected');
        });
        if (hasSelected) { $("ul.holder li.bit-box:contains('" + title + "')").remove(); };

        $(li).attr({ 'class': 'bit-box' });
        $(li).prepend(txt);
        $(aclose).attr({ 'class': 'closebutton', 'href': '#' });
        li.appendChild(aclose);
        li.appendChild(input);
        $(li).insertBefore($('input.maininput').parent());
        $(aclose).click(function() {
            $(this).parent('li').fadeOut('fast', function() {
                var removemail = $(this).find('input').val();
                $("#ceeYourContactList div.list div[title=" + removemail.toLowerCase() + "]").removeClass('selected');
                $(this).remove();
            });
            return false;
        });
        if (!preadded) {
            holder.removeChild(document.getElementById('annoninput'));
            addInput();
        }
        feed.hide();
        $('.default').show();
        $('.error').hide();
    }
    var defaultFilter = function(input) {
        if (filter.userfilter) {
            var flag; feed.children('li:not([fckb])').removeClass('hidden'); $.each(feed.children('li:not([fckb])'), function(i, val) {
                var item = $(val); if (filter.casesensetive) { flag = item.text().indexOf(input); item.html(item.text().replace(input, '<em>' + input + '</em>')); }
                else { flag = item.text().toLowerCase().indexOf(input.toLowerCase()); item.html(item.text().replace(input, '<em>' + input + '</em>')); }
                if (flag == -1) { item.addClass('hidden'); }
                else { counter++; }
            });
        }
        else { counter += feed.children('li:not([fckb])').length; }
        if (counter > height) { feed.css({ 'height': (height * 24) + 'px', 'overflow': 'auto' }); }
        else { feed.css('height', 'auto'); }
    }
    var feedFilter = function(item, caption, input) {
        if (filter.userfilter) {
            if (filter.casesensetive) { if (caption.indexOf(input) != -1) { item.html(caption.replace(input, '<em>' + input + '</em>').replace(/\s/ig, "&nbsp;")); return true; } }
            else { if (caption.toLowerCase().indexOf(input) != -1) { item.html(caption.replace(input, '<em>' + input + '</em>').replace(/\s/ig, "&nbsp;")); return true; } }
        }
        else { item.html(caption.replace(input, '<em>' + input + '</em>').replace(/\s/ig, "&nbsp;")); return true; }
    }
    var addItemFeed = function(data, input) {
        feed.children('li[fckb=2]').remove();
        $.each(data, function(i, val) {
            if (val.caption) {
                var li = document.createElement('li');
                $(li).attr({ 'title': val.value + '', 'fckb': '2' });
                if (feedFilter($(li), val.caption + '', input)) {
                    feed.append(li); counter++;
                }
            }
        });
        defaultFilter(input);
    }
    var addTextItemFeed = function(value) { if (newel) { feed.children('li[fckb=1]').remove(); var li = document.createElement('li'); $(li).attr({ 'value': value, 'fckb': '1' }); $(li).html(value); feed.prepend(li); counter++; } }
    var removeFeedEvent = function() { feed.children('li').unbind('mouseover'); feed.children('li').unbind('mouseout'); feed.mousemove(function() { bindFeedEvent(); feed.unbind('mousemove'); }) }
    var bindFeedEvent = function() { feed.children('li').mouseover(function() { feed.children('li').removeClass("auto-focus"); $(this).addClass("auto-focus"); nowFocusOn = $(this); }); feed.children('li').mouseout(function() { $(this).removeClass("auto-focus"); nowFocusOn = null; }); }
    var bindEvents = function() {
        var maininput = $('.maininput'); bindFeedEvent(); feed.children('li').unbind('click'); feed.children('li').click(function() { addItem($(this)); complete.hide(); }); maininput.unbind('keydown'); maininput.keydown(function(event) {
            if (event.keyCode == 13 && nowFocusOn != null) { addItem($(nowFocusOn)); complete.hide(); event.preventDefault(); }
            if (event.keyCode == 40) {
                removeFeedEvent(); if (typeof (nowFocusOn) == 'undefined' || nowFocusOn.length == 0) { nowFocusOn = $(feed.children('li:visible:first')); feed.get(0).scrollTop = 0; }
                else { nowFocusOn.removeClass("auto-focus"); nowFocusOn = nowFocusOn.nextAll('li:visible:first'); var prev = parseInt(nowFocusOn.prevAll('li:visible').length, 10); var next = parseInt(nowFocusOn.nextAll('li:visible').length, 10); if ((prev > Math.round(height / 2) || next <= Math.round(height / 2)) && typeof (nowFocusOn.get(0)) != 'undefined') { feed.get(0).scrollTop = parseInt(nowFocusOn.get(0).scrollHeight, 10) * (prev - Math.round(height / 2)); } }
                feed.children('li').removeClass("auto-focus"); nowFocusOn.addClass("auto-focus");
            }
            if (event.keyCode == 38) {
                removeFeedEvent(); if (typeof (nowFocusOn) == 'undefined' || nowFocusOn.length == 0) { nowFocusOn = $(feed.children('li:visible:last')); feed.get(0).scrollTop = parseInt(nowFocusOn.get(0).scrollHeight, 10) * (parseInt(feed.children('li:visible').length, 10) - Math.round(height / 2)); }
                else { nowFocusOn.removeClass("auto-focus"); nowFocusOn = nowFocusOn.prevAll('li:visible:first'); var prev = parseInt(nowFocusOn.prevAll('li:visible').length, 10); var next = parseInt(nowFocusOn.nextAll('li:visible').length, 10); if ((next > Math.round(height / 2) || prev <= Math.round(height / 2)) && typeof (nowFocusOn.get(0)) != 'undefined') { feed.get(0).scrollTop = parseInt(nowFocusOn.get(0).scrollHeight, 10) * (prev - Math.round(height / 2)); } }
                feed.children('li').removeClass("auto-focus"); nowFocusOn.addClass("auto-focus");
            }
        });
    }

    var manualAdd = function(input, event) {
        var isExit = false;
        var etext = $.trim($(input).val());
        if (event.keyCode != keyEnter && event.keyCode != keySpace) etext = etext.substring(0, etext.length - 1);

        $(input).val(etext);

        var emailArr = etext.split(/,|;|\s/);

        var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

        for (var i = 0; i < emailArr.length; i++) {
            var itext = $.trim(emailArr[i]);
            //$(input).parent().remove();
            //$(".annoninput").remove();
            if (itext !== "" && re.test(itext)) {
                //nowFocusOn = $("<li>" + itext + "</li>");
                addItem($("<li>" + itext + "</li>"), 1);
                isExit = true;
                feed.hide();
                $('.error').hide();
                $('.default').show();
            }
            if (itext != "" && !re.test(itext)) {
                feed.hide();
                $('.default').hide();
                $('.error').show();
            }
        }
        $(input).val('');
        //addInput();
        return isExit;
    }


    if (typeof (jQuery.facebookManualAdd) !== 'function')
    { jQuery.facebookManualAdd = manualAdd; }

    var addInput = function() {
        nowFocusOn = undefined;
        var li = document.createElement('li');
        var input = document.createElement('input');
        $(li).attr({ 'class': 'bit-input', 'id': 'annoninput' });
        $(input).attr({ 'type': 'text', 'class': 'maininput' });
        li.appendChild(input);
        holder.appendChild(li);
        $(input).focus(function() {
            complete.fadeIn('fast');
        });
        $(holder).click(function() {
            $(input).focus();
            if (feed.length && $(input).val().length) { feed.show(); }
            else {
                feed.children('li[fckb=2]').remove();
                feed.children('li').addClass('hidden');
                feed.css('height', '0px');
                $('.default').show();
                $('.error').hide();
            }
        });
        var del = true;


        $(input).keyup(function(event) {


            if (event.keyCode != 40 && event.keyCode != 38) {
                var isExit = false;

                if ($.browser.msie) keySemiCollon = 186;

                if (event.keyCode == keyEnter || event.keyCode == keySemiCollon || event.keyCode == keyCollon || event.keyCode == keySpace) {
                    isExit = manualAdd(input, event);
                }

                if (!isExit) {
                    counter = 0;
                    var etext = $(input).val();
                    if ($.trim(etext) == "" && event.keyCode == keyBackspace && del) {
                        var l = $('ul.holder li.bit-box:last input');
                        if (l.length > 0) {
                            $("#ceeYourContactList div.list div[title=" + l.val().toLowerCase() + "]").removeClass('selected');
                            l.parent().remove();
                        }
                    }

                    if (etext != "") del = false;
                    else del = true;
                    var findcache = function(cache, etext) {
                        var found = 0;
                        if (cache.length > 0) {
                            for (var c in cache) {
                                if (cache[c]['caption'].toString().indexOf(etext) > -1) found++;
                            }
                        }

                        return found;
                    }


                    addTextItemFeed(etext);
                    etext = etext.toString();
                    if (ajax.url) {

                        var found = findcache(jQuery.facebookCache, etext);
                        if (found <= 3 && etext.length > 3) found = 3;
                        if (ajax.cache && jQuery.facebookCache.length > 0 && found > 5) {
                            addItemFeed(jQuery.facebookCache, etext);
                            bindEvents();
                        }
                        else {
                            $.getJSON(ajax.url, { tag: etext }, function(data) {
                                addItemFeed(data, etext);
                                jQuery.facebookCache = data;
                                bindEvents();
                            });
                        }
                    }
                    else { bindEvents(); }
                    $('.default').hide(); feed.show();
                }

            }

        });

    }

    if (typeof (elem) != 'object') { elem = $(elem); }
    if (typeof (list) != 'object') { list = $(list); }
    if (typeof (complete) != 'object') { complete = $(complete); }
    var feed = $('#feed');
    var counter = 0;
    var nowFocusOn;
    var holder = document.createElement('ul');
    elem.css('display', 'none');
    $(holder).attr('class', 'holder');
    if (list && list.children('li').length) {
        $.each(list.children('li'), function(i, val) {
            addItem($(list.children('li')[i]), 1);
        });
    }
    addInput();

    elem.before(holder);
    $(document).click(function(event) {

        if ($(event.target).attr('class') != 'holder' && $(event.target).attr('class') != 'maininput') {
            $('.default').hide();
            $(feed).hide();
            if (!manualAdd('.maininput', { keyCode: keyEnter })) {
                $('.maininput').val('');
            } else { $(".annoninput input.maininput").focus(); }
        }
    });
}

function ceeContactListInit() {
    $(document).ready(function() {
        var ceeyourlist = {
            viewby: function(by) {
                by = $.trim(by.toLowerCase());
                if (by == "all") {
                    $("#ceeYourContactList .list div.mailing").show();
                } else if (by == "other") {
                    $("#ceeYourContactList .list div.mailing").hide();
                    $("#ceeYourContactList .list div.mailing").each(function() {
                        if (!/^[a-z]/i.test($(this).attr('title')) || !/^[a-z]/i.test($(this).find("div.mname").attr('title')))
                            $(this).show();
                    });
                } else {
                    $("#ceeYourContactList .list div.mailing").hide();
                    $("#ceeYourContactList .list div.mailing[title^=" + by + "]").show();
                    $("#ceeYourContactList .list div.mname[title^=" + by + "]").parent().show();
                }

            },
            search: function(kw) {
                $("#ceeYourContactList .list div.mailing").hide();
                $("#ceeYourContactList .list div.mailing[title*=" + kw + "]").show();
                $("#ceeYourContactList .list div.mname[title*=" + kw + "]").parent().show();
            }
        };


        $("#ceeYourContactList .alphabet div").unbind('click').click(function() {
            ceeyourlist.viewby($(this).text());
            //var numshow = $("#ceeYourContactList .list div.mailing:visible").length;
            //$('#ceeYourContactList div.header span').text(numshow);
        }).parent().show();

        $("#ceeYourContactList div.list div.mailing").click(
                  function() {
                      if ($(this).hasClass("selected")) {
                          $(this).removeClass("selected");
                          var title = $.trim($(this).attr('title'));
                          if (title != "")
                              $("ul.holder li.bit-box:contains('" + title + "')").remove();
                      } else {
                          $(this).addClass("selected");
                          if (typeof (jQuery.facebookManualAdd) == 'function') {
                              $('.maininput').val($(this).attr('title'));
                              jQuery.facebookManualAdd('.maininput', { keyCode: 13 });
                          }
                      }
                  }
            );
        $('#ceeYourContactList div.header span').text($("#ceeYourContactList div.list div.mailing:visible").length);
    });


}
ceeContactListInit();
