/*!
 * Copyright (c) 2009 Łukasz Wełniak Omnigence Sp. z o.o.
 *
 * Date: 2009-07-24
 * Version 0.1
 *
 * script for input select (single select) replacement
 *
 */
(function($){

	$.fn.selectReplace = function(){
		var _elements = $("select");
		_elements.each(function(){
			//console.debug(offset.top);
			if (!$(this).hasClass("no-replace")) _replaceSelect(this);
		});
		_activateOptionBoxes();

		/***
		 * replace select with newSelect
		 **/

		function _replaceSelect(e) {
			var selName = $(e).attr("name");
			var _inSelectOptions = $(e).find("option");
			var activeOptionHtml = $(e).find("option:selected").html();
			var newSelect = '<dl class="replaced-select replaced-select-'+selName+'"><dt class="replaced-select-selected-option">'+activeOptionHtml+'</dt><dd><ul>';
			var newSelName = $(e).attr("name");

			_inSelectOptions.each(function(){
				var selValue = $(this).attr("value");
				var selTxt = $(this).html();
				newSelect+= '<li><input type="radio" name="'+newSelName+'" value="'+selValue+'" id="'+selName+'_'+selValue+'" /><label for="'+selName+'_'+selValue+'">'+selTxt+'</label></li>';
			});
			newSelect+= '</ul></dd></dl>';
			//var offset = $(this).offset();
			$(e).wrap(newSelect).remove();
		}

		/***
		 * activate hide/show for option lists
		 **/

		function _activateOptionBoxes() {
			$(".replaced-select dt").click(function(event){
				var thisId = $(this).next("dd").attr("id");
				if(thisId == 'hide') {
					_hideActiveOptionBoxes();
				}
				else {
					_hideActiveOptionBoxes();
					_showOptionBox($(this).next("dd"));
				}
				event.stopPropagation();
			});
			$(".replaced-select dd ul li").click(function(event){

				var thisHtml = $(this).find("label").html();
				$(this).parent().find("li.active").removeClass("active");
				$(this).addClass("active");
				$(this).find("input").attr("selected", true);
				$(this).parent().parent().parent().find(".replaced-select-selected-option").html(thisHtml);
			});
			$(document).click(function(){ _hideActiveOptionBoxes(); });
		}

		/***
		 * hide displayed option lists when activating other newSelect
		 **/

		function _hideActiveOptionBoxes() {
			$(".replaced-select dd[id=hide]").hide().attr("id","");
			$(".special-select dd[id=hide]").hide().attr("id","");
		}

		/***
		 * show option list for clicked newSelect
		 **/

		function _showOptionBox(e) {
			$(e).slideDown(400).attr("id", "hide");
		}


	}

})(jQuery)

