/** Author: Draco Chan < draco.chan@butterflyinternet.com.au / im@dracochan.com >
 * Used to replace select tag for stylling
 * Version: 1.0
 * Known issue: z-index might not be high enough
 * Notes: make sure the element id is unique
 * Requirement: jQuery 1.4.2 +
 * Useage:
jQuery('select').each( function() {
	selectReplacement(jQuery(this));
});
 **/

/* Parameter
 * jElement: jQuery object of select element */
var selectID = 0; /*global ID for bind event to the document*/
function selectReplacement(jElement){
	var thisSelectID = selectID++;
	jElement.css('display', 'none');
	var div = document.createElement('div');
	div.className = 'selectReplacement '+jElement.attr('class');
	div.innerHTML = '<span></span><ul style="display:none;list-style:none;">'+jElement.html().replace(/<option/gi, '<li').replace(/option>/gi, 'li>')+'</ul>';
	if(jElement.attr('id')){
		var newID =  jElement.attr('id')+'-replacement';
		if(jQuery('#'+newID).length!=0)
			jQuery('#'+newID).remove();
		div.id = newID;
	}
	jElement.after(div);
	var jDIV = jQuery(div);
	var jUL = jDIV.children('ul');
	jUL.css('position', 'relative');
	jUL.css('overflow', 'auto');
	jUL.css('max-height', '180px');
	jUL.css('z-index', '99999');
	jDIV.css('cursor', 'pointer');
	jUL.children('li').css('cursor', 'pointer');
	var selected = jUL.children('li[selected="selected"]'); /*reference to previous selection*/
	var text = jDIV.children('span:first'); /*display selected item*/
	var firstValue = jUL.children(':first');
	if(selected.length==0){
		text.html(firstValue.html());
		selected = null;
	} else {
		text.html(selected.html())
	}
	text.addClass('first');
	firstValue.addClass('first');
	jUL.children().each(function (index){
		var jLI = jQuery(this);
		jLI.click( function(e){
			e.stopPropagation();
			if(selected)
				selected.removeClass('selected');
			jQuery(this).addClass('selected');
			selected = jQuery(this);
			text.html(jQuery(this).html());
			jElement.val(index);
			if(index==0) /*might be useful*/
				text.addClass('first');
			else
				text.removeClass('first');
			jQuery(jElement.children('option').get(index)).attr('selected', 'selected');
			jElement.trigger('change');
			shown = false;
			jUL.slideUp(200);
		});
		/*jLI.hover(
			function(){ jLI.addClass('hover'); }
			, function(){ jLI.removeClass('hover'); }
		);*/
	});
	var shown = false;
	function hide(){
		shown = false;
		jUL.slideUp(200);
		jQuery(document).unbind('click.fakeS.'+thisSelectID);
	}
	jDIV.click( function(){ 
		if(shown) {
			hide();
		} else {
			jUL.slideDown(200);
			jQuery(document).bind('click.fakeS.'+thisSelectID, function(e){
				if(shown && jQuery(e.target)[0]!=jDIV[0] && jQuery(e.target)[0]!=jDIV.children('span:first')[0])
					hide();
			});
			shown = true;
		}
	});
}

