//por ricardo tomasi (originalmente, depois só deus sabe)
//ricardobeat@gmail.com

//$(document).ready(function(){

	$('head').append('<style id="hidebusca" type="text/css">#sidebar .busca select, #sidebar .busca input { display: none }</style>');
	$.fn.replaceInput = function(options){

		var opt = { multi:11, textAll:'Selecionar todos', textNone:'Remover todos',textOk:'OK' }
		var opt = jQuery.extend(opt,options);
		var form = this.parents('form');

		function checkComplete(el){
			var c = 0;
			$.fn.replaceInput.store.each(function(){
				if ($(this).find('li.ativo').length) c++;
			});
			//FIXME:COMENTEI A LINHA ABAIXO NAO SEI SE INTEFERE NO BUSCA
			//if (c == $.fn.replaceInput.store.length) form.submit();
		};//checkComplete



		return this.each(function(i){

			var $this = $(this);
			var id = $this.attr('id');
			var $select = $this.attr('id','old_'+id).after('<div id='+id+' class="replaceSelect">').hide();
			var $newthis = $(document.getElementById(id));
			//this.$newthis = $newthis;
			$newthis.textopadrao = $select.children(':first').text();
			$newthis.css('z-index',500-(i*5));

					if ($this.is('[multiple]')) {
						$newthis.append('<div class="rS_item multi">');
				var selecionados = $select.children('option[selected]');//$select.children('option:gt(0)[selected]');
				if (selecionados.length) {
					var texto = '';

					selecionados.each(function(i){

						texto += $(this).text() + (i == selecionados.length-1 ? '' : ', ');

						if (texto.length > 20) texto = texto.substring(0,20)+'...';


					});

					$newthis.prepend('<span>'+texto+'</span>');

				} else {

					$newthis.prepend('<span>'+$newthis.textopadrao+'</span>');

				}

				var $title = $newthis.children('span');


				$newthis

					.children('span,.show').click(function(){

						$newthis.children('div.multi').slideToggle();

					}).end()

					.children('.rS_item').bind('mouseleave',function(){ //verifica itens ativos e adiciona a lista

						var $thiz = $(this);

						$(this).data('mousesaindo', setTimeout(function(){

							//var $ativos = $thiz.slideUp().find('li.ativo');
							var $ativos = $thiz.slideUp().find('li');

							if ($ativos.length) {

								$title.text(function(){

									var a = [];



									$ativos.each(function(){
										if ($(this).hasClass('ativo')) {
											$select.find('option[value='+$(this).attr('rel')+']').attr('selected','selected');
											a.push( $(this).text() );
										}
										else
										{
											$select.find('option[value='+$(this).attr('rel')+']').removeAttr('selected');
										}

									});

									/*if ($show.length) {

										$show.children('li').each(function(i){

											($ativos.length > $show.children('li').length+1 && i == $show.children('li').length-1) ? $(this).text(a[i+1]+' (+) ') : $(this).text(a[i+1]);

										});

										return a[0];

									} else {*/

										a = a.join(', ');

										if (a.length > 20) a = a.substring(0,20)+'...';
										if (a.length == 0)
											a = $newthis.textopadrao;

													return a;

									//}

								}());

							} else { $title.text($newthis.textopadrao); /*$show.children('li').text('');*/ };

							checkComplete();

							$newthis.add($this).trigger('change');

						},500));

					}).bind('mouseenter', function(){

						clearInterval( $(this).data('mousesaindo') );

					}).hide();



				$select.children('option:gt(0)').each(function(index){
					var ativo = this.selected ? ' class="ativo"' : '';

					var newItem = '<li rel="'+$(this).val() +'" index="'+index+'" '+ativo+'>'+this.innerHTML+'</li>';

					if (index == 0 || !((index) % opt.multi)) {

						$newthis.children('div')

							.append('<ul>').children('ul:last')

							.append(newItem);

					} else {

						$newthis.find('div ul:last')

							.append(newItem);

					}

				});

				$newthis.find('li')


					.mousedown(function()
					{  //Se tem class ativo é pq foi selecionado
					//$(this).toggleClass('ativo');
					if ($(this).hasClass('ativo'))
					{
						$(this).removeClass('ativo');
					}
					else
					{
						$(this).addClass('ativo');
					}

					//alert("HAS CLASS:" + $(this).hasClass('ativo'));
					//Carlos Kuhn incluiu pq não tá desselecionando
					if (!$(this).hasClass('ativo'))
					{
						//$(this).removeClass('ativo');
						//alert ("ID:" + $(this).attr('id') + " sel: "+ $(this).attr('selected'));

					}
					$newthis.data('lastclicked',$(this).hasClass('ativo') ? this : '');
					})

				//Carlos kuhn documenta:
				//Dispara quando usuário digita algo, se for enter(cód 16) e tiver alguém que seja "lastclicked",
				// marca como "ativo"
				//o elemento onde
				function multiSelect(e){

					if (e.keyCode == 16 && $newthis.data('lastclicked')) {
						var $lis = $newthis.find('li');
						var $holder = $newthis.children('div');
						var start = $lis.index( $newthis.data('lastclicked') );

						$holder.one('click',function(e){

							var end = $lis.index( (e.target||e.srcElement) );

							if (end < start) { var st=start; start=end; end=st };

							$lis.filter(':lt('+end+'):gt('+start+')').addClass('ativo');

							$newthis.data('lastclicked','');

						});

					}//if e.keycode

				};//function multiselect

				$().keydown(multiSelect);

				//if ($newthis.find('ul').length > 1) {

				$('<span class="selControls"></span>').appendTo($newthis.children('div'))

					.append('<span class="selControl selectAll">'+opt.textAll+'</span>')

					.append('<span class="selControl selectNone">'+opt.textNone+'</span>')

					.append('<span class="selControl selectOk">'+opt.textOk+'</span>')

					.children('span.selectAll').click(function(){ $newthis.find('li').addClass('ativo') })

					.next('span.selectNone').click(function() { $newthis.find('li').removeClass('ativo') })

					.next('span.selectOk').click(function(){ $newthis.children('div.rS_item').slideUp('100') });

			}
				else//Se nao for Select Multiple
				{

				var selecionado = $select.children('option[selected]');
					var selecionadoTXT = (selecionado.length ? selecionado.text() : $select.children(':first').text());
					//Corta tamanho se for máximo e mínimo
					if ($select.attr('id')== 'old_busca_maximo' ||
						$select.attr('id')== 'old_busca_minimo')
					{
						if (selecionadoTXT.length > 10)
								{
									selecionadoTXT = selecionadoTXT.substring(0,8)+'..';
								}


					}
					//alert("SELECIONADO:"+ selecionado);
				$newthis

					.append('<span>'+selecionadoTXT+'</span>')

					.append('<ul class="rS_item">')

					.children('span').click(function(){

						$('div.replaceSelect .rS_item:visible').slideUp(100);

						$(this).next('ul:not(:visible)').slideDown('fast');

					});

					function fechar(){

						var $thiz = $(this).slideUp();

						var $ativo = $thiz.find('li.ativo');

						var $title = $thiz.prev('span');

						if ($ativo.length)

							($title.width() > 90)

								? $title.text( $ativo.text() )

								: $title.text( $ativo.text().substring(0,8)+'..' );

						$select.val( $ativo.attr('rel') );

						checkComplete();

						$newthis.add($this).trigger('change');

					};

				$select.children('option:gt(0)').each(function(){

					var ativo = this.selected ? ' class="ativo"' : '';
					$newthis.children('ul').append('<li rel="'+$(this).val()+'" '+ativo+'>'+this.innerHTML+'</li>').hide();

				});

				$newthis.find('li')

					.mousedown(function(){

						$(this).addClass('ativo').siblings('li').removeClass('ativo').parent().each(fechar);

					}).add('span.selControl')

						.hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')});

			};



			//adicionar ao conjunto

			$.fn.replaceInput.store = ($.fn.replaceInput.store)

				? $.fn.replaceInput.store.add( $newthis.find('.rS_item') )

				: $newthis.find('.rS_item');



		});



	};



