/* Author: 
	Matt Ladner and Friends
*/
	
$(document).ready(function() {

    // LOKWON-482 Dropdown navigation. Handles more than one if necessary.
    (function() {
        var navigation = $('#nav-drop'),
            dropdowns = navigation.find('select');

        dropdowns.each(function() {
            var dropdown = $(this);
            dropdown.change(function(e) {
                e.preventDefault();
                var val = $(this).val();
                // If the value isn't blank, go to whatever page or named anchor that is referenced by this value
                if (!val.match(/^\s*$/)) {
                    window.location = val;
                }
            });
        });
    }());

    $('#page-header nav:first').each(function() {
        var nav = $(this),
            footer = $('#global-footer'),
            waypointOptions = {
                offset: '100%'
            };

        nav.data('initialOffset', nav.offset()).data('totalHeight', (function() {
            var maxHeight = 0;
            nav.find('*').map(function() {
                var height = $(this).height();
                maxHeight = (height > maxHeight) ? height : maxHeight;
            });
            return maxHeight;
        }()));


        footer.waypoint(function(e, dir) {
            if ('down' === dir) {

                var top = nav.data('initialOffset').top + $(window).scrollTop();

                nav.css({
                    position: 'absolute',
                    top: [top, 'px'].join('')
                });

                // Check to see if the nav appears to have been placed behind the footer.

                (function() {
                    var navTop = nav.offset().top,
                        navHeight = nav.data('totalHeight'),
                        footerTop = footer.offset().top,
                        overflowAmount = function() {
                            return footerTop - (navTop + navHeight);
                        },
                        isOverflowing = function() {
                            return (navTop + navHeight) >= footerTop;
                        };


                    // If the sum of the y-coordinate of the nav block plus its height is greater than
                    // the value of the y-coordinate of the footer, then some portion of the nav block is
                    // obscured by the footer and it needs to be adjusted upwards.
                    if (isOverflowing()) {
                        var currentTop = parseInt(nav.css('top'), 10);
                        nav.animate({
                            top: [currentTop + overflowAmount() - 100, 'px'].join('')
                        }, 100);
                    }
                }());

            } else {
                nav.css({
                    position: 'fixed',
                    top: 'auto'
                });
            }
        }, waypointOptions);

        // Check to see if the nav has moved behind the footer on a AFAP-scroll (As Fast As Possible).
        $(window).scroll(function(e) {

        });
    });



	// Populate submenu navigation
	var current_submenu = $.map( $('nav li.current_page_item ul li'), function (element) { return $(element).text() }).join(', '); 
	current_submenu += $.map( $('nav li.current_page_parent ul li'), function (element) { return $(element).text() }).join(', '); 
	
	var submenu_links = $.map( $('nav li.current_page_item ul li a'), function (element) { return $(element).attr('href') }).join(', '); 
	submenu_links += $.map( $('nav li.current_page_parent ul li a'), function (element) { return $(element).attr('href') }).join(', '); 
	
	
	if (submenu_links == '') {
		submenu_links += $.map( ($('nav li.current-menu-parent').closest('ul').children('li').children('a')), function (element) { return $(element).attr('href') }).join(', '); 
	}
	if (current_submenu == '') {
		current_submenu += $.map( ($('nav li.current-menu-parent').closest('ul').children('li')), function (element) { return $(element).text() }).join(', '); 
	}
	
	var submenu_arr = current_submenu.split(','); 
	var sublink_arr = submenu_links.split(','); 
	
	var current_selected_item = $('nav li.current_page_parent ul li.current-menu-item').text();
	var current_parent_item = $('nav li.current_page_parent > a').text();
	var current_menu_parent= $('nav li.current-menu-parent > a').text();
	
	
	var parentEls = $("nav li.current-menu-parent").closest("ul").parent().get(0);
	var parentName = $(parentEls).children('a').text();
	
	if(current_parent_item != '' & current_parent_item != null) {
		$('#primary-dropdown option:contains(\'' + current_parent_item + '\')').attr('selected', 'selected');
	} else if(current_menu_parent != '' & current_menu_parent != null) {
		$('#primary-dropdown option:contains(\'' + current_menu_parent + '\')').attr('selected', 'selected');
	} 
	
	if(parentName != '' & parentName != null) {
		$('#primary-dropdown option:contains(\'' + parentName + '\')').attr('selected', 'selected');
	}
	
	if (current_selected_item == '') {
		current_selected_item = $('nav li.current-menu-parent:first').text();
	}

	populateSubNav();
	function populateSubNav() {
		var options = '<option value="">Select page</option>';
		if (submenu_arr.length <= 1) {
		} else {
			for (var i = 0; i < submenu_arr.length; i++) {
				var str_val = submenu_arr[i]; 
				str_val.replace(/\s+/g, '-').toLowerCase(); 
				if (current_selected_item != $.trim(submenu_arr[i])) {
					options += '<option value="' + sublink_arr[i] + '">' + $.trim(submenu_arr[i]) + '</option>';
				} else {
					options += '<option value="' + sublink_arr[i] + '" selected="selected">' + $.trim(submenu_arr[i]) + '</option>';
				}
			}
			$('#secondary-dropdown').html(options);
			$('#secondary-navigation').show();
		}
	}

});
