/* HomeAway GTMenu Drop Build - $BuildNumber */
(function($){
	var version = 'build-$BuildNumber';
	
	jQuery.fn.gtmenu = function(options){
		
		//build main options before element iteration
		opts = $.extend({}, jQuery.fn.gtmenu.defaults, options);
		
		return $(this).each(function(){
			var self = $(this);
				self.selectedIndex = -1;
			var minwidth = 0;
			var minheight = 0;
			var menupadding = 20;
			var wrap, arrow, arrowwrap, choices, ul;
				
			//Check to see if the tag is a SELECT, if so we need to mock it with a ul
			if(this.tagName.toLowerCase() == 'select'){
				self.css({position:'absolute'}).hide();
				var ul = $('<ul class="gtmenu"></ul>');
				self.children('option').each(function(){
					var li = $('<li></li>').text($(this).text()).addClass($(this).attr('class'));//.val($(this).val());
					
					// Add address for swaping text
					if(this.selected) {
						// Copy text and store it in an attribute
						li.addClass('gtmenu-active').attr('data-address', $(this).text());
						
						// Swap Text
						if (opts.swapLabel) {
							li.text('Выберите действие');
						}
					}
					
					li.attr('data-value', $(this).val());
					ul.append(li);
				});
				choices = ul.children();
			}else{
				self.addClass('gtmenu');
				choices = self.children();
			}

			choices.children('a').each(function(){
				$(this).parent().attr('data-value', $(this).attr('href'));
				$(this).removeAttr('href');
			});
			
			//Wrap the control in a div so we can style it
			wrap = self.wrap('<a class="'+opts.wrapClass+'" href="#"></a>').parent();
			if(this.tagName.toLowerCase() == 'select') wrap.append(ul);
			
			if (opts.hasLabel != true) {
				arrow = $('<div class="gtmenu-arrow"></div>');
				arrowwrap = $('<div class="gtmenu-arrow-wrap"></div>');
				
				//get the width of the gtmenu-arrow-wrap div so we can add it to the width of the ul and get the total width
				if (typeof(arrowwrapwidth) == 'undefined') {
					$selectorPlaceholder = $('<div class="gtmenu-wrap" style="position:absolute;top:-1000px;left:-1000px;"></div>').append(arrowwrap);
					$('body').append($selectorPlaceholder)
					arrowwrapwidth = $selectorPlaceholder.find('.gtmenu-arrow-wrap').outerWidth();
					$selectorPlaceholder.remove();
				}
				
				choices.each(function(){
					//minwidth = Math.max($(this).outerWidth(), minwidth);
					minheight = Math.max($(this).outerHeight(), minheight);
					if($(this).children().length > 0) $(this).children().bind('click', function(evt){evt.preventDefault()});
				}).addClass('gtmenu-option');
				
				//minwidth += arrowwrapwidth;
				
				wrap.append(arrowwrap.append(arrow)).css({minHeight:minheight+'px'});
				
				if($('.gtmenu-active', wrap).length == 0) {
					choices.first().addClass('gtmenu-active');
					self.selectedIndex = 0;
				}else{
					self.selectedIndex = choices.index($('.gtmenu-active', wrap));
				}
			}
			self.css({width:'auto'});
			self.data('maxsize', opts.maxsize);
			wrap[0].hideFocus = true;
			wrap[0].setAttribute('tabindex',0);
			wrap.bind('click.gtmenu', {'choices':choices,'self':self,'rightAlign':opts.rightAlign,'swapLabel':opts.swapLabel}, $.fn.gtmenu.showMenu);
			wrap.bind('focus.gtmenu', function(){
				this.hasFocus = true;
			}).bind('blur.gtmenu', function(event){
				//alert('blur');
				$('.gtmenu-open').removeClass('gtmenu-open').onCloseGTMenu(); //  gtmenu-scroll
				this.hasFocus = false;
				if(choices.index($('.gtmenu-active', wrap)) != self.selectedIndex) {
					self.selectedIndex = choices.index($('.gtmenu-active', wrap));
					self.attr('data-value', choices.eq(self.selectedIndex).attr('data-value'));
					self.trigger('change');
				}
				return false;
			});
			wrap.bind('keydown.gtmenu', function(event){
				if($.inArray(event.keyCode, [0,32]) !== -1) {
					$(this).trigger('click.gtmenu');
					return false;
				}else if($.inArray(event.keyCode, [38,40] !== -1)) {
					switch (event.keyCode) {
						case 38:
							if(choices.index($('.gtmenu-active', wrap)) > 0)
							choices.parent().children('.gtmenu-active').removeClass('gtmenu-active').prev().addClass('gtmenu-active');
							break;
						case 40:
							if(choices.index($('.gtmenu-active', wrap)) < choices.length-1)
							choices.parent().children('.gtmenu-active').removeClass('gtmenu-active').next().addClass('gtmenu-active');
							break;
					}
					selectedIndex = choices.index($('.gtmenu-active', wrap));
					return true;
				}
			})
			if (opts.hasLabel) {
				wrap.prev().bind('click.gtmenu', {'choices':choices,'self':self,'label':true}, $.fn.gtmenu.showMenu);
			}
			wrap.attr("id", $(this).attr("id")+"-gtmenu");

			});
	};
	$.fn.gtmenu.defaults = {
		wrapClass: 'gtmenu-wrap',
		rightAlign: false,
		swapLabel: false,
		hasLabel: false
	};
	$.fn.onCloseGTMenu = function(){
		if (opts.swapLabel) $(this).setText();
		for(var i=0; i<this.length; i++){
			var $obj = $(this[i]);
			$obj.parent().css({overflow:'hidden'});
			$obj.css({top: 0,width:'',right:'auto'}).removeClass('gtmenu-scroll');
		}
		return this;
	};
	$.fn.setText = function(){
		if ($(this).find('li.gtmenu-active')) {
			 $(this).find('li.gtmenu-active').text('Выберите действие');
		}
		return this;
	};
	
	$.fn.gtmenu.showMenu = function(event){
		var self = event.data.self;
		var choices = event.data.choices;
		var rightAlign = event.data.rightAlign;
		var swapLabel = event.data.swapLabel;
		if (event.data.label != undefined) {
			var label = event.data.label;
		} else {
			var label = false;
		}
		if (rightAlign == true) {
			var ul = $(this).children('ul').removeClass('gtmenu-scroll').css({height: 'auto', width: 'auto', top: '0px', right: '0px' }); // for scroll+moveup
		} else {
			var ul = $(this).children('ul').removeClass('gtmenu-scroll').css({height: 'auto', width: 'auto', top: '0px' }); // for scroll+moveup
		}
		
		if (ul.hasClass('gtmenu-open')){
			event.stopPropagation();
			event.preventDefault();
			$(this).trigger('blur');
		} else {
			var opening = false; // for scroll+moveup
			if (label) {
				opening = true; // for scroll+moveup
				$(this).next().children('ul').addClass('gtmenu-open');
			} else {
				opening = true; // for scroll+moveup
				$(this).children('ul').addClass('gtmenu-open');
				
				// Check for swapped text and revert
				if (swapLabel && $(this).find('li.gtmenu-active')) {
					 $(this).find('li.gtmenu-active').text($(this).find('li.gtmenu-active').data('address'));
				}
				
				self.parent()[0].focus();
			}
			
			// START scroll+moveup
			if(opening){
				var itemlimit = ul.data('maxsize') || 10;
				var listlen = ul.children().length;
				var listh = ul.outerHeight();
				var listparent = ul.parent();
				listparent.css({overflow:'visible'});
				ul[0].onmousedown = ul[0].onselectstart = function(){return false;}
				
				// scrolling?
				if(itemlimit<listlen){
					listparent.css({overflow:'visible'});
					var listw = ul.width();
				
					var itemh = listh / listlen;
					var winh = $(window).height();
					var maxh = itemlimit * itemh;
					listh = maxh;
					ul.addClass('gtmenu-scroll').css({height: maxh, width: listw}); // listw+20
				}
				
				// moveup?
				var $win = $(window);
				var portbottom = $win.scrollTop() + $win.height();
				var listbottom = Math.round(ul.offset().top + listh); 
				if(listbottom>portbottom)ul.css('top', (listbottom-portbottom+10)*-1); 
				
			}
			// END scroll+moveup
			
			choices.unbind('click.gtmenu').bind('click.gtmenu', function(evt){
				evt.stopPropagation();
				choices.removeClass('gtmenu-active').removeAttr('style');
				if (label) {
					//$(this).next().addClass('gtmenu-active');
				} else {
					$(this).addClass('gtmenu-active');
				}
				$('.gtmenu-open').removeClass('gtmenu-open').onCloseGTMenu();

				choices.unbind('click.gtmenu');
				self.selectedIndex = choices.index($('.gtmenu-active', self.parent()));
				
				self.attr('data-value', choices.eq(self.selectedIndex).attr('data-value'));
				
				if (self.children('option').length > 0) {
					self.val(choices.eq(self.selectedIndex).attr('data-value'))
					self.children('option:selected').removeAttr('selected');
					self.children('option:eq('+self.selectedIndex+')').attr('selected','selected');
				}
				
				self.trigger('change');
				
				return false;
			});

			$(document).bind('click.gtmenu', function(event){
				$('.gtmenu-open').removeClass('gtmenu-open').onCloseGTMenu();
				choices.unbind('click.gtmenu');
				$(document).unbind('click.gtmenu');
			});

			event.stopPropagation();
			event.preventDefault();
			return false;
		}
	};
})(jQuery);
