/**
 * Handlers for Alternating Channels page
 */
var maxAltChannels = 8;
var altChannels = [];
var allChannels = {};
var menuList = {};

/**
 * Populate select boxes of an alternating channel container
 */
populateAlternatingChannelDropdown = function(container, conditionChannels) {
    if (conditionChannels === undefined) {
        conditionChannels = {};
    }
    
    if ( !$.isEmptyObject(container) ) {
        var menuString = "";

        //menuList is an associative array of MenuNumber = MenuName, MenuItem1, MenuItem2, ...
        Object.keys(menuList).forEach(function(menuNumber) {
            //Create list item for MenuNumber and sub-list of MenuItems
            var subMenuString = '<div class="flyout"><ul>';
            for (i = 1; i < menuList[menuNumber].length; i++) {
                var subMenuNumber = menuList[menuNumber][i];
                subMenuString += '<li value="' + subMenuNumber + '">' + allChannels[subMenuNumber] + '</li>';
            }
            subMenuString += '</ul></div>';

            //Create dummy element to sort with JQuery
            $elementToSort = $(subMenuString);
            sortList($elementToSort.find('ul'));
            subMenuString = $elementToSort.clone().wrap('<div/>').parent().html();

            menuString += ' \
                <li value="' + menuNumber + '"> \
                    <a>' + menuList[menuNumber][0] + ' </a> \
                    ' + subMenuString + ' \
                </li> \
            ';
        });

        container.find('ul').each(function() {
            var $nav = $(this).closest('nav');
            var conditionName = $nav.attr('name');

            $(this).append(menuString);
            sortList($(this));
            $(this).prepend('<li value=""><a>Ignore Condition</a></li>');
            
            $nav.attr('data-selected', allChannels[conditionChannels[conditionName]]);
            $nav.val(conditionChannels[conditionName]);
        });
    }
}

/**
 * Return the first available alternating channel
 */
getAvailableChannel = function() {
    for (var i = 1; i <= maxAltChannels; i++) {
        if (altChannels.indexOf(i) == -1) {
            return i;
        }
    }
}

/**
 * Create a new alternating channel container
 */
addAlternatingChannelContainer = function( conditionChannels ) { 
    if (conditionChannels === undefined) {
        conditionChannels = {};
    }                    
    var altChannelContainer = $('#altChannelsContainer');
    var altChannelNumber = getAvailableChannel();

    altChannels.push(altChannelNumber);
    sectionName = 'AltChannel' + altChannelNumber;
    altChannelContainer.append(' \
        <div class="top-wrapper box" id="' + sectionName + '"> \
            <span class="analogue-close">&times;</span> \
            <fieldset> \
				<legend> \
                    <h2>&nbsp;Alternating Channel ' + altChannelNumber + ' </h2> \
                </legend> \
                <div class="alt-heading-row"> \
                    <h2 class="alt-heading">Time Interval 1</h2> \
                    <h2 class="alt-heading">Time Interval 2</h2> \
                    <h2 class="alt-heading">Port Tack</h2> \
                    <h2 class="alt-heading">Starboard Tack</h2> \
                </div> \
                <div class="alt-input-row"> \
                    <nav class="channel-dropdown database-input" name="timer1" \
                        data-section="' + sectionName + '" data-key="timer1" \
                        data-selected="Ignore Condition"> \
                        <ul class="menu-list"></ul> \
                    </nav> \
                    <nav class="channel-dropdown database-input" name="timer2" \
                        data-section="' + sectionName + '" data-key="timer2" \
                        data-selected="Ignore Condition"> \
                        <ul class="menu-list"></ul> \
                    </nav> \
                    <nav class="channel-dropdown database-input" name="port" \
                        data-section="' + sectionName + '" data-key="port" \
                        data-selected="Ignore Condition"> \
                        <ul class="menu-list"></ul> \
                    </nav> \
                    <nav class="channel-dropdown database-input" name="stbd" \
                        data-section="' + sectionName + '" data-key="starboard" \
                        data-selected="Ignore Condition"> \
                        <ul class="menu-list"></ul> \
                    </nav> \
                </div> \
                <div class="alt-heading-row"> \
                    <h2 class="alt-heading">Upwind</h2> \
                    <h2 class="alt-heading">Reaching</h2> \
                    <h2 class="alt-heading">Downwind</h2> \
                    <h2 class="alt-heading">Prestart</h2> \
                </div> \
                <div class="alt-input-row"> \
                    <nav class="channel-dropdown database-input" name="upwind" \
                        data-section="' + sectionName + '" data-key="upwind" \
                        data-selected="Ignore Condition"> \
                        <ul class="menu-list"></ul> \
                    </nav> \
                    <nav class="channel-dropdown database-input" name="reaching" \
                        data-section="' + sectionName + '" data-key="reaching" \
                        data-selected="Ignore Condition"> \
                        <ul class="menu-list"></ul> \
                    </nav> \
                    <nav class="channel-dropdown database-input" name="downwind" \
                        data-section="' + sectionName + '" data-key="downwind" \
                        data-selected="Ignore Condition"> \
                        <ul class="menu-list"></ul> \
                    </nav> \
                    <nav class="channel-dropdown database-input" name="prestart" \
                        data-section="' + sectionName + '" data-key="prestart" \
                        data-selected="Ignore Condition"> \
                        <ul class="menu-list"></ul> \
                    </nav> \
                </div> \
            </fieldset> \
        </div> \
    ');
    populateAlternatingChannelDropdown($('#' + sectionName), conditionChannels);
}

