/*
 * 	 styleSelect - apply style to a select box
 *   (http://www.8stream.com/blog/entry/styleselect)
 *
 * 	 Copyright (c) 2010 Siim Sindonen, <siim@8stream.com>
 *   Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 *   Requires jQuery version: >= 1.3.2
 * 	 Version: 2.0.0 | 15.10.2010
 */
 
(function($){

	$.fn.styleSelect = function(options){
		
		var tabindex = 1;
		
		var opts = $.extend({}, $.fn.styleSelect.defaults , options);
		
		//set tabindex		
		$('input,select,textarea,button').each(function() {
			
			var input = $(this);
				
			if (!input.attr('tabindex')){
				
				input.attr('tabindex', tabindex);
				tabindex++;
			}
		});


        $("."+opts.styleClass).remove();
        
		var result = this.each(function(){

			mainSelect = $(this);
            
			var orgSelectbox = mainSelect.attr('name');
			var mainId = orgSelectbox.replace(/\[.*\]/, '');
			
			var styledTabIndex = mainSelect.attr('tabindex');
			
			var date = new Date;
			var selectId = 'selectbox_'+mainId+date.getTime();
			
			//Hidde select box
			mainSelect.hide();
	
			//Main container 
			var mainContainer = $('<div tabindex="'+styledTabIndex+'"></div>')
					.css({position : 'relative', 'z-index' : parseInt(1000 - styledTabIndex)})
					.addClass(opts.styleClass)
					.attr('id', selectId)
					.insertBefore(mainSelect);
					
			$('<div class="styleSelect_item"></div>')
				.appendTo(mainContainer)
				.css({'position' : 'absolute', 'z-index' : '' + parseInt(500 - styledTabIndex) + '', 'top' : opts.optionsTop, 'left' : opts.optionsLeft})
				.hide();
			
			$('<div class="styleSelect_item_start"></div><div class="styleSelect_item_content_wrapper"><div class="styleSelect_item_content"></div></div><div class="styleSelect_item_end">').appendTo($('#'+selectId + ' .styleSelect_item'));
			
			//Options container
			var subContainer = $('<ul></ul>').appendTo($('#'+selectId + ' .styleSelect_item_content'));
				
			//Generate options list
			var optionsList = "";
			
			mainSelect.find('option').each(function(){
			
				optionsList += '<li id="'+$(this).val()+'"';
				if($(this).attr('class')) optionsList += ' class="'+$(this).attr('class')+'" ';
				optionsList += '>';
				optionsList += '<span style="display: block;"';
				if ($(this).attr('selected')) optionsList += ' class="selected" ';
				optionsList += '>';
				optionsList += $(this).text();
				optionsList += '</span>';
				optionsList += '</li>';
				
			});

			subContainer.append(optionsList);
			
			checkSelected(opts.styleClass,opts.optionsWidth);
				
			//Show otions   
            $('#'+selectId).click(function(event){
                if($(".selectPrintleDisabled").length > 0)
                {
                    return;
                }
                $(".styleSelect_item").each(function(){
                    if($(this).parent().attr("id") != selectId)
                    {
                        $(this).slideUp(opts.speed);
                        $(this).parent().find("span.activeSelect").removeClass("opened");
                    }
                })

				var eitem = $(event.target);

                var el = $(this);
                $(this).find('.styleSelect_item').slideToggle(opts.speed, function(){
                    if(el.find('.styleSelect_item').is(":visible"))
                     {
                         el.find("span.activeSelect").toggleClass("opened");
                         $('.styleSelect_item_content').animate({scrollTop: el.find('li span.selected').offset().top - el.offset().top - 8},'slow');
                     }
                });
			});

			//On click
			$('#'+selectId+' li').click(function(){
                $('#'+selectId).find("span.activeSelect").removeClass("opened");
				doSelection($(this));
			});
			
			//Do selection
			var doSelection = function(item){

				item.siblings().find("span").removeClass('selected');
				item.find("span").addClass('selected');

				var selectedItem = item.attr('id');

				var realSelector = $('select[name="'+orgSelectbox+'"]');
				realSelector.siblings().selected = false;
				realSelector.find('option[value="'+selectedItem+'"]').attr('selected','selected');
				realSelector.trigger(opts.selectTrigger);
		
				checkSelected(opts.styleClass,opts.optionsWidth);
			}
			
			$('#'+selectId).click(function(event){
			
				event.stopPropagation();
			});
			
			$(document).click(function() {
			
				$('#'+selectId+' .styleSelect_item').slideUp(opts.speed);
                $('#'+selectId).find("span.activeSelect").removeClass("opened");
			});
		});
        return result;
	}
		
		//Selected items check
		function checkSelected(mainClass,mainWidth){
				
				$('.'+mainClass).each(function(){
				
					var elementList = $(this).find('.styleSelect_item');
					
					$(this).find('span').each(function(){
					
						var spanClass = $(this).attr("class");
						if (spanClass == "passiveSelect" || spanClass == "activeSelect") $(this).remove();
					
					});
					
					var selectedName = $(this).find('.selected');
					
					$('<span></span>').text(selectedName.text())
							.attr('id', selectedName.parent().attr('id'))
							.addClass('passiveSelect')
							.appendTo($(this));
					
					if (mainWidth === 0){
						$(this).css({'width' :  elementList.width()});
					}
					
				});
				
				$('.'+mainClass+' span').each(function(){
					if ($(this).attr('id')){
						$(this).removeClass();
						$(this).addClass('activeSelect');
					}
				});
		}	
	
		$.fn.styleSelect.defaults = {
		
			optionsTop: '0px',
			optionsLeft: '0px',
			optionsWidth: 0,
			styleClass: 'selectMenu',
			speed: 200,
			selectTrigger: 'change',
			jScrollPane: 0,
			jScrollPaneOptions: ''
		};
		
})(jQuery);