$(document).ready(function(){



	/* mapas */

	$('#topo .poa .mapa').append('<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" class="http://maps.google.com.br/maps?f=q&amp;hl=pt-BR&amp;geocode=&amp;q=Rua+Dona+Mimi+Moro,+45+porto+alegre+brazil&amp;sll=51.495137,-0.242449&amp;sspn=0.009819,0.019312&amp;ie=UTF8&amp;g=Rua+Dona+Mimi+Moro,+45+porto+alegre+brazil&amp;s=AARTsJrXEk_YbgGZ5JKNc2vpUthO_MThLA&amp;ll=-30.013146,-51.173372&amp;spn=0.026013,0.036478&amp;z=14&amp;iwloc=addr&amp;output=embed"></iframe>');
	$('#topo .poasul .mapa').append('<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" class="http://maps.google.com.br/maps?f=q&amp;source=s_q&amp;hl=pt-BR&amp;geocode=&amp;q=Av+Wenceslau+Escobar,+3205+-+Porto+Alegre+RS&amp;sll=-27.672583,-48.442497&amp;sspn=0.169053,0.363579&amp;ie=UTF8&amp;hq=&amp;hnear=Av.+Wenceslau+Escobar,+3205+-+Vila+Concei%C3%A7%C3%A3o,+Porto+Alegre+-+Rio+Grande+do+Sul,+91900-000&amp;ll=-30.113503,-51.247959&amp;spn=0.041284,0.090895&amp;z=14&amp;iwloc=A&amp;output=embed"></iframe>');	
	$('#topo .floripa .mapa').append('<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" class="http://maps.google.com.br/maps?f=q&amp;hl=pt-BR&amp;geocode=&amp;q=Florian%C3%B3polis:%7C+Av.+Campeche,+2935&amp;sll=-30.022186,-51.177616&amp;sspn=0.006828,0.009656&amp;g=Rua+Dona+Mimi+Moro,+45+porto+alegre+brazil&amp;ie=UTF8&amp;ll=-27.667566,-48.480177&amp;spn=0.013967,0.019312&amp;z=14&amp;output=embed&amp;s=AARTsJr_AoW3Yh6Y3sk1ty0a_8T2OlFikQ"></iframe>');
	$('#topo a.local').click(function(e){
		var $iframe = $(this).next('.mapa').children('iframe');
			$iframe.attr('src',$iframe.attr('class'))
				.load(function(){
					$(this).parent('.mapa').slideToggle('normal');
				})
		e.preventDefault;
		return false;
	});



	/* hover IE6, bordas IE*/

	if ($.browser.msie) {
		$('form.busca li,div.box, .info .item').hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')});
	}

	/* tooltips ajuda */
	$('a.ajuda').hover(
		function(){ $(this).next('.textoajuda').fadeIn() },
		function(){ $(this).next('.textoajuda').fadeOut() }
	).click(function(){return false}).attr('title','');



	/* fechar drop-downs quando clicar fora */
	var mapas = $('.mapa');
	$(document).click(function(e){
		if (!$(e.target).parents('.busca').length) $('div.replaceSelect .rS_item:visible,div.replaceSelect .rS_item:animated').slideUp(150);
		if (mapas.filter(':visible,:animated').length) {
			mapas.slideUp();
		}
	});



	//evitar selecao de texto no menu
	if ($.browser.msie) { $('.busca div, .info').bind('selectstart',function(){return false});}
	else { $('.busca div, .info').css('MozUserSelect','none'); };

	$('#sidebar div.item').each(function(){
		var sub = $('> div.submenu', this); //salvar o submenu pra nao ter que procurar a cada hover
		$(this).hover(
			function(){ sub.show();	},
			function(){	sub.hide();	}
		);
	});



	/* desativar botao direito em imagens */
	setTimeout("$('img').bind('contextmenu',function(){return false})",300);

	/* rotacao rodape */
	var $sort = $('.rotacao > div:not(#cadastronews,.trabalheconosco)'), n = $sort.length-1;
	if (n > 0)
	{
		var rnd = rnd2 = Math.ceil(Math.random()*n);
		//while (rnd2 == rnd) rnd2 = Math.ceil(Math.random()*n);
		//$sort.eq(rnd).prependTo($sort.parent()).fadeIn(1500);
		$sort.eq(rnd).fadeIn(1500);
	}


});

