/* CUSTOMIZED */
/*! http://tinynav.viljamis.com v1.03 by @viljamis */
(function ($, window, i) {
    $.fn.tinyNav = function (options) {

        // Default settings
        var settings = $.extend({
            'active':'selected', // String: Set the "active" class
            'header':true // Boolean: Show header instead of the active item
        }, options);

        return this.each(function () {
            // Used for namespacing
            i++;
            var $nav = $(this);
            var namespace = 'tinynav'
            var namespace_i = namespace + i;
            var l_namespace_i = '.l_' + namespace_i;
            var $select = $('<select/>').addClass(namespace + ' ' + namespace_i);

            if ($nav.is('ul,ol')) {

                if (settings.header) {
                    $select.append($('<option/>').text('Navigate ...'));
                }

                // Build options
                var options = '';
                $nav.addClass('l_' + namespace_i).find('a').each(function () {
                    var indent = getItemIndent($(this));
                    options += '<option value="' + $(this).attr('href') + '">' + indent + $(this).text() + '</option>';
                });

                // Append options into a select
                $select.append(options);

                // Select the active item
                if (!settings.header) {
                    $select.find(':eq(' + $(l_namespace_i + ' li')
                        .index($(l_namespace_i + ' li.' + settings.active)) + ')')
                        .attr('selected', true);
                }

                // Change window location
                $select.change(function () {
                    window.location.href = $(this).val();
                });

                // Inject select
                $(l_namespace_i).after($select);

            }

        });

        function getItemIndent(item) {
            var i=0;
            var indent = '';
            while (item) {
                if(i==50){
                    break;
                }
                var tagName = item.prop("nodeName").toUpperCase();
                if (tagName == 'NAV') {
                    break;
                } else if ((tagName == 'UL') || (tagName == 'OL')) {
                    indent += ' - ';
                }
                item = item.parent();
                i++;
            }
            return indent;
        }

    };
})(jQuery, this, 0);