/**
 * Populate existing alternating channels. If none exist, one is added by default.
 */
populateAlternatingChannelContainers = function() {
    readSingle("AlternatingChannels", "Channels").done(function(channelList) {
        var definedChannels = channelList.split(";");

        for ( var i = 0; i < definedChannels.length; i++ ) {
            readSection("AltChannel" + definedChannels[i]).done(function(sectionJSON) {
                var section = JSON.parse(sectionJSON);
                addAlternatingChannelContainer(section);
            })
        }
    });
}

/**
 * Load channels from database
 */
loadChannels = function() {
    var functionDeferred = new $.Deferred();
    var outerPromises = [];

    var menuDeferred = new $.Deferred();
    outerPromises.push(menuDeferred);
    readSingle("MFDMenuItems", "MenuItems").done(function(menuString) {
        var innerPromises = [];
        var menuArray = menuString.split(',');
        for (var i = 0; i < menuArray.length; i++) {
            (function(menuItem) {
                var deferred = new $.Deferred();
                innerPromises.push(deferred);
                readSingle("MFDMenuItems", menuItem).done(function(subMenu) {
                    menuList[menuItem] = subMenu.split(',');
                    deferred.resolve();
                });
            })(menuArray[i]);
        }
        $.when.apply($, innerPromises).then(function() {
            menuDeferred.resolve();
        })
    });

    var channelDeferred = new $.Deferred();
    outerPromises.push(channelDeferred);
    readSingle("MFDChannelNames", "ChannelList").done(function(channelList) {
        var channelArray = channelList.split(',');
        for (var i = 0; i < channelArray.length; i += 2) {
            allChannels[channelArray[i]] = channelArray[i+1];
        }
        channelDeferred.resolve();
    })

    $.when.apply($, outerPromises).then(function() {
        functionDeferred.resolve();
    });

    return functionDeferred;
}

 /**
  * Event handlers
  */
$(document).ready(function() {
    var pageHandler = new InputPageHandler('fastnet.php', 'altChannels');

    loadChannels().done(function() {
        populateAlternatingChannelContainers();
    });
    
    $('#addAltChannel').click(function() {
        if (altChannels.length < maxAltChannels) {
            addAlternatingChannelContainer();
        }
    });

    $(document).on('click', '.analogue-close', function() {
        var $container = $(this).closest('.top-wrapper');
        var channelNumber = parseInt($container.attr('id').slice(-1));
        $container.remove();
        altChannels.splice(altChannels.indexOf(channelNumber), 1);
    });

    $(document).on('click', function(event) {
        //Close untargeted dropdowns
        $('nav').not($(event.target).closest('.channel-dropdown')).trigger('closeMenu');
    });

    $(document).on('closeMenu', 'nav', function() {
        $(this).removeClass('channel-dropdown-visible');
        $(this).removeClass('channel-noafter');
    });

    //Open nav dropdown
    $(document).on('click', 'nav', function() {
        $(this).addClass('channel-dropdown-visible');
        //If scrollbar is visible, hide dropdown arrow
        if ( $(this).prop('scrollHeight') > $(this).prop('clientHeight') ) {
            $(this).addClass('channel-noafter');
        }
    });

    //Select dropdown option on click
    $(document).on('click', 'nav ul li a', function() {
        var channelNumber = $(this).closest('li').val();
        $(this).closest('nav').val(channelNumber);
        //::before pseudo element content set through data-selected attribute
        $(this).closest('nav').attr('data-selected', $(this).text());
        $(this).closest('nav').removeClass('channel-noafter');
    });    

    pageHandler.validateForm = function() {

        writeSingle("AlternatingChannels", "Channels", altChannels.join(';'), 'altChannels');

        return $.Deferred().resolve( validateRange($('#timerInterval'), 0, 0, 60, 10) );

    }
});