/*
 * AT_dropNav.js - A jQuery Plugin
 * A jQuery plugin for creating dropdown select boxes from a UL nested list
 *
 * By Andy Tennison (andrew@tennisons.com / http://www.tennisons.com)
 *
 * Version 1.0.1
 * October 8th, 2009
 *
 * Copyright (c) 2009 Andy Tennison
 * Dual licensed under the MIT and GPL licenses.
*/

(function($) {
	$.fn.AT_dropNav = function(options) {
		var opts = $.extend({}, $.fn.AT_dropNav.defaults, options);

		return this.each(function(ii){
			$n = $(this);
			$topList = $(this).find('ul:first')
			$topLevel = [];
			
			$n.append(
				 '<div class="pc_link">'
				 		+'<a class="pc_btn" id="pc_1" href="#control_1"><span>Choose a range</span></a>'
						+'<div class="pc_list"><div class="pc_listInner"></div></div>'
				+'</div>'
				+'<div class="pc_link">'
						+'<a class="pc_btn off" id="pc_2" href="#control_2"><span>---</span></a>'
						+'<div class="pc_list"><ul></ul><div class="pc_listInner"></div></div>'
				+'</div>'
				)
			$A = $n.find('.pc_list:eq(0)');
			$B = $n.find('.pc_list:eq(1)');
			
			$topList.children('li').each(function(i){
				$topLevel[i] = $(this);
				$topLevel[i].link = $(this).children('a');
				$topLevel[i].list = $(this).children('ul');
				
				$A.append($topLevel[i].link)								//creates dropdown list A
			});
					
			$('.pc_link a.pc_btn').bind("click", function(e){
				e.preventDefault();
				var thisList = $(this).siblings('.pc_list');
				if(thisList.find('a').html()){
					thisList.toggle();
				};
				if (e.type == 'focus') {
					thisList.find('a:first').focus()
				};
				thisList.find('a:last').blur(function(){
					thisList.hide();
				});
    		});
			
			$('.pc_link .pc_list').hover(function(){
        		//empty
    		}, function(){
				$(this).hide();
			});
			
			
			$A.find('a').click(function(e){
				e.preventDefault();
				var thisI = $('.pc_list a').index(this);
				$A.hide();
				$A.siblings('a.pc_btn').find('span').text($(this).text());
				$B.siblings('a.pc_btn').find('span').text('Choose a variety of '+$(this).text());

				$B.find('ul').empty().append($topLevel[thisI].list.html());		//creates dropdown list B
				$B.siblings('a.pc_btn').removeClass('off');
				
				$('#pc_2').focus();
				clickB ();
			})
			
			
			function clickB (){
				$B.find('a').click(function(e){
					e.preventDefault();
					$B.hide();
					$B.siblings('a.pc_btn').find('span').text($(this).text());
					if (!$(this).hasClass("on")) {
						window.location.href = $(this).attr('href');
					}
				});			
			};
			
			//sets boxes if any contain "on" class
			$A.find('a.on').click()
			$B.find('a.on').click()
				
		}); // end subList
		
	}; // end plugin AT_dropNav


// end of closure
})(jQuery);

$.fn.AT_dropNav.defaults = {
	test: 'test'
};

