/**
 * Custom selectbox and filter options
 */
(function($){

    // load up the chosen select box with selected values from 'memory'
    // we 'use' the window.name property since this value does not refresh on page re-load.
    if ( sessvars.chosen ) {
        $('.custom-select').val(sessvars.chosen);
    }

    // init select box, and set the 'onchange' event handler
    $('.custom-select').chosen().change(function() {

            //test
           //window.name = JSON.stringify({ select: $(this).val(), sort: sortData });
           sessvars.chosen = $(this).val();

            // get parent container element
            var $filter_container = $(this).parent();

            // guard: check for values
            if ( ! $(this).val()) {
                $('.wrapper', $filter_container).show();
                return false;
            }

            // hide all options
            $('.wrapper', $filter_container).hide();

            // loop trough select values
            jQuery.each($(this).val(), function() {
                $('.' + this, $filter_container).show();
            });
        }
    );

    // call the onchange event on select box, to force refreshing of data
    // to refresh to box if selected items are found in memory
    $('.custom-select').trigger('change');


    // init sorting by alphabet
    $('a.sort-by-alphabet').click(function(event) {

            // sort nodes
            findExhibitorsList($(this)).tsort();

            // set the class names
            setClasses($(this));

            // prevent click action
            event.preventDefault();

            sessvars.sort = 'alphabet';
        }
    );

    // init sorting by alphabet
    $('a.sort-by-stand').click(function(event) {

            // sort nodes
            findExhibitorsList($(this)).tsort('span.stand');

            // set the class names 
            setClasses($(this));

            // prevent click action
            event.preventDefault();

            sessvars.sort = 'stand';
        }
    );

    // check if a session is stored, if so trigger the event
    if ( sessvars.sort ) {

        switch ( sessvars.sort ) {
            case 'alphabet':
                $('a.sort-by-alphabet').trigger('click');
            break;
            case 'stand':
                $('a.sort-by-stand').trigger('click');
            break;
        }
    }

    /**
     * Find exhibitors list
     * @param JQuery HTML Object
     */
     function findExhibitorsList($element) {

        // get the parents
        var $parents = $element.parents('.exhibitors');

        return $parents.find('ul.exhibitors-list li');
     }

    /**
     * Remove and add classes
     * @param JQuery HTML Object
     */
     function setClasses($element) {

        // remove all selected states
        $element.parents('.exhibitors').find('ul.options li').removeClass('sel');

        // set selected class
        $element.parent().addClass('sel');
     }

})(jQuery)
