﻿/*
Stylish Select 0.4.1 - $ plugin to replace a select drop down box with a stylable unordered list
http://scottdarby.com/

Requires: jQuery 1.3 or newer

Contributions from Justin Beasley: http://www.harvest.org/ & Anatoly Ressin: http://www.artazor.lv/

Dual licensed under the MIT and GPL licenses.

*/
(function(jQuery) {

    var jQuerycontainerDivLast;

    //add class of js to html tag
    jQuery('html').addClass('stylish-select');

    //create cross-browser indexOf
//    Array.prototype.indexOf = function(obj, start) {
//        for (var i = (start || 0); i < this.length; i++) {
//            if (this[i] == obj) {
//                return i;
//            }
//        }
//    }

    //utility methods
    jQuery.fn.extend({
       getSetSSValue: function(value) {
                        if (value) {
                            //set value and trigger change event
                            jQuery(this).val(value).change();
                            return this;
                        } else {
                            return jQuery(this).find(':selected').val();
                        }
            return this;
        },
        //added by Justin Beasley
        resetSS: function() {
            var oldOpts = jQuery(this).data('ssOpts');
            jQuerythis = jQuery(this);
            jQuerythis.next().remove();
            //unbind all events and redraw
            jQuerythis.unbind().sSelect(oldOpts);
        }
    });

    jQuery.fn.sSelect = function(options) {

        return this.each(function() {
            var defaults = {
                defaultText: 'Please select',
                animationSpeed: 0, //set speed of dropdown
                ddMaxHeight: '' //set css max-height value of dropdown
            };
            var id = '#ddl_' + jQuery(this).attr('id');
            if (jQuery(id).length != 0) {
                return;
            }


            //initial variables
            var opts = jQuery.extend(defaults, options),
            jQueryinput = jQuery(this),
			jQueryid_input = jQueryinput.attr('id'),
            jQuerycontainerDivText = jQuery('<div class="selectedTxt"></div>'),
            jQuerycontainerDiv = jQuery('<div class="" tabindex="0" id="ddl_' + jQueryid_input + '"></div>'),
            jQuerynewUl = jQuery('<ul class="newList"></ul>'),
			jQuerybottomRow = jQuery('<li class="newListBottom"></li>'),
            itemIndex = -1,
            currentIndex = -1,
            keys = [],
            prevKey = false,
            prevented = false,
            jQuerynewLi;


            //added by Justin Beasley
            jQuery(this).data('ssOpts', options);

            //build new list
            jQuerycontainerDiv.insertAfter(jQueryinput);
            jQuerycontainerDivText.prependTo(jQuerycontainerDiv);
            jQuerynewUl.appendTo(jQuerycontainerDiv);
            jQueryinput.hide();

            //test for optgroup
            if (jQueryinput.children('optgroup').length == 0) {
                jQueryinput.children().each(function(i) {
                    var option = jQuery(this).text();
                    var key = jQuery(this).val();

                    //add first letter of each word to array
                    keys.push(option.charAt(0).toLowerCase());
                    if (jQuery(this).attr('selected') == true) {
                        opts.defaultText = option;
                        currentIndex = i;
                    }
                    jQuerynewUl.append(jQuery('<li><a href="JavaScript:void(0);">' + option + '</a></li>').data('key', key));

                });
                //cache list items object
                jQuerynewLi = jQuerynewUl.children().children();

            } else { //optgroup
                jQueryinput.children('optgroup').each(function() {

                    var optionTitle = jQuery(this).attr('label'),
                    jQueryoptGroup = jQuery('<li class="newListOptionTitle">' + optionTitle + '</li>');

                    jQueryoptGroup.appendTo(jQuerynewUl);

                    var jQueryoptGroupList = jQuery('<ul></ul>');

                    jQueryoptGroupList.appendTo(jQueryoptGroup);

                    jQuery(this).children().each(function() {
                        ++itemIndex;
                        var option = jQuery(this).text();
                        var key = jQuery(this).val();
                        //add first letter of each word to array
                        keys.push(option.charAt(0).toLowerCase());
                        if (jQuery(this).attr('selected') == true) {
                            opts.defaultText = option;
                            currentIndex = itemIndex;
                        }
                        jQueryoptGroupList.append(jQuery('<li><a href="JavaScript:void(0);">' + option + '</a></li>').data('key', key));
                    })
                });
                //cache list items object
                jQuerynewLi = jQuerynewUl.find('ul li a');
            }

            jQuerybottomRow.appendTo(jQuerynewUl);

            //get heights of new elements for use later
            var newUlHeight = jQuerynewUl.height(),
            containerHeight = jQuerycontainerDiv.height(),
            newLiLength = jQuerynewLi.length;

            //check if a value is selected
            if (currentIndex != -1) {
                navigateList(currentIndex, true);
            } else {
                //set placeholder text
                jQuerycontainerDivText.text(opts.defaultText);
            }

            //decide if to place the new list above or below the drop-down
            function newUlPos() {
                var containerPosY = jQuerycontainerDiv.offset().top,
                docHeight = jQuery(window).height(),
                scrollTop = jQuery(window).scrollTop();

                //if height of list is greater then max height, set list height to max height value
                if (newUlHeight > parseInt(opts.ddMaxHeight)) {
                    newUlHeight = parseInt(opts.ddMaxHeight);
                }

                containerPosY = containerPosY - scrollTop;
                if (containerPosY + newUlHeight >= docHeight) {
                    jQuerynewUl.css({
                        //top: '-'+newUlHeight+'px',
                        height: newUlHeight
                    });
                    jQueryinput.onTop = true;
                } else {
                    jQuerynewUl.css({
                        //top: containerHeight+'px',
                        height: newUlHeight
                    });
                    jQueryinput.onTop = false;
                }
            }

            /*
            //run function on page load
            newUlPos();
			
            //run function on browser window resize
            jQuery(window).resize(function(){
            newUlPos();
            });
			
            jQuery(window).scroll(function(){
            newUlPos();
            });
            */

            //positioning
            function positionFix() {
                jQuerycontainerDiv.css('position', 'relative');
            }

            function positionHideFix() {
                jQuerycontainerDiv.css('position', 'static');
            }

            jQuerycontainerDivText.click(function(event) {

                var oClass = jQuerycontainerDivText.parent().attr('class');
                if (oClass.indexOf('selectedTextDown') > -1) {
                    jQuerycontainerDivText.parent().attr('class', '');
                }
                else {
                    jQuerycontainerDivText.parent().attr('class', 'selectedTextDown');
                }

                event.stopPropagation();

                //hide all menus apart from this one
                jQuery('.newList').not(jQuery(this).next()).hide().parent().removeClass('newListSelFocus');
                jQuery('.newList').not(jQuery(this).next()).hide().parent().removeClass('selectedTextDown');

                //show/hide this menu
                jQuerynewUl.toggle();
                positionFix();
                //scroll list to selected item
                jQuerynewLi.eq(currentIndex).focus();


            });

            jQuerynewLi.click(function(e) {

                var jQueryclickedLi = jQuery(e.target);

                //update counter
                currentIndex = jQuerynewLi.index(jQueryclickedLi);

                //remove all hilites, then add hilite to selected item
                prevented = true;
                navigateList(currentIndex);
                jQuerycontainerDiv.removeClass('selectedTextDown');
                jQuerynewUl.hide();
                jQuerycontainerDiv.css('position', 'static'); //ie

            });

            jQuerynewLi.hover(
                function(e) {
                    var jQueryhoveredLi = jQuery(e.target);
                    jQueryhoveredLi.addClass('newListHover');
                },
                function(e) {
                    var jQueryhoveredLi = jQuery(e.target);
                    jQueryhoveredLi.removeClass('newListHover');
                }
                );

            function navigateList(currentIndex, init) {
                jQuerynewLi.removeClass('hiLite')
                .eq(currentIndex)
                .addClass('hiLite');

                if (jQuerynewUl.is(':visible')) {
                    jQuerynewLi.eq(currentIndex).focus();
                }

                var text = jQuerynewLi.eq(currentIndex).text();
                var val = jQuerynewLi.eq(currentIndex).parent().data('key');

                //page load
                if (init == true) {
                    jQueryinput.val(val);
                    jQuerycontainerDivText.text(text);
                    return false;
                }

                jQueryinput.val(val)
                jQueryinput.change();
                jQuerycontainerDivText.text(text);
            };

            jQueryinput.change(function(event) {
                jQuerytargetInput = jQuery(event.target);
                //stop change function from firing
                if (prevented == true) {
                    prevented = false;
                    return false;
                }
                jQuerycurrentOpt = jQuerytargetInput.find(':selected');

                //currentIndex = jQuerytargetInput.find('option').index(jQuerycurrentOpt);
                currentIndex = jQuerytargetInput.find('option').index(jQuerycurrentOpt);


                navigateList(currentIndex, true);
            }
            );

            //handle up and down keys
            function keyPress(element) {
                //when keys are pressed
                element.onkeydown = function(e) {
                    var keycode;
                    if (e == null) { //ie
                        keycode = event.keyCode;
                    } else { //everything else
                        keycode = e.which;
                    }

                    //prevent change function from firing
                    prevented = true;

                    switch (keycode) {
                        case 40: //down
                        case 39: //right
                            incrementList();
                            return false;
                            break;
                        case 38: //up
                        case 37: //left
                            decrementList();
                            return false;
                            break;
                        case 33: //page up
                        case 36: //home
                            gotoFirst();
                            return false;
                            break;
                        case 34: //page down
                        case 35: //end
                            gotoLast();
                            return false;
                            break;
                        case 13:
                        case 27:
                            jQuerynewUl.hide();
                            positionHideFix();
                            return false;
                            break;
                    }

                    //check for keyboard shortcuts
                    keyPressed = String.fromCharCode(keycode).toLowerCase();

                    var currentKeyIndex = keys.indexOf(keyPressed);

                    if (typeof currentKeyIndex != 'undefined') { //if key code found in array
                        ++currentIndex;
                        currentIndex = keys.indexOf(keyPressed, currentIndex); //search array from current index
                        if (currentIndex == -1 || currentIndex == null || prevKey != keyPressed) currentIndex = keys.indexOf(keyPressed); //if no entry was found or new key pressed search from start of array


                        navigateList(currentIndex);
                        //store last key pressed
                        prevKey = keyPressed;
                        return false;
                    }
                }
            }

            function incrementList() {
                if (currentIndex < (newLiLength - 1)) {
                    ++currentIndex;
                    navigateList(currentIndex);
                }
            }

            function decrementList() {
                if (currentIndex > 0) {
                    --currentIndex;
                    navigateList(currentIndex);
                }
            }

            function gotoFirst() {
                currentIndex = 0;
                navigateList(currentIndex);
            }

            function gotoLast() {
                currentIndex = newLiLength - 1;
                navigateList(currentIndex);
            }

            jQuerycontainerDiv.click(function() {
                keyPress(this);
            });

            jQuerycontainerDiv.focus(function() {
                jQuery(this).addClass('newListSelFocus');
                keyPress(this);
                if (jQuerycontainerDivLast != null && jQuerycontainerDiv != jQuerycontainerDivLast) {
                    jQuerycontainerDivLast.css("position", "static");
                }

                if (jQuerycontainerDiv.find("ul.newList").css("display") == "none") {
                    positionHideFix();
                }
                else {
                    jQuerycontainerDivLast = jQuerycontainerDiv;
                }
            });

            jQuerycontainerDiv.blur(function() {
                jQuery(this).removeClass('newListSelFocus');
                positionHideFix();
            });

            //hide list on blur
            jQuery('body').click(function() {
                jQuerycontainerDiv.removeClass('newListSelFocus');
                jQuerycontainerDiv.removeClass('selectedTextDown');
                jQuerynewUl.hide();
                positionHideFix();
            });

            //add classes on hover
            jQuerycontainerDivText.hover(function(e) {
                var jQueryhoveredTxt = jQuery(e.target);
                jQueryhoveredTxt.parent().addClass('newListSelHover');
            },
            function(e) {
                var jQueryhoveredTxt = jQuery(e.target);
                jQueryhoveredTxt.parent().removeClass('newListSelHover');
            }
            );

            //reset left property and hide
            jQuerynewUl.css('left', '0').hide();

        });

    };

})(jQuery);
