﻿// This is just here to tell JS lint that we need to use a global variable
/*global TVI, loadFirebugConsole, document, alert, console, window $ */

/*
    TVI Framework
    Version 1.0
    Copywrite 2009 TVI Design
    Last Updated: 11/01/2010
    
    Contents:
        TVI.Components.CustomDDL
*/


TVI.Components.CustomDDL = function() {

    /* Private */

    /* Properties */

    var cmp = {};
    var componentIndex = -1;





    /* Methods */

    var init = function() {
    
        //add to components array
        componentIndex = TVI.Components.add({
        
            type: 'customDDL',
            selector: '.TVI-customDDL',
            setup: setup,
            create: create,
            layout: layout
        
        });
        

        // Don't do anything in IE6
        if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {

            $('.TVI-customDDL SELECT').show();

            return;

        };

        // Close panels when anything on the page is clicked
        $(document).click(function(e) {

            var clicked = $(e.target);
            var controlClicked = clicked.parents('.TVI-customDDL-control');

            // Has the user clicked on a custom DDL control?
            if (controlClicked.length > 0) {
                return;
            }

            // Otherwise, close all custom DDLs
            var controls = $('.TVI-customDDL-control');
            controls.removeClass('open');
            controls.find('.TVI-customDDL-panel').hide();
        });


        // Open and close when the button is clicked
        TVI.event('.TVI-customDDL-button', 'click', function() {

            var buttonControl = $(this).parents('.TVI-customDDL-control');
            var panelControl = buttonControl.find('.TVI-customDDL-panel');
            var alreadyOpen = false;

            // Check to see if the panel is already open
            if (buttonControl.hasClass('open')) {
                alreadyOpen = true;
            }

            // Close all panels
            buttonControl.removeClass('open');
            $('.TVI-customDDL-panel').hide();

            // If the panel wasn't open then open it.
            if (!alreadyOpen) {
                panelControl.show();
                buttonControl.addClass('open');
            }


        });

        // Handle an option being clicked
        TVI.event('.TVI-customDDL-option', 'click', function() {

            var option = $(this);
            var optionText = option.find('A').text();
            var optionValue = option.find('.value').text();
            var control = $(this).parents('.TVI-customDDL');
            var SelectControl = control.find('SELECT');
            var customControl = control.find('.TVI-customDDL-control');

            // Set the text in the custom DDL
            customControl.find('.TVI-customDDL-button-text').text(optionText);

            var currentOption = SelectControl.val();

            if (optionValue !== currentOption) {

                // Choose the corresponding option in the original SELECT element
                SelectControl.val(optionValue);

                //fire changed event on select list
                SelectControl.trigger('change');

            }

            // Close all panels
            customControl.removeClass('open');
            $('.TVI-customDDL-panel').hide();

        });


    }
    
    
    
    
    
    var create = function(element) {
        
        //ignore if already created
        if (element.hasClass('TVI-created')){ return; }

        // Don't do anything in IE6
        if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
            return;
        };

        // Finds all Custom DDLs within the supplied root element and create them

        var selectElement = element.find('SELECT');
        var defaultOption = selectElement.find('OPTION:selected');
        var defaultText = defaultOption.text();
        var defaultValue = defaultOption.attr('value');
        var totalWidth = selectElement.parent().width();
        var middleWidth = totalWidth;
        var middleClass = ''
        var widthUsed = 0;
        var style = 'defaultStyle';
        var leftHTML = '';
        var middleHTML = '';
        var rightHTML = '';
        var customDDLHTML = '';


        // Get a list of the classes used on the main element
        var classes = element.attr('class').split(' ');
        var classesLength = classes.length;

        // Check to see if we are not using the default button style
        for (i = 0; i < classesLength; i++) {
            if (classes[i].substring(0, 17) == 'TVI-customDDL-style-') {
                style = classes[i].substring(20);
            }
        }

        // Create a shortcut to the button style
        style = TVI.Components.CustomDDL.styles[style];

        //Work out the width of the middle section
        middleWidth = totalWidth - (style.buttonLeftEndWidth + style.buttonRightEndWidth + style.buttonLeftPadding + style.buttonRightPadding);
        var controlHTML = ''
            + '<div class="TVI-customDDL-control TVI-onTop clearfix">'
            + '<a class="TVI-customDDL-button" href="#">'
            + '<span class="TVI-customDDL-button-left sp"></span>'
            + '<span class="TVI-customDDL-button-middle sp" style="width:' + middleWidth + 'px;">'
            + '<span class="TVI-customDDL-button-text">' + defaultText + '</span>'
            + '</span>'
            + '<span class="TVI-customDDL-button-right sp"></span>'
            + '</a>'
            + '<div class="TVI-customDDL-panel" style="min-width:' + (totalWidth - (style.panelBorderWidth * 2)) + 'px;">'
            + '<div class="TVI-customDDL-options">';

        // Loop through all the options and recreate each one
        selectElement.find('option').each(function() {
            var newValue = $(this).attr('value');
            controlHTML += '<div class="TVI-customDDL-option"><span class="value">' + newValue + '</span><a href="#">' + $(this).text() + '</a></div>';
        });

        controlHTML += '</div>'
            + '</div>'
            + '</div>';

        selectElement.after(controlHTML);


        // Add hover and active classes to button
        var buttonElement = element.find('.TVI-customDDL-button');

        buttonElement.bind("mouseenter", function() {
            $(this).addClass(style.hoverClass);
        });
        buttonElement.bind("mouseleave", function() {
            $(this).removeClass(style.hoverClass);
        });
        
        //handle select changed event to update this control
        selectElement.change(function(){
        
            update($(this));
        
        });

        // Tell the system it doesn't need to be created again.
        element.addClass('TVI-created');

    };
    
    
    
    
    
    var layout = function(element){
    
        // Don't do anything in IE6
        if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
            return;
        };

        // Finds all Custom DDLs within the supplied root element and create them

        var selectElement = element.find('SELECT');
        var totalWidth = selectElement.parent().width();
        var middleWidth = totalWidth;
        var panelWidth = 0;
        var widthUsed = 0;
        var style = 'defaultStyle';


        // Get a list of the classes used on the main element
        var classes = element.attr('class').split(' ');
        var classesLength = classes.length;

        // Check to see if we are not using the default button style
        for (i = 0; i < classesLength; i++) {
            if (classes[i].substring(0, 20) == 'TVI-customDDL-style-') {
                style = classes[i].substring(20);
            }
        }

        // Create a shortcut to the button style
        style = TVI.Components.CustomDDL.styles[style];

        //Work out the width of the middle section
        middleWidth = totalWidth - (style.buttonLeftEndWidth + style.buttonRightEndWidth + style.buttonLeftPadding + style.buttonRightPadding);        
        panelWidth = totalWidth - (style.panelBorderWidth * 2)
    
        element.find('.TVI-customDDL-button-middle').width(middleWidth);
        element.find('.TVI-customDDL-panel').width(panelWidth);
                    
    };
    
    
    
    
    
    var setup = function(container){
    
        //add data to elements
        container.find('.TVI-customDDL').each(function(){
        
            //ignore if already created
            if ($(this).hasClass('TVI-created')){ return; }
        
            $(this).data('componentIndex', componentIndex);
        
        });
    
    };
    




    var update = function(control) {

        var defaultOption = control.find('option:selected');

        var controlHTML = '';

        control.find('option').each(function() {

            var opt = $(this);

            controlHTML += '<div class="TVI-customDDL-option"><span class="value">' + opt.attr('value') + '</span><a href="#">' + opt.text() + '</a></div>';

        });

        var customDDL = control.parents('.TVI-customDDL:first');

        customDDL.find('.TVI-customDDL-button-text').html(defaultOption.text());
        customDDL.find('.TVI-customDDL-options').html(controlHTML);

    };





    /* Public */

    TVI.apply(cmp, {

        /* Properties */

        styles: {
            defaultStyle: {
                buttonLeftEndWidth: 11,
                buttonLeftPadding: 0,
                buttonRightEndWidth: 20,
                buttonRightPadding: 0,
                panelBorderWidth: 1,
                hoverClass: 'TVI-customDDL-hover'
            }
        },

        /* Methods */

        create: function(element) {
            create(element);
        },

        update: function(control) {
            update(control);
        }

    });
    

    TVI.ready(init);

    return cmp;

} ();
