/*
 *Kort dokumentation
 */
; (function($) {
    var listItemHeight = 0,
    selectListHeight = 0,
    listitemsCount = -1,
    currentSelection = -1,
    lastChar = "",
    numPressed = 1,
    firstChar = [],
    /*
	* Private methods 
	*/

	_removeList = function(e) {
		$(document).unbind('keydown');
		$('body').unbind('click');
		$('.selectorList').remove()
	}
    _keydownIdentifier = function(e, scope) {
		if(!(e.keyCode == 9))
		{
			e.preventDefault();
			switch (e.keyCode) 
			{
				case 38:
				// User pressed "up" arrow
					_navigate('up');
					break;
				case 40:
				 // User pressed "down" arrow
					_navigate('down');
					break;
				case 13:
				case 32:
				// User pressed "enter or space" and select an item
					_setSelectedItem(scope);
					break;
				default:
					_findCharAt(e);
					//Naviget in list whit characters
			}
		}else
		{	
			//user tabs to navigate
			_removeList();
		}
    }


    _navigate = function(direction) {
        if (direction == 'up' && currentSelection > 0) {
            if (currentSelection) {
                currentSelection--;
            }
        } else if (direction == 'down') {
            if (currentSelection != listitemsCount) {
                currentSelection++;
            }
        }
        _setCurrentSelection(currentSelection);
    }

    _setCurrentSelection = function(currentSelection) {
        $(".item").removeClass("hover");
        $('#' + currentSelection).addClass("hover");
        var pos = $(".selectorList li.hover").position();
        var scroll = $('.selectorList').scrollTop();
        if (pos.top >= selectListHeight - listItemHeight) {
            $('.selectorList').scrollTop((pos.top + listItemHeight + scroll) - selectListHeight);
        } else if (pos.top < -1) {
            $('.selectorList').scrollTop(scroll + pos.top);
        }
    }

    _findCharAt = function(e)
    {
        if (firstChar.exists(String.fromCharCode(e.keyCode).toUpperCase()))
        {
            switch (e.keyCode)
            {
            case 221:
                var charPressed = "Å";
                break;
            case 222:
                var charPressed = "Ä";
                break;
            case 192:
                var charPressed = "Ä";
                break;
            default:
                var charPressed = String.fromCharCode(e.keyCode).toUpperCase();
            }
            if (charPressed == lastChar)
            {
                numPressed++;
            }
            else
            {
                lastChar = charPressed;
                numPressed = 1;
            }
            var lastIndex = -1;
            for (var i = 0; i < numPressed; i++)
            {
                var index = -1;
                for (var j = lastIndex + 1; j < firstChar.length; j++)
                {
                    if (firstChar[j] == lastChar)
                    {
                        index = j;
                        break;
                    }
                }
                if (index == -1)
                {
                    if (i == 0)
                    break;
                    i = -1;
                    lastIndex = -1;
                    numPressed = 1;
                }
                else
                {
                    currentSelection = index;
                    _setCurrentSelection(index);
                    lastIndex = index;
                }
            }
        }
    }

    _createListitem = function(item, counter, selectedIndex) {
        firstChar[listitemsCount] = item.text().replace(/^\s*|\s*$/g,'').charAt(0).toUpperCase();

        if (counter == selectedIndex) {
            return '<li id="' + listitemsCount + '" selectVal="' + item.val() + '" class="item selected">' + item.text() + '</li>';
        } else {
            return '<li id="' + listitemsCount + '" selectVal="' + item.val() + '" class="item">' + item.text() + '</li>';
        }

    }

    Array.prototype.exists = function(search) {
        for (var i = 0; i < this.length; i++)
        if (this[i] == search) return true;

        return false;
    }

    _getScrollTop = function() {
        if (typeof pageYOffset != 'undefined') {
            //most browsers
            return pageYOffset;
        }
        else {
            var B = document.body;
            //IE 'quirks'
            var D = document.documentElement;
            //IE with doctype
            D = (D.clientHeight) ? D: B;
            return D.scrollTop;
        }
    }
	
	//Set the current selection in select and removes the list
	_setSelectedItem = function(scope, obj){
		scope.find('.selectorText').html($('#' + currentSelection).html()).parent().find('select').val($('#' + currentSelection).attr('selectVal')).change();
		_removeList();
	}


    _createSelectList = function(scope, options) {
        /*Get all listItems from select list*/
		var listSize = options.listSize;
        var list = "";
        var listItems = "";
        listitemsCount = -1;
        currentSelection = scope.find('select').attr('selectedIndex');
        scope.find('select').children().each(
        function(i) {
            if ($(this).is('optgroup')) {
                var opt = $(this);
                var listItemsChildren = "";
                $(this).children().each(
                function(j) {
                    listitemsCount++;
                    listItemsChildren += _createListitem($(this), listitemsCount, currentSelection);

                });
                listItems += '<li class="optgroup">' + $(this).attr('label') + '<ul>' + listItemsChildren + '</ul></li>';
            } else {
                listitemsCount++;
                listItems += _createListitem($(this), listitemsCount, currentSelection);
            }
        });
        list = '<ul class="selectorList">' + listItems + '</ul>';
        var $selectList = $(list);

        // see  if selectlist is open
        if (! ($('.selectorList').length > 0)) {
            $('body').append($selectList);
            $selectList.css({
                'left': -999999,
                'display': 'block'
            });
			// Sets height of list
            listItemHeight = $selectList.find('.item').first().outerHeight();
            if ((listitemsCount + 1) > listSize) {
                selectListHeight = listItemHeight * listSize;
            }
            else {
                selectListHeight = listItemHeight * (listitemsCount + 1);
            }
			var width = scope.outerWidth();
			 var offset = scope.offset();
            $selectList.removeAttr('style') .css({
                'width': width,
                'maxHeight': selectListHeight,
                'left': offset.left
            });
			var selectListOuterHeight = $selectList.outerHeight();
            var windowHeight = $(window).height();
            var scrollTop = _getScrollTop();
            var scopeHeight = scope.outerHeight();
			
			// Set position of list
            var listPosition = 0;
            
            // see  if the list fitts in the bottom or top of the screen
            var z = windowHeight + scrollTop - (offset.top + scopeHeight);
			var y = (windowHeight - offset.top)  + scrollTop;
            if ((z < selectListOuterHeight) && (selectListOuterHeight < y)) {
                listPosition = offset.top - (selectListOuterHeight / 2);
            } else if (z < selectListOuterHeight) {
                listPosition = offset.top - selectListOuterHeight;
            }else {
				listPosition = offset.top + scopeHeight;
			}
			
			// Navigation in list
            $(document).bind('keydown',
            function(e) {
                _keydownIdentifier(e, scope)
            });
            
            $selectList
            .css({
                'top': listPosition
            })
            .slideDown(function() {
                _setCurrentSelection(currentSelection);
            })
            .find('.item').bind('click',
            function(e) {
				e.stopPropagation();
				currentSelection = $(this).attr('id')
				_setSelectedItem(scope);
            });

			$('body').bind('click', function(e) {  _removeList(); return false  } );

        }

    }

    $.fn.selectList = function(options)
    {
		var defaults = { 
		    listSize:     10
		};
		
		var options = $.extend({}, defaults, options); 
        return this.each(function()
        {	
			obj = $(this);
			select = obj.find('select');
			if (!('ontouchstart' in document.documentElement)) 
			{ 
				obj.hover(function() {
					$(this).find('select').css('display', 'none');
				},
				function() {
					$(this).find('select').css('display', 'block')
				});
				obj.click(function(e) {
					_removeList();
					e.stopPropagation();
					_createSelectList($(this), options);
				});
				select.focus(function() {
					_removeList();
					_createSelectList($(this).parent(), options);
				});
			}else
			{
				select.focus(function() { $(this).parent().addClass('focus'); });
				select.blur(function() { $(this).parent().removeClass('focus'); });
				select.change(function() {$(this).parent().find('.selectorText').html(this.options[this.selectedIndex].text);});
			
			}
						
           
        });
    }
})(jQuery);
