/*jquery.selectStyle.js */
/*
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Copyright 2010 Christiano Erick =D
 */
(function ($) {
	$.fn.selectStyle = function(w) {
		return $(this).each(function(i) {
			$(this).wrap('<div style="position:relative" class="sel-style-select"></div>');
			$(this).parent().children().before('<div style="position: relative; z-index: 999" class="sel-style-texto"></div><ul style="display: none; position:absolute; z-index: 9999;" class="sel-style-lista"></ul>').each(function() {
				$(this).hide();
				$html = $texto = '';
				$(this).find('option').each(function(){
					$img = ($(this).attr('imagem'))?'<img src="'+$(this).attr('imagem')+'" alt="" />':'';
					$html += '<li style="cursor:pointer" value="'+$(this).attr('value')+'">'+$img +'<span>'+$(this).html()+'</span></li>';
					if($(this).attr('selected')){
						$texto = $img+'<span>'+$(this).html()+'</span>';
					}
				});
				$(this).prev().html($html).prev().html($texto).click(function(){
					if($(this).next().css('display') == 'none'){
						$(this).next().slideDown();
					}else{
						$(this).next().slideUp();
					}
				});
				$(this).prev().find('li').click(function(){
					$nv = $(this).attr('value');
					$(this).parent().next().find('option').each(function(){
						if($(this).attr('value') == $nv){
							if($(this).attr('url')){
								document.location.href = $(this).attr('url');
							}
							$img = ($(this).attr('imagem'))?'<img src="'+$(this).attr('imagem')+'" alt="" />':'';
							$(this).attr('selected', true).parent().prev().slideUp().prev().html($img+'<span>'+$(this).html()+'</span>');
						}else{
							$(this).attr('selected', false);
						}
					});
				}).hover(function(){
					$(this).addClass('hover');
				}, function(){
					$(this).removeClass('hover');
				});
				$(document).bind('click', function(e) {
					var $clicked = $(e.target);
					if (!$clicked.parents().hasClass("sel-style-select")) $(".sel-style-select ul").slideUp().prev();
				});
			});
		});
	}
}(jQuery));
