/**
 * JQuery plugin for converting simple SELECT elements to fancy UnorderedList based drop downs based on CSS 
 * @author Rytis Alekna
 * @use
 * Simple generated raSelect structure
 * 				<div class="comboBox">
					<img class="dropButton" src="images/combo_button.jpg" />
					<ul class="comboList closed">
						<li class="selectedItem"><a href="#">Selected Item1</a></li>
						<li><a href="#">Item1</a></li>
						<li><a href="#">Item2</a></li>
						<li><a href="#">Item3</a></li>
						<li><a href="#">Item4</a></li>
					</ul>
					
				</div>
 */
( function ($) {
	
	var currentlyOpenedSelect;
	
	/**
	 * Finds and replaces checkboxes by given class
	 * @param {String} target (class or id)
	 * @param {Object} options
	 */
	$.fn.raSelect = function ( target, opt ) {
		
		var options = {
			
			/**
			 * Use button?
			 */
			useButton 				: true,
			
			/**
			 * Is menu opened by default?
			 */
			opened					: false,
			
			/**
			 * Style class 
			 */
			topClass				: 'raSelect',
			
			/**
			 * Style class for button 
			 */
			buttonClass 			: 'raSelectButton',
			
			/**
			 * Style class for list (UL)
			 */
			listClass				: 'raSelectList',
			
			/**
			 * Style class for closed list (UL)
			 */
			closedListClass			: 'raSelectClosedList',
			
			/**
			 * Style class for selected item (element of UL)
			 */
			selectedItemClass		: 'raSelectSelectedItem',
			
			/**
			 * Submit on select
			 */
			submitOnSelect			: false
			
		};
		
		var currentZIndex = 100;
		
		// if options are not specified use default settings
		options = $.extend( options, opt );
		
		var changeFunctions = [];
		
		var originalSelectBoxes = [];
		
		/**
		 * Renders a select box
		 * @param {Object} original select box
		 * @return	rendered object
		 */
		function renderRaSelectBox( originalSelectBox ) {
			var retVal = $('<div ' + 
				( $( originalSelectBox ).attr('id') != undefined ? 'id=\'' + $( originalSelectBox ).attr('id') + '\' ' : '' ) + 
				' class=\'' + options.topClass + '\' ' +
				( $( originalSelectBox ).attr('onchange') != undefined ? 'onchange=\'' + $( originalSelectBox ).attr('onchange') + '\' ' : '' ) + 
				( $( originalSelectBox ).attr('onfocus') != undefined ? 'onfocus=\'' + $( originalSelectBox ).attr('onfocus') + '\' ' : '' ) + 
				( $( originalSelectBox ).attr('onblur') != undefined ? 'onblur=\'' + $( originalSelectBox ).attr('onblur') + '\' ' : '' ) + 
				 '>' + 
				( options.useButton ? ('<a href=\'#\' class=\''+ options.buttonClass + '\'></a>' ) : '' ) +
				'<ul class=\'' + options.listClass + ( options.opened ? '' : ' ' + options.closedListClass ) + '\'></ul>' +
				'<input type=\'hidden\' name=\'' + $( originalSelectBox ).attr('name') + '\' ' + ( $( originalSelectBox ).attr('id') != undefined ? 'id=\'' + $( originalSelectBox ).attr('id') + '\' ' : '' ) + ' />' + 
				'</div>');
			
			var selectedItem ='';
			var listItems = new Array();
			
			// push LI items to array
			$( 'option', originalSelectBox ).each(
				function () {
					listItems.push( '<li><a href=\'' + ( $(this).val() ? $(this).val() : '' ) + '\'>' + $(this).text() + '</a></li>' );
					
					
					// if ( Option(this).selected ) {
					if ( $( this ).attr('selected') == true ) {
						selectedItem = '<li class=\'' + options.selectedItemClass + '\'><a href=\'' + ( $(this).val() ? $(this).val() : '' ) + '\'>' + $(this).text() + '</a></li>';
						$( 'input', retVal).val( $(this).val() );
					}
					
				}			
			)
			
			$( '.' + options.listClass, retVal).html( selectedItem + listItems.join('') );
			
			retVal = $('<div>').append( $(retVal).clone()).remove().html(); 
			
			changeFunctions.push( $( originalSelectBox ).attr('onchange') )
			
			originalSelectBoxes.push( originalSelectBox );
			
			return retVal;
			
		}
		
		/**
		 * Add functionality to select box
		 * @param {Object} generated select box
		 */
		function addFunctionality ( value, index ) {
			
			var list = $( '.' + options.listClass, value );
			
			// alert( $(value).change() );
			
			//var change = $(value).attr('onchange');
			//var focus = $(value).attr('onfocus');
			// var blur = $(value).attr('onblur');
			
			// change item on select
			$( '.' + options.listClass + ' a', value ).click(
				function () {
					
					var optionIndex = $( '.' + options.listClass + ' a', value ).index(this);
					
					if (list.hasClass(options.closedListClass)) {
						
						list.removeClass(options.closedListClass);
						list.css('z-index', currentZIndex++);
						if ( currentlyOpenedSelect && currentlyOpenedSelect != list ) {
							currentlyOpenedSelect.addClass(options.closedListClass);
						}
						currentlyOpenedSelect = list;
					} else {
						
						list.addClass( options.closedListClass );
						
					}
					
					if ( $( 'input:hidden', value ).val() != $( this ).attr('href') )  {
						$( '.' + options.selectedItemClass + ' a', value ).html( $( this ).html() );
						$( 'input:hidden', value ).val( $( this ).text() );
						
						// this.value = $( this ).attr('href');
						// $(originalSelectBoxes[ index ]).attr( 'value', ($( this ).attr('href')) );
						
						$(originalSelectBoxes[ index ]).attr( 'selectedIndex', optionIndex - 1 );
						//alert( $(originalSelectBoxes[ index ]).attr( 'selectedIndex' ) );
						if (changeFunctions[index] != undefined) {
							// alert( changeFunctions[index] );
							// changeFunctions[index]( new $.Event('onchange') );
							// changeFunctions[index]( $.Event('change'), $( this ).text() );
							
							// originalSelectBoxes[ index ].onchange();
							
							$(originalSelectBoxes[ index ]).change();
							
							return false;
							
							// changeFunctions[index](  )
							// $(originalSelectBoxes[ index ]).trigger('change');
						}
						
					}
					
					if ( options.submitOnSelect ) {
						$( value ).parents('form').submit();
					}
					
					return false;
					
				}
			);
			
			// open close on button press
			if ( options.useButton ) {
				$('.' + options.buttonClass, value ).click( 
					function () {
						// var list = $( '.' + options.listClass, value );
						if (list.hasClass(options.closedListClass)) {
							list.removeClass(options.closedListClass);
							list.css('z-index', ++currentZIndex);
						} else {
							list.addClass( options.closedListClass );
						}
						
						if (currentlyOpenedSelect && currentlyOpenedSelect != list ) {
							
							currentlyOpenedSelect.addClass(options.closedListClass);
						}
						currentlyOpenedSelect = list;

						
						return false;
					}
				 )
			}
			
			return {
				
				
				
			}
			

		}
		
		$( target ).each(
				function () {
					$(this).replaceWith( renderRaSelectBox( this ) );
				}			
		)
		
		$( '.' + options.topClass ).each(
			function () {
				addFunctionality( this, $( '.' + options.topClass ).index(this) );
			}
		);
		
		$(document).click(
			function () {
				if ( currentlyOpenedSelect ) {
					currentlyOpenedSelect.addClass( options.closedListClass );
					currentlyOpenedSelect = null;
				}
			}
			
		)
		
		return this;
		
	}
	
})( jQuery );

