/**
 * ************************************************************
 * MODIFIED HEAVILY FROM ORIGINAL BY RICK FOR REUSE BY REACTIVE
 * ************************************************************
 * jQuery custom selectboxes
 * 
 * Copyright (c) 2008 Krzysztof SuszyÅ„ski (suszynski.org)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 0.6.1
 * @category visual
 * @package jquery
 * @subpakage ui.selectbox
 * @author Krzysztof SuszyÅ„ski <k.suszynski@wit.edu.pl>
**/
jQuery.fn.selectbox = function(options){
	/* Default settings */
	var settings = {
		className: 'customSelect',
		listboxMaxSize: '5',
		replaceInvisible: false,
		dropdownBehaviour: 'hover'
	};
	var commonClass = 'jquery-custom-selectboxes-replaced';
	var listOpen = false;
	var showList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.css('visibility', 'visible');
		listObj.css('overflow', 'auto');
		//listObj.show();
		listOpen = true;
		selectbox.addClass('selecthover');
		selectbox.find('.' + settings.className + '-moreButton').addClass('morebuttonhover');
		jQuery(document).bind('click', onBlurList);;
		return listObj;
	}
	var hideList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.css('visibility', 'hidden');
		listObj.css('overflow', 'hidden');
		//listObj.hide();
		listOpen = false;
		selectbox.removeClass('selecthover');
		selectbox.find('.' + settings.className + '-moreButton').removeClass('morebuttonhover');
		jQuery(document).unbind('click', onBlurList);
		return listObj;
	}
	var onBlurList = function(e) {
		var trgt = e.target;
		var currentListElements = jQuery('.' + settings.className + '-list:visible').parent().find('*').andSelf();
		if(jQuery.inArray(trgt, currentListElements)<0 && listOpen) {
			hideList( jQuery('.' + commonClass + '-list') );
		}
		return false;
	}
	
	/* Processing settings */
	settings = jQuery.extend(settings, options || {});
	/* Wrapping all passed elements */
	return this.each(function() {
		var _this = jQuery(this);
		var existingClassName = $(this).attr('class'); // get any existing className
		if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
			return;
		var replacement = jQuery(
			'<div class="' + existingClassName + ' ' + settings.className + ' ' + commonClass + '">' +
				'<div class="' + settings.className + '-moreButton" />' +
				'<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
				'<span class="' + settings.className + '-currentItem" />' +
			'</div>'
		);
		jQuery('option', _this).each(function(k,v){
			var v = jQuery(v);
			var listElement =  jQuery('<span class="' + settings.className + '-item value-'+v.val()+' item-'+k+'">' + v.text() + '</span>');	
			listElement.click(function(){
				var thisListElement = jQuery(this);
				var thisReplacment = thisListElement.parents('.'+settings.className);
				var thisIndex = thisListElement[0].className.split(' ');
				for( k1 in thisIndex ) {
					if(/^item-[0-9]+$/.test(thisIndex[k1])) {
						thisIndex = parseInt(thisIndex[k1].replace('item-',''), 10);
						break;
					}
				};
				var thisValue = thisListElement[0].className.split(' ');
				for( k1 in thisValue ) {
					if(thisValue[k1].indexOf('value-') != -1) {
						thisValue = thisValue[k1].replace('value-','');
						break;
					}
				};
				thisReplacment
					.find('.' + settings.className + '-currentItem')
					.text(thisListElement.text());
				if (thisReplacment.find('select').val() != thisValue) {
					thisReplacment
						.find('select')
						.val(thisValue)
						.triggerHandler('change');
				}
				var thisSublist = thisReplacment.find('.' + settings.className + '-list');
				if (settings.dropdownBehaviour.toLowerCase() == 'hover' || settings.dropdownBehaviour.toLowerCase() == 'normal') {
					if(thisSublist.filter(":visible").length > 0) {
						hideList( thisSublist );
					}else{
						showList( thisSublist );
					}
				}
			}).bind('mouseenter',function(){
				jQuery(this).addClass('listelementhover');
			}).bind('mouseleave',function(){
				jQuery(this).removeClass('listelementhover');
			});
			jQuery('.' + settings.className + '-list', replacement).append(listElement);
			if(v.filter(':selected').length > 0) {
				jQuery('.'+settings.className + '-currentItem', replacement).text(v.text());
			}
		});
		if (settings.dropdownBehaviour.toLowerCase() == 'hover' || settings.dropdownBehaviour.toLowerCase() == 'normal') {
			replacement.hover(
				function(){
					var otherLists = jQuery('.' + settings.className + '-list')
						.not(jQuery(this).find('.' + settings.className + '-list'));
					hideList( otherLists );
					var thisList = jQuery(this).find('.' + settings.className + '-list');
					showList( thisList );
				},
				function(){
					var thisMoreButton = jQuery(this);
					var otherLists = jQuery('.' + settings.className + '-list')
						.not(thisMoreButton.siblings('.' + settings.className + '-list'));
					hideList( otherLists );
					var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
					hideList( thisList );
				}
			);
		} else {
			replacement.click(
				function(){
					var otherLists = jQuery('.' + settings.className + '-list')
						.not(jQuery(this).find('.' + settings.className + '-list'));
					hideList( otherLists );
					var thisList = jQuery(this).find('.' + settings.className + '-list');
					if(thisList.filter(":visible").length > 0) {
						hideList( thisList );
					}else{
						showList( thisList );
					}
				}
			);
		}
		_this.hide().replaceWith(replacement).appendTo(replacement);
		var thisListBox = replacement.find('.' + settings.className + '-list');
		var thisCurrentItem = replacement.find('.' + settings.className + '-currentItem');
		var thisListBoxItems = thisListBox.find('.' + settings.className + '-item');
		var thisListBoxSize = thisListBoxItems.length;
		var thisListBoxWidth = 0;
		var thisCurrentItemWidth = 0;
		var thisScrollbarWidth = 0;
		var cssWidth = _this.css('width');
		if (cssWidth == null || cssWidth == 'auto' || cssWidth == '0px' || cssWidth.indexOf('px') == -1) {
			thisListBoxWidth = Math.round(_this.outerWidth());
			//if(jQuery.browser.safari) thisListBoxWidth = thisListBoxWidth * 0.94;
		} else {
			thisListBoxWidth = Math.round(cssWidth.replace('px', ''));
		}
		replacement.css('width', thisListBoxWidth + 'px');
		//Set to a minimum of 3 for the IE 6 float jog bug
		var thisCurrentItemPaddingRight = 3;
		if (thisCurrentItem.css('padding-right') != null && thisCurrentItem.css('padding-right').indexOf('px') != -1) {
			var paddingRight = Math.round(thisCurrentItem.css('padding-right').replace('px', ''));
			if (paddingRight > thisCurrentItemPaddingRight) thisCurrentItemPaddingRight = paddingRight;
		}
		thisCurrentItemWidth = (thisListBoxWidth - Math.round(replacement.find('.' + settings.className + '-moreButton').outerWidth())) - (thisCurrentItem.outerWidth() - thisCurrentItem.width()) - thisCurrentItemPaddingRight;
		thisCurrentItem.css('width', thisCurrentItemWidth + 'px');
		var thisListBoxHeight = 0;
		if (thisListBoxSize > settings.listboxMaxSize) {
			thisListBoxSize = settings.listboxMaxSize;
			thisScrollbarWidth = 20;
		}
		if(thisListBoxSize > 0) {
			thisListBoxHeight = (Math.round(thisListBox.height() / thisListBox.find('.' + settings.className + '-item').length) * thisListBoxSize);
		}
		if (thisListBox.outerWidth() + thisScrollbarWidth < thisListBoxWidth) {
			thisListBoxWidth = Math.round(thisListBoxWidth - (thisListBox.outerWidth() - thisListBox.innerWidth()));
		} else {
			thisListBoxWidth = 0;
			for (i = 0; i < thisListBoxItems.length; i++) {
				var thisItem = thisListBoxItems.get(i);
				if (thisListBoxWidth < thisItem.offsetWidth) {
					thisListBoxWidth = thisItem.offsetWidth;
				}
			}
			thisListBoxWidth += thisScrollbarWidth;
		}
		thisListBox.css({
			width: thisListBoxWidth + 'px',
			height: thisListBoxHeight + 'px',
			overflow: 'hidden'
		});
	});
}
jQuery.fn.unselectbox = function(){
	var commonClass = 'jquery-custom-selectboxes-replaced';
	return this.each(function() {
		var oriSelectBox = jQuery(this);
		var selectToRemove = $(oriSelectBox.parent().get(0));
		selectToRemove.replaceWith($(oriSelectBox));		
	});
}