/*
FullSelectLc - wariacje js z selectem
fr,
Paginacja,
MultiSelect,
Ikony

Struktura Listy ul->li ( input[checkbox], span, a:hover  )

*/
(function($)
{
	$.fn.fullSelectLc = function (opt)
	{
        window.setId = (window.setId==undefined)?0:(window.setId+1);
        $(this).attr('rel',setId);
        var d =
        {
            multiselect : false,
            search : false,
            searchText : 'Search...',
            ajax : false,
            paging : false,
            specialelement : false,
            className : '',
            name : 'defaultName',
            moreLink : false,
            search : false,
            searchTextResults : 'Total: ',
            customLinkMask : false,
            keyEv : false,
            onFocusInput : false,
            onBlurInput : false,
            insertValueToArrayName : false,
            setListSize : 'toParentWidth',
            debug : false

        }
        opt = $.extend({}, d, opt);
        window.fsLc = (window.fsLc==undefined)?{}:window.fsLc;
        fsLc[setId] =
        {
            init : function($c,opt)
            {
                window.timeOutStamp = {
                    wait : function (param)
                    {
                        delete timeOutStamp[param];
                    }
                };
                var $that = $($c);
                var id = $($c).attr('rel');
                fsLc[id].that = $that;
                var $container = $('<div class="FullSelectLcContainer FullSelectLcContainerDefault close"></div>').addClass(opt.className);
                var $input = $('<input class="FullSelectLcInput inputLc" type="text" />')
                .attr('readonly','readonly')
                .bind(
        		{
        			'click' : function(e)
                    {
                        $($that).parent().find('.buttonLc').focus().trigger('click');
                    	e.stopPropagation();
                    },
        			'focus' : function(e)
                    {
                        $($that).parent().find('.buttonLc').focus().trigger('click');
                    	e.stopPropagation();
                    },
        			'keydown' : function(e)
                    {
                        fsLc[id].onKeyDown(e, this, $that);
                        e.stopPropagation();
                    }
        		});
                var $inputNon = $('<input class="FullSelectLcInput inputNon" style="display:none;" type="text" />')
                .attr('readonly','readonly')
                .bind(
        		{
        			'focus' : function(e)
                    {
                    	if (opt.onFocusInput)
                		{
                    		opt.onFocusInput( $(this), $that, $that.attr('id') );
                		}
                    },
        			'blur' : function(e)
                    {
                    	if (opt.onBlurInput)
                		{
                    		opt.onBlurInput( $(this), $that,  $that.attr('id') );
                		}
                    }
        		});
                if ($that.attr('tabindex')!=undefined)
                	{
                		$input.attr('tabindex',$that.attr('tabindex'));
                	}

                var $inputsearch = $('<input class="FullSelectLcInput searchLc" type="text" />')
                    .val(opt.searchText)
                    .bind({
                        'click' : function(e)
                        {
                            $(this).val('');
                            fsLc[id].onSearch(this, $that);
                            e.stopPropagation();
                        },
                        'keyup' : function(e)
                        {
                            fsLc[id].onSearch(this, $that);
                            e.stopPropagation();
                        },
	        			'keydown' : function(e)
	                    {
	                        fsLc[id].onKeyDown(e, this, $that);
	                        e.stopPropagation();
	                    }
                    });
                var $buttonInput = $('<input type="button" class="FullSelectLcButton buttonLc" value="&#x25BC;"/>')
                .bind(
        		{
        			'click' : function(e)
                    {
                        fsLc[id].onShowClose(this, $that);
                        e.stopPropagation();
                    },
        			'keydown' : function(e)
                    {
                        fsLc[id].onKeyDown(e, this, $that);
                        e.stopPropagation();
                    }
        		});

                var $customElem = $('<div class="FullSelectLcCustomElem1 custom1Lc"></div>').css({'opacity':0});

                var $containerList = $('<div class="FullSelectLcContainerList"></div>')
                    .bind('click',function(e)
                    {
                        e.stopPropagation();
                    });

                fsLc[id].getOptionValue($that);
                fsLc[id].waitForAjax = function()
                {
                    if (fsLc[id].table==undefined)
                    {
                        setTimeout('fsLc["'+[id]+'"].waitForAjax()',30);
                        return false;
                    }

                    var inputValue = fsLc[id].setInputValue($that, fsLc[id].table);
                    var list = fsLc[id].createList($that, fsLc[id].table);
                    var listMore = fsLc[id].createListMore($that, fsLc[id].table);
                    $input.val(inputValue);

					$customElem.animate(
						{
							'opacity':1
						},
						{
							'queue' : false,
							'duration' : 500
						}).prependTo($containerList);

					list.appendTo($containerList);
                    listMore.appendTo($containerList);

                    $input.appendTo($container);
                    $inputNon.appendTo($container);
                    $inputsearch.appendTo($container);
                    $buttonInput.appendTo($container);
                    $containerList.appendTo($container);

                    $that.after($container);
                    $that
                        .css({'display':'none'})
                        .removeAttr('name')
                        .appendTo($container);

                    var $body = $('body')
                    .unbind('click')
                    .bind(
                    {
                    	'click' : function(e)
	                    {
	                        fsLc[id].closeOpened(this);
	                        e.stopPropagation();
	                    },
	                	'keydown, keyup' : function(e)
	                    {
	                        e.stopPropagation();
	                    }
                    });

                    if (opt.onAfterLoad)
                    {
                    	opt.onAfterLoad($that, fsLc[id].table);
                    }

                    switch (opt.setListSize)
                    {
	                	case 'toParentWidth':
	                	break;
	                	default :
	                		$containerList.css({'width': opt.setListSize});
	                	break;
                    }
                }
                fsLc[id].waitForAjax();
            },
            getOptionValue : function(that)
            {
                var id = $(that).attr('rel');
                if (!opt.ajax)
                {
                    var table =
                    {
                       total_results : 0,
                       results : [],
                       selected : []
                    };

                    that.find('option').each(function()
                    {
                        var l = table.results.length;
                        table.results[l] = { value : $(this).val(), name : $(this).text(), title:(($(this).attr('title')==undefined)?'':$(this).attr('title')) };
                    });
                    table.total_results = that.find('option').length;
                    that.find('option:selected').each(function()
                    {
                        var l = table.selected.length;
                        table.selected[l] = { value : $(this).val(), name : $(this).text() };
                    });

                    fsLc[id].table = table;
                }
                else
                {
                    $.ajax({
                      type: "GET",
                      url: opt.ajax,
                      success: function(table)
                      {
                        var j = eval("(" + table + ")");
                        fsLc[id].table = j.table;
                      }
                    });
                }

            },
            setInputValue : function(that, table)
            {
            	var val = [];
                var separator = '; ';
                var option = $(that).find('option');
                option.removeAttr('selected');

                for (i = 0; i < table.selected.length ; i++ )
                {
                    val[val.length] = table.selected[i].name;
                    that.find('option[value="'+table.selected[i].value+'"]').attr('selected','selected');
                }
                return val.join(separator)
            },
            createList : function(that, table)
            {
                var id = $(that).attr('rel');
                var name = (that.attr('name') != undefined)?that.attr('name'):opt.name;
                var ul = (that.find('.list').get(0)==undefined)?$('<ul></ul>').addClass('list'):that.find('.list');
                var li = $('<li></li>');
                var checkbox = $('<input type="checkbox" />');
                var span = $('<span></span>');
                var a = $('<a href="#"></a>');

                if (opt.addCheckAll)
                {
                    var newLi = li.clone();
                    var newCheckbox=checkbox.clone();
                    var newSpan = span.clone();
                    var newA = a.clone();

                    newLi.addClass('checkAll');
                    newCheckbox
                        .attr('name','')
                        .val('')
                        .appendTo(newLi)

                    newSpan
                        .text(opt.addCheckAll)
                        .appendTo(newLi);

                    newLi.bind(
            		{
        			'click':function(e)
                    {
            			if ($(this).hasClass('all')==false)
            				{
            					var notSelectedLi = $(this).parent().find('li').not('.selected').not('.checkAll');
            					notSelectedLi.trigger('click');
            					$(this).addClass('all');
            				}
            			else
            				{
	        					var selectedLi = $(this).parent().find('li.selected').not('.checkAll');
            					selectedLi.trigger('click');
            					$(this).removeClass('all');
            				}
            			e.stopPropagation();
                    }
            		});
                    newLi.appendTo(ul);
                }

                for (i = 0; i < table.results.length; i++)
                {
                    var newLi = li.clone();
                    var newCheckbox=checkbox.clone();
                    var newSpan = span.clone();
                    var newA = a.clone();
                    var sufix = '[]';

                    if (opt.insertValueToArrayName)
                    {
                    	sufix = '['+table.results[i].value+']';
                    }

                    if (table.results[i].title!='')
                    	{
                    		newLi.
                    			attr('title',table.results[i].title);
                    	}
                    newCheckbox
                        .attr('name',(name+sufix).replace(/\[\]\[\]/g,'[]'))
                        .val(table.results[i].value)
                        .appendTo(newLi)

                    newSpan
                    	.text(table.results[i].name)
                        .attr('rel',table.results[i].name.toLowerCase())
                        .appendTo(newLi);

                    newLi.bind(
            		{
        			'click':function(e)
                    {
                        fsLc[id].onClickLi(this, that, table);
                        if (opt.onClickLiAfter)
                    	{
                    		opt.onClickLiAfter(this, that, table);
                    	}
                        if (opt.addCheckAll)
                    	{
                        	fsLc[id].onCheckAll(this, that, table);
                    	}
                    }
            		});

                    newLi.hover(
                		function(e)
                        {
                            fsLc[id].onHoverLi(this, that, table);
                        },
	            		function(e)
	                    {
	                        fsLc[id].onHoverLi(this, that, table);
	                    });

                    for (l = 0; l < table.selected.length; l++)
                    {
                        if (table.selected[l].value == table.results[i].value)
                        {
                            newCheckbox.attr('checked','checked');
                            newLi.addClass('selected');
                        }
                    }

                    if (opt.paging && !opt.ajax)
                    {
                        if (opt.paging <= i )
                        {
                            newLi.addClass('none');
                        }
                    }
                    if (!opt.multiselect)
                    {
                        newCheckbox.css({'display':'none'})
                    }
                    if (opt.customLinkMask)
                    {
                        var a = opt.customLinkMask
                        	.replace('[[title]]',table.results[i].title)
                            .replace('[[val]]',table.results[i].value)
                            .replace('[[name]]',table.results[i].name);
                        a = $(a)
                            .bind('click',function(e)
                                {
                                    e.stopPropagation();
                                })
                            .appendTo(newLi);
                    }
                    newLi.appendTo(ul);
                }
                if (opt.addCheckAll)
            	{
                	fsLc[id].onCheckAll(newLi, that, table);
            	}
            return ul;
            },
            createListMore : function(that, table)
            {
            	var id = $(that).attr('rel');
                var ul = $('<ul class="more" style="display:none;"></ul>');
                var li = $('<li></li>');
                var checkbox = $('<input type="checkbox" />');
                var span = $('<span></span>');
                var a = $('<a href="#"></a>');

                if (opt.paging && opt.paging < parseInt(table.total_results))
                {
                    var newLi = li.clone().addClass('paging');
                    span
                        .clone()
                        .text('prev')
                        .addClass('prev disabled')
                        .attr('rel',0)
                        .bind('click',function(){ fsLc[id].prevNext(this,that); } )
                        .appendTo(newLi);

                    span
                        .clone()
                        .text('next')
                        .addClass('next enabled')
                        .attr('rel',opt.paging)
                        .bind('click',function(){ fsLc[id].prevNext(this,that); } )
                        .appendTo(newLi);
                    newLi.appendTo(ul);
                }

                if (opt.moreLink && typeof(opt.moreLink)=='object')
                {
                    for (i = 0; i < opt.moreLink.length; i++)
                    {
                    var newLi = li.clone();
                    $('<span>'+opt.moreLink[i]+'</span>')
                        .appendTo(newLi);
                        newLi.appendTo(ul);
                    }

                }

                if ( (opt.moreLink && typeof(opt.moreLink)=='object') || (opt.paging && opt.paging < parseInt(table.total_results)) )
                {
                    ul.removeAttr('style');
                }

            return ul;
            },
            prevNext : function(t, that)
            {
                var id = $(that).attr('rel');
                var n = $(t).parent().find('.next');
                var p = $(t).parent().find('.prev');
                var l = $(t).parents('.FullSelectLcContainer').find('.list');
                var hover = l.find('.hover');

                hover.removeClass('hover');

                var setElementClass = function(p,n,length)
                {
                   var pR = parseInt(p.attr('rel'));
                   var nR = parseInt(n.attr('rel'));
                   if ( pR <= 0 )
                   {
                        p.addClass('disabled').removeClass('enabled');
                   }
                   else
                   {
                        p.removeClass('disabled').addClass('enabled');
                   }

                   if ( nR >= length )
                   {
                        n.addClass('disabled').removeClass('enabled');
                   }
                   else
                   {
                        n.removeClass('disabled').addClass('enabled');
                   }
                }
                if (!opt.ajax)
                {
                    var ll = l.find('li').length;
                    if (( $(t).hasClass('prev') || $(t).hasClass('next') ) && $(t).hasClass('enabled')  )
                    {
                       var z = ($(t).hasClass('prev'))?-1:1;
                       n.attr('rel',(parseInt(n.attr('rel'))+(opt.paging*z)));
                       p.attr('rel',(parseInt(p.attr('rel'))+(opt.paging*z)));
                       l.find('li').each(function(index)
                       {
                            if (!$(this).hasClass('selected'))
                            {
                                $(this).addClass('none');
                            }
                            if (index >= p.attr('rel') && index < n.attr('rel'))
                            {
                                $(this).removeClass('none');
                            }
                       });
                       setElementClass(p,n,ll);
                    }
                }
                else
                {

                	var ll = parseInt(fsLc[id].table.total_results);
                    if (( $(t).hasClass('prev') || $(t).hasClass('next') ) && $(t).hasClass('enabled')  )
                    {

                    	var paging = $(that).parent().find('.paging');
                        var loading = $('<div>Loading ...</div>')
                        	.css({'opacity':0})
                        	.addClass('loadingLc')
                            .animate(
                                {
                                    'opacity':1
                                },
                                {
                                    'queue' : false,
                                    'duration' : 100
                                }
                            )
                        	.appendTo(paging);

                       var z = ($(t).hasClass('prev'))?-1:1;
                       n.attr('rel',(parseInt(n.attr('rel'))+(opt.paging*z)));
                       if ($(t).hasClass('prev'))
                       {
                           var page = (parseInt($(t).attr('rel'))==0)?1:(parseInt($(t).attr('rel'))/(opt.paging));
                           p.attr('rel',(parseInt(p.attr('rel'))+(opt.paging*z)));
                       }
                       else
                       {
                           p.attr('rel',(parseInt(p.attr('rel'))+(opt.paging*z)));
                           var page = (parseInt($(t).attr('rel'))==0)?1:(parseInt($(t).attr('rel'))/(opt.paging));
                       }

                            $.ajax({
                              type: "GET",
                              url: opt.ajax+page,
                              success: function(table)
                              {
                                var j = eval("(" + table + ")");
                                var s = [];
                                var r = [];
                                fsLc[id].table = j.table;

                                if (opt.multiselect)
                                {
	                                l.find('li.selected').each(function(index)
	                                {
	                                        var t = 0;
	                                        for (i = 0; i < fsLc[id].table.results.length; i++)
	                                        {
	                                            if (fsLc[id].table.results[i].value == $(this).find('input[type="checkbox"]').val())
	                                            {
	                                                t = 1;
	                                                break;
	                                            }
	                                        }
	                                        if (t==0)
	                                        {
	                                            r[r.length] = {'value':$(this).find('input[type="checkbox"]').val(),'name':$(this).find('span').text()};
	                                        }

	                                        var v = 0;
	                                        for (i = 0; i < fsLc[id].table.selected.length; i++)
	                                        {
	                                            if (fsLc[id].table.selected[i].value == $(this).find('input[type="checkbox"]').val())
	                                            {
	                                                v = 1;
	                                                break;
	                                            }
	                                        }
	                                        if (v==0)
	                                        {
	                                            s[s.length] = $(this).find('input[type="checkbox"]').val();
	                                        }
	                                });
                                }

                                fsLc[id].table.selected = s.concat(fsLc[id].table.selected);
                                fsLc[id].table.results = r.concat(fsLc[id].table.results);
                                var nUl = fsLc[id].createList(fsLc[id].that, fsLc[id].table);
                                var oUl = $(fsLc[id].that).parent().find('ul.list');
                                oUl.after(nUl);
                                oUl.remove();
                                setElementClass(p,n,ll);

                            	loading.animate(
                                    {
                                        'opacity':0
                                    },
                                    {
                                        'queue' : false,
                                        'duration' : 500,
                                        'complete' : function()
                                        {
                                    	loading.remove();
                                        }
                                    }
                                );
                              }
                            });
                    }


                }
            },
            closeOpened : function (el)
            {
                var opened = $('.FullSelectLcContainer.open').find('.buttonLc').each(function()
                {
                    if ($(el).get(0) != $(this).get(0))
                    {
                      $(this).trigger('click');
                    }
                });

            },
            onSearch : function (t, that)
            {
                var id = $(that).attr('rel');
                var t = $(t);
                var p = t.parent();
                var v = t.val();

                if (timeOutStamp.search==undefined && v.length>2)
                {
                    p.find('.paging').css({'display':'none'});
                    if (!opt.ajax)
                    {
                        var li = p.find('.list li');
                        var c = 0;
                        li.each(function()
                        {
                            if ($(this).find('span').text().toLowerCase().indexOf(v.toLowerCase()) != -1)
                            {
                                c++;
                                $(this).removeClass('none');
                            }
                            else
                            {
                                $(this).addClass('none');
                            }
                        });

                    }
                    else
                    {
                        $.ajax({
                          type: "GET",
                          url: opt.search+v,
                          success: function(table)
                          {
                            var j = eval("(" + table + ")");
                            fsLc[id].table = j.table;

                            var nUl = fsLc[id].createList(fsLc[id].that, fsLc[id].table);
                            var oUl = $(fsLc[id].that).parent().find('ul.list');

                            p.find('.searchCountResults').text( nUl.find('li').length );
                            oUl.after(nUl);
                            oUl.remove();
                          }
                        });
                    }

                    // total results
                    if (p.find('.searchlist').get(0))
                    {
                        var sl = p.find('.searchlist');
                    }
                    else
                    {
                        var sl = $('<ul class="searchlist"></ul>');
                        var slli = $('<li></li>').appendTo(sl);
                        var slspant = $('<span class="searchTextResults">'+opt.searchTextResults+'</span>').appendTo(slli);
                        var slspanc = $('<span class="searchCountResults"></span>').appendTo(slli);
                        var slspanr = $('<span class="searchRemoveResults">x</span>')
                            .bind('click',function(e)
                            {
                                fsLc[id].onRemoveSearchResults(that);
                                e.stopPropagation();
                            })
                            .appendTo(slli);



                        p.find('.list').before(sl);
                    }
                    sl.find('.searchCountResults').text(c);

                    timeOutStamp.search = setTimeout('timeOutStamp.wait("search")',300);
                }
                else
                {
                    return false;
                }
            },
            onShowClose : function (t, that)
            {
                var id = $(that).attr('rel');
                if (opt.onShowClose)
                {
                    opt.onShowClose(t);
                    return false;
                }

                var p = $(t).parent();
                // zamknij otwarte
                fsLc[id].closeOpened(t);

                if (p.hasClass('close'))
                {
                    if (opt.search)
                    {
                        p.find('.searchLc').css('z-index',10000);
                    }
                    //$(t).val('\u25B6');
                    switch (opt.setListSize)
                    {
	                	case 'toParentWidth':
	                	break;
	                	default :
	                		p.find('.FullSelectLcContainerList').css({'width': opt.setListSize});
	                	break;
                    }

                    p.find('.inputNon').focus();
                    p
                        .css({'z-index':10000})
                        .find('.FullSelectLcContainerList')
                        .css({'opacity':0,'height':'auto','display':'block'})
                        .animate(
                            {
                                'opacity':1
                            },
                            {
                                'queue' : false,
                                'duration' : 500,
                                'complete' : function()
                                {
                                    p.removeClass('close').addClass('open');
                                    $('.FullSelectLcContainerList').css({'filter':'none'});

                                }
                            }
                        )
                }
                else
                {
                    if (opt.search)
                    {
                        p.find('.searchLc').val(opt.searchText).css({'z-index':'-1'});
                    }
                    //$(t).val('\u25BC');
                    p.find('.inputNon').blur();
                    p
                        .find('.FullSelectLcContainerList')
                        .animate(
                            {
                                'opacity':0
                            },
                            {
                                'queue' : false,
                                'duration' : 200,
                                'complete' : function()
                                {
                                    $(this).removeAttr('style');
                                    p
                                        .addClass('close')
                                        .removeClass('open')
                                        .removeAttr('style');
                                }
                            }
                        )
                }
            },
            onClickLi : function (t, that, table)
            {
                var id = $(that).attr('rel');
                if (opt.onClickLi)
                {
                    opt.onClickLi(t, that, table);
                    return false;
                }
                if (!opt.multiselect)
                {
                    $(t).parent().find('.selected').each(function()
                    {
                        $(this)
                            .removeClass('selected')
                            .find('input[type="checkbox"]')
                            .removeAttr('checked');
                    });
                }

                if ($(t).hasClass('selected'))
                {
                    $(t)
                        .removeClass('selected')
                        .find('input[type="checkbox"]')
                        .removeAttr('checked');
                }
                else
                {
                    $(t)
                        .addClass('selected')
                        .find('input[type="checkbox"]')
                        .attr('checked','checked');
                }
                var s = [];
                $(t).parent().find('input:checked').each(function()
                {
                    s[s.length] = { value : $(this).val(), name:$(this).parent().find('span').text() };
                });
                table.selected = s;
                that.parent().find('.inputLc ,.searchLc').val(fsLc[id].setInputValue(that, table));

                if (!opt.multiselect && !opt.keyEv)
                {
                    that.parent().find('.buttonLc').trigger('click');
                }

            },
            onCheckAll : function (t, that, table)
            {
            	var elCount = $(t).parent().find('li').not('.checkAll').length;
            	var elSelCount = $(t).parent().find('li.selected').not('.checkAll').length;
            	var checkAll = $(t).parent().find('.checkAll');
            	var checkbox = checkAll.find('input[type="checkbox"]');

            	checkbox.removeAttr('checked');
            	checkAll.removeClass('all');
            	if (elCount == elSelCount)
            		{
            			checkbox.attr('checked','checked');
                    	checkAll.addClass('all');
            		}
            },
            onHoverLi : function (t, that, table)
            {
            	var id = $(that).attr('rel');
                if (opt.onHoverLi)
                {
                    opt.onHoverLi(t, that, table);
                    return false;
                }

            },
            onKeyDown : function (e, t, that)
            {
            	var p = $(that).parent();
            	var input = p.find('.inputLc');
            	var butt = p.find('.buttonLc');
            	var list = p.find('.list');
            	var llall = list.find('li');
            	var ll = list.find('li:not(.none)');
            	var l = ll.last();
            	var f = ll.first();
            	var s = list.find('li.selected:not(.none)');
            	var h = list.find('li.hover:not(.none)');
            	var sp = s.prev('li');
            	var sn = s.next('li');
            	var hp = h.prev('li');
            	var hn = h.next('li');
            	var next = p.find('.next');
            	var prev = p.find('.prev');

            	if (p.hasClass('close'))
            	{
            		return false;
            	}
            	switch(e.keyCode)
                 {
					case 38: // up
						if (!opt.multiselect)
						{
			            	opt.keyEv = true;
			            	llall.removeClass('selected');
			            	s
								.removeClass('selected')
								.find('input[type="checkbox"]')
								.removeAttr('checked');
			            	if (s.get(0)==undefined)
			            	{
			            		s=f;
			            	}
							if (s.get(0) == f.get(0))
							{
								l
									.addClass('selected')
									.find('input[type="checkbox"]')
									.attr('checked','checked');
								if (!opt.onClickLi)
									{
										l.trigger('click');
									}
							}
							else
							{
								sp
									.addClass('selected')
									.find('input[type="checkbox"]')
									.attr('checked','checked');
								if (!opt.onClickLi)
								{
									sp.trigger('click');
								}
							}
			            	opt.keyEv = false;
						}
						else
						{
							h.removeClass('hover');
							if (h.get(0)==undefined)
							{
								h = l.addClass('hover');
							}
							else if (h.get(0) == f.get(0))
							{
								l.addClass('hover');
							}
							else
							{
								hp.addClass('hover');
							}
						}
						/* Scroll Move */
						var actS = s.parent().find('.selected');
						var sT = actS.position().top+actS.outerHeight()+list.scrollTop()-list.outerHeight();
						if (list.outerHeight()>0)
							{
								sT = sT+actS.outerHeight()*5;
							}
						else
						{
								sT = o;
						}
						list.animate(
							{
								scrollTop : sT
							},
							{
								queue : false,
								duration : 50
							});
						/* */
					break;

					case 40: // down
						if (!opt.multiselect)
						{
			            	opt.keyEv = true;
			            	llall.removeClass('selected');
							s
								.removeClass('selected')
								.find('input[type="checkbox"]')
								.removeAttr('checked');
			            	if (s.get(0)==undefined)
			            	{
			            		s=l;
			            	}
							if (s.get(0) == l.get(0))
							{
								f
									.addClass('selected')
									.find('input[type="checkbox"]')
									.attr('checked','checked');
								if (!opt.onClickLi)
								{
									f.trigger('click');
								}
							}
							else
							{
								sn
									.addClass('selected')
									.find('input[type="checkbox"]')
									.attr('checked','checked');
								if (!opt.onClickLi)
								{
									sn.trigger('click');
								}
							}
			            	opt.keyEv = false;
						}
						else
						{
							h.removeClass('hover');
							if (h.get(0)==undefined)
							{
								h = f.addClass('hover');
							}
							else if (h.get(0) == l.get(0))
							{
								f.addClass('hover');
							}
							else
							{
								hn.addClass('hover');
							}
						}
						/* Scroll Move */
						var actS = s.parent().find('.selected');
						var sT = actS.position().top+actS.outerHeight()+list.scrollTop()-list.outerHeight();
						if (list.outerHeight()>0)
							{
								sT = sT+actS.outerHeight()*5;
							}
						else
						{
								sT = o;
						}
						list.animate(
							{
								scrollTop : sT
							},
							{
								queue : false,
								duration : 100
							});
						/* */
					break;

					case 37: // left
						if (opt.paging)
						{
							prev.trigger('click');
						}
					break;

					case 39: // right
						if (opt.paging)
						{
							next.trigger('click');
						}
					break;

					case 13: // return
						if (!opt.multiselect)
						{
							s.trigger('click');
						}
						else
						{
							input.trigger('click');
						}
					break;

					case 32: // space
						if (opt.multiselect)
						{
							h.trigger('click');
						}
						if (opt.onClickLi)
						{
							s.trigger('click');
						}
					break;

					case 27: // escape
						butt.trigger('click');
					break;

					case 9: // tab
						butt.trigger('click');
					break;

					default:
						var sChar=String.fromCharCode(e.keyCode);
						var first = ll.find('span[rel^="'+sChar.toLowerCase()+'"]').eq(0);
						if (first.get(0)!=undefined)
							{
			            	opt.keyEv = true;
			            	llall.removeClass('selected');
			            	s
								.removeClass('selected')
								.find('input[type="checkbox"]')
								.removeAttr('checked');

			            		first
									.addClass('selected')
									.find('input[type="checkbox"]')
									.attr('checked','checked');
			            			if (!opt.onClickLi)
									{
			            				first.trigger('click');
									}

									var actS = s.parent().find('.selected');
									var sT = actS.position().top+actS.outerHeight()+list.scrollTop()-list.outerHeight();
									if (list.outerHeight()>0)
										{
											sT = sT+actS.outerHeight()*5;
										}
									else
									{
											sT = o;
									}
									list.animate(
										{
											scrollTop : sT
										},
										{
											queue : false,
											duration : 50
										});

									opt.keyEv = false;
							}
							//opt.keyEv = true;
							//first.parents('li').trigger('click');
							//console.log( sChar )
							//opt.keyEv = false;



						/* Scroll Move */

						/* */


					break;

				}
            	e.preventDefault();
            	e.stopPropagation();
            },
            onRemoveSearchResults : function (that)
            {
                var id = $(that).attr('rel');
                var p = $(that).parent();
                if (!opt.ajax)
                {
                    var lilist = p.find('.list li');
                    lilist.removeClass('none');
                    if (opt.paging)
                    {
                        lilist.each(function(i)
                        {
                            if (opt.paging <= i )
                            {
                                $(this).addClass('none');
                            }
                        });
                    }


                }
                else
                {
                    $.ajax({
                      type: "GET",
                      url: opt.ajax,
                      success: function(table)
                      {
                        var j = eval("(" + table + ")");
                        fsLc[id].table = j.table;
                        var nUl = fsLc[id].createList(fsLc[id].that, fsLc[id].table);
                        var oUl = $(fsLc[id].that).parent().find('ul.list');
                        oUl.after(nUl);
                        oUl.remove();
                      }
                    });
                }
                p.find('.paging').removeAttr('style');
                p.find('.searchlist').remove();
            }
        }

        this.each(function()
        {
            fsLc[setId].init(this,opt);
        });



    }
})(jQuery);


