/**
* Stylish Select 0.4.5 - jQuery plugin to replace a select drop down box with a stylable unordered list
* http://github.com/sko77sun/Stylish-Select
* 
* Requires: jQuery 1.3 or newer
* 
* Contributions from Justin Beasley: http://www.harvest.org/ Anatoly Ressin: http://www.artazor.lv/ Wilfred Hughes: https://github.com/Wilfred
* 
* Dual licensed under the MIT and GPL licenses.
*/


(function($j)
{
	//add class to html tag
	$j('html').addClass('stylish-select');

	//Cross-browser implementation of indexOf from MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
	if (!Array.prototype.indexOf)
	{
		Array.prototype.indexOf = function(searchElement /*, fromIndex */)
		{
			if (this === void 0 || this === null)
				throw new TypeError();

			var t = Object(this);
			var len = t.length >>> 0;
			if (len === 0)
				return -1;

			var n = 0;
			if (arguments.length > 0)
			{
				n = Number(arguments[1]);
				if (n !== n) // shortcut for verifying if it's NaN
					n = 0;
				else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
					n = (n > 0 || -1) * Math.floor(Math.abs(n));
			}

			if (n >= len)
				return -1;

			var k = n >= 0
			? n
			: Math.max(len - Math.abs(n), 0);

			for (; k < len; k++)
			{
				if (k in t && t[k] === searchElement)
					return k;
			}
			return -1;
		};
	}

	//utility methods
	$j.fn.extend(
	{
		getSetSSValue: function(value)
		{
			if (value)
			{
				//set value and trigger change event
				$j(this).val(value).change();
				return this;
			}
			else
			{
				return $j(this).find(':selected').val();
			}
		},
		//added by Justin Beasley
		resetSS: function()
		{
			var oldOpts = $j(this).data('ssOpts');
			$jthis = $j(this);
			$jthis.next().remove();
			//unbind all events and redraw
			$jthis.unbind('.sSelect').sSelect(oldOpts);
		}
	});

	$j.fn.sSelect = function(options)
	{
		return this.each(function()
		{
			var defaults = {
				defaultText:    'Seleccionar opção',
				animationSpeed: 0, //set speed of dropdown
				ddMaxHeight:    '', //set css max-height value of dropdown
				containerClass: '' //additional classes for container div
			};

			//initial variables
			var opts = $j.extend(defaults, options),
			$jinput = $j(this),
			$jcontainerDivText    = $j('<div class="selectedTxt"></div>'),
			$jcontainerDiv        = $j('<div class="newListSelected ' + opts.containerClass + '"></div>'),
			$jcontainerDivWrapper = $j('<div class="SSContainerDivWrapper" style="visibility:hidden;"></div>'),
			$jnewUl               = $j('<ul class="newList"></ul>'),
			itemIndex            = -1,
			currentIndex         = -1,
			prevIndex            = -1,
			keys                 = [],
			prevKey              = false,
			prevented            = false,
			$jnewLi;

			//added by Justin Beasley
			$j(this).data('ssOpts',options);

			//build new list
			$jcontainerDiv.insertAfter($jinput);
			$jcontainerDiv.attr("tabindex", $jinput.attr("tabindex") || "0");
			$jcontainerDivText.prependTo($jcontainerDiv);
			$jnewUl.appendTo($jcontainerDiv);
			$jnewUl.wrap($jcontainerDivWrapper);
			$jcontainerDivWrapper = $jnewUl.parent();
			$jinput.hide();

			//added by Justin Beasley (used for lists initialized while hidden)
			$jcontainerDivText.data('ssReRender',!$jcontainerDivText.is(':visible'));

			//test for optgroup
			if ($jinput.children('optgroup').length == 0)
			{
				$jinput.children().each(function(i)
				{
					var option = $j(this).text();
					var key = $j(this).val();

					//add first letter of each word to array
					keys.push(option.charAt(0).toLowerCase());
					if ($j(this).attr('selected') == 'selected' || $j(this).attr('selected') == true)
					{
						opts.defaultText = option;
						currentIndex = prevIndex = i;
					}
					$jnewUl.append($j('<li><a href="JavaScript:void(0);">'+option+'</a></li>').data('key', key));

				});
				//cache list items object
				$jnewLi = $jnewUl.children().children();

			}
			else //optgroup
			{
				$jinput.children('optgroup').each(function()
				{
					var optionTitle = $j(this).attr('label'),
					$joptGroup = $j('<li class="newListOptionTitle">'+optionTitle+'</li>'),
					$joptGroupList = $j('<ul></ul>');

					$joptGroup.appendTo($jnewUl);
					$joptGroupList.appendTo($joptGroup);

					$j(this).children().each(function()
					{
						++itemIndex;
						var option = $j(this).text();
						var key = $j(this).val();
						//add first letter of each word to array
						keys.push(option.charAt(0).toLowerCase());
						if ($j(this).attr('selected') == 'selected' || $j(this).attr('selected') == true)
						{
							opts.defaultText = option;
							currentIndex = prevIndex = itemIndex;
						}
						$joptGroupList.append($j('<li><a href="JavaScript:void(0);">'+option+'</a></li>').data('key',key));
					})
				});
				//cache list items object
				$jnewLi = $jnewUl.find('ul li a');
			}

			//get heights of new elements for use later
			var newUlHeight = $jnewUl.height(),
			containerHeight = $jcontainerDiv.height(),
			newLiLength     = $jnewLi.length;


			//check if a value is selected
			if (currentIndex != -1)
			{
				navigateList(currentIndex);
			}
			else
			{
				//set placeholder text
				$jcontainerDivText.text(opts.defaultText);
			}

			//decide if to place the new list above or below the drop-down
			function newUlPos()
			{
				var containerPosY = $jcontainerDiv.offset().top,
				docHeight         = $j(window).height(),
				scrollTop         = $j(window).scrollTop();

				//if height of list is greater then max height, set list height to max height value
				if (newUlHeight > parseInt(opts.ddMaxHeight))
				{
					newUlHeight = parseInt(opts.ddMaxHeight);
				}

				containerPosY = containerPosY-scrollTop;
				if (containerPosY+newUlHeight >= docHeight)
				{
					$jnewUl.css(
					{
						height: newUlHeight
					});
					$jcontainerDivWrapper.css({
						top:    '-'+newUlHeight+'px',
						height: newUlHeight
					});
					$jinput.onTop = true;
				}
				else
				{
					$jnewUl.css(
					{
						height: newUlHeight
					});
					$jcontainerDivWrapper.css(
					{
						top:     containerHeight+'px',
						height: newUlHeight
					});
					$jinput.onTop = false;
				}
			}

			//run function on page load
			newUlPos();

			//run function on browser window resize
			$j(window).bind('resize.sSelect scroll.sSelect', newUlPos);

			//positioning
			function positionFix()
			{
				$jcontainerDiv.css('position','relative');
			}

			function positionHideFix()
			{
				$jcontainerDiv.css(
				{
					position: 'static'
				});
			}

			$jcontainerDivText.bind('click.sSelect',function(event)
			{
				event.stopPropagation();

				//added by Justin Beasley
				if($j(this).data('ssReRender'))
				{
					newUlHeight = $jnewUl.height('').height();
					$jcontainerDivWrapper.height('');
					containerHeight = $jcontainerDiv.height();
					$j(this).data('ssReRender',false);
					newUlPos();
				}
				
				//hide all menus apart from this one
				$j('.SSContainerDivWrapper')
				.not($j(this).next())
				.hide()
				.parent()
				.css('position', 'static')
				.removeClass('newListSelFocus');
					
				//show/hide this menu
				$jcontainerDivWrapper.toggle();
				positionFix();
				
				//scroll list to selected item
				if(currentIndex == -1) currentIndex = 0;
				$jnewLi.eq(currentIndex).focus();
			});

			function closeDropDown(fireChange, resetText)
			{
				if(fireChange == true)
				{
					prevIndex = currentIndex;
					$jinput.change();
				}
				
				if(resetText == true)
				{
					currentIndex = prevIndex;
					navigateList(currentIndex);
				}
				
				$jcontainerDivWrapper.hide();
				positionHideFix();
			}

			$jnewLi.bind('click.sSelect',function(e)
			{
				var $jclickedLi = $j(e.target);

				//update counter
				currentIndex = $jnewLi.index($jclickedLi);

				//remove all hilites, then add hilite to selected item
				prevented = true;
				navigateList(currentIndex, true);
				closeDropDown();
			});

			$jnewLi.bind('mouseenter.sSelect',
				function(e)
				{
					var $jhoveredLi = $j(e.target);
					$jhoveredLi.addClass('newListHover');
				}
				).bind('mouseleave.sSelect',
				function(e)
				{
					var $jhoveredLi = $j(e.target);
					$jhoveredLi.removeClass('newListHover');
				}
				);

			function navigateList(currentIndex, fireChange)
			{
				if(currentIndex == -1)
				{
					$jcontainerDivText.text(opts.defaultText);
					$jnewLi.removeClass('hiLite');
				}
				else
				{
					$jnewLi.removeClass('hiLite')
					.eq(currentIndex)
					.addClass('hiLite');

					var text = $jnewLi.eq(currentIndex).text(),
					val = $jnewLi.eq(currentIndex).parent().data('key');

					try
					{
						$jinput.val(val)
					}
					catch(ex)
					{
						// handle ie6 exception
						$jinput[0].selectedIndex = currentIndex;
					}

					$jcontainerDivText.text(text);
				
					//only fire change event if specified
					if(fireChange == true)
					{
						prevIndex = currentIndex;
						$jinput.change();
					}
				
					if ($jcontainerDivWrapper.is(':visible'))
					{
						$jnewLi.eq(currentIndex).focus();
					}
				}
			}

			$jinput.bind('change.sSelect',function(event)
			{
				var $jtargetInput = $j(event.target);
				//stop change function from firing
				if (prevented == true)
				{
					prevented = false;
					return false;
				}
				var $jcurrentOpt  = $jtargetInput.find(':selected');
				currentIndex = $jtargetInput.find('option').index($jcurrentOpt);
				navigateList(currentIndex);
			});

			//handle up and down keys
			function keyPress(element)
			{
				//when keys are pressed
				$j(element).unbind('keydown.sSelect').bind('keydown.sSelect',function(e)
				{
					var keycode = e.which;

					//prevent change function from firing
					prevented = true;

					switch(keycode)
					{
						case 40: //down
						case 39: //right
							incrementList();
							return false;
							break;
						case 38: //up
						case 37: //left
							decrementList();
							return false;
							break;
						case 33: //page up
						case 36: //home
							gotoFirst();
							return false;
							break;
						case 34: //page down
						case 35: //end
							gotoLast();
							return false;
							break;
						case 13: //enter
						case 27: //esc
							closeDropDown(true);
							return false;
							break;
					}

					//check for keyboard shortcuts
					keyPressed = String.fromCharCode(keycode).toLowerCase();

					var currentKeyIndex = keys.indexOf(keyPressed);

					if (typeof currentKeyIndex != 'undefined')
					{ //if key code found in array
						++currentIndex;
						currentIndex = keys.indexOf(keyPressed, currentIndex); //search array from current index

						if (currentIndex == -1 || currentIndex == null || prevKey != keyPressed)
						{
							// if no entry was found or new key pressed search from start of array
							currentIndex = keys.indexOf(keyPressed);
						}

						navigateList(currentIndex);
						//store last key pressed
						prevKey = keyPressed;
						return false;
					}
				});
			}

			function incrementList()
			{
				if (currentIndex < (newLiLength-1))
				{
					++currentIndex;
					navigateList(currentIndex);
				}
			}

			function decrementList()
			{
				if (currentIndex > 0)
				{
					--currentIndex;
					navigateList(currentIndex);
				}
			}

			function gotoFirst()
			{
				currentIndex = 0;
				navigateList(currentIndex);
			}

			function gotoLast()
			{
				currentIndex = newLiLength-1;
				navigateList(currentIndex);
			}

			$jcontainerDiv.bind('click.sSelect',function(e)
			{
				e.stopPropagation();
				keyPress(this);
			});

			$jcontainerDiv.bind('focus.sSelect',function()
			{
				$j(this).addClass('newListSelFocus');
				keyPress(this);
			});

			$jcontainerDiv.bind('blur.sSelect',function()
			{
				$j(this).removeClass('newListSelFocus');
			});

			//hide list on blur
			$j(document).bind('click.sSelect',function()
			{
				$jcontainerDiv.removeClass('newListSelFocus');
				
				if ($jcontainerDivWrapper.is(':visible'))
				{
					closeDropDown(false, true);
				}
				else
				{
					closeDropDown(false);
				}
			});

			//add classes on hover
			$jcontainerDivText.bind('mouseenter.sSelect',
				function(e)
				{
					var $jhoveredTxt = $j(e.target);
					$jhoveredTxt.parent().addClass('newListSelHover');
				}
				).bind('mouseleave.sSelect',
				function(e)
				{
					var $jhoveredTxt = $j(e.target);
					$jhoveredTxt.parent().removeClass('newListSelHover');
				}
				);

			//reset left property and hide
			$jcontainerDivWrapper.css(
			{
				left: '0',
				display: 'none',
				visibility: 'visible'
			});

		});

	};

})(jQuery);

