/**
 * jQuery custom selectboxes
 * 
 * Copyright (c) 2008 Krzysztof Suszynski (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 Suszynski <k.suszynski@wit.edu.pl>
**/
/*
1. Сохраняем ссылку на объект красивого SELECT'а в эл-те (списке)
2. Если при повторном превращении ссылка уже есть, работаем с этим эл-том. И если reloadData == true, то перегружаем только контентную часть*/





jQuery.fn.selectbox = function(options){
	/* Default settings */
	var settings = {
		className: 'jquery-selectbox',
		animationSpeed: "fast",
		listboxMaxSize: 11,
		replaceInvisible: false ,
		reloadData: false  
	};
	var commonClass = 'jquery-custom-selectboxes-replaced';
	var listOpen = false;
	var showList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.slideDown(settings.animationSpeed, function(){
			listOpen = true;
		});
		selectbox.addClass('selecthover');
		jQuery(document).bind('click', onBlurList);
		return listObj;
	}
	var hideList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		/*listObj.slideUp(settings.animationSpeed, function(){
			listOpen = false;
			jQuery(this).parents('.' + settings.className + '').removeClass('selecthover');
		});
		*/
		listObj.hide( settings.animationSpeed, function(){
			listOpen = false;
			jQuery(this).parents('.' + settings.className + '').removeClass('selecthover');
			});
		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;
	}
	var loadList = function ( listObj , reloadSource ) {
		var _this = jQuery( listObj );
		listObj.selectedIndes = 0;
		//if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
		//	return;
		if( reloadSource && reloadSource.tagName == "SELECT" ) {
			_this.empty( );
			var selectedIndex = 0;
			for( var jj = 0 ; jj < reloadSource.options.length ; jj++ ) {
				if( reloadSource.options[jj].selected ) {
					selectedIndex = jj;
					break;
				}
			}
			
			jQuery('*', reloadSource).each(function(k,v) {
				var v_tmp = jQuery(v);
				_this.append(v_tmp);
			});
			
			listObj.selectedIndex = selectedIndex;
		}
		
		if( document.getElementById( listObj.getAttribute("id") + "_replacement" ) ){
			var replacement = jQuery( "#" + listObj.getAttribute("id") + "_replacement" );
			jQuery('.' + settings.className + '-list', replacement).empty();
			jQuery('.' + settings.className + '-currentItem', replacement).text( "--" );
			reloadData = true;
		}
		else {
			var replacement = jQuery(
				'<div id="' + listObj.getAttribute("id") + '_replacement" class="' + settings.className + ' ' + commonClass + '">' +
					'<div class="' + settings.className + '-moreButton" />' +
					'<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
					'<div class="' + settings.className + '-currentItem" />' +
				'</div>'
			);
			reloadData = false;
		}
				
		// изменено ChaosEremite
		// пробегаем по всем дочерним узлам объекта SELECT
		// при находждении группы OPTGROUP - прост осоздаем отдельный спан со значение его атрибута label
		// при нахождении узлов OPTION выполняем штатные операции по его преобразованию в спан и настройке
		jQuery('*', _this).each(function(k,v){
			var v = jQuery(v);
			if ( v.attr( 'tagName' ) == "OPTGROUP" ) {
				var listOptElement =  jQuery('<span class="' + settings.className + '-item_group value-'+v.val()+' item-'+k+'">' + v.attr('label') + '</span>');	
				jQuery('.' + settings.className + '-list', replacement).append(listOptElement);
			} 
			else if( v.attr( 'tagName' ) == "OPTION" ) {
				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(/^value-.+$/.test(thisValue[k1])) {
							thisValue = thisValue[k1].replace('value-','');
							break;
						}
					};
					thisReplacment
						.find('.' + settings.className + '-currentItem')
						.text(thisListElement.text());
					thisReplacment
						.find('select')
						.val(thisValue)
						.triggerHandler('change');
					var thisSublist = thisReplacment.find('.' + settings.className + '-list');
					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 ( reloadData != true ) {
			// изменено ChaosEremite
			// при нажатие на текущий элемент, тоже раскрываем список
			replacement.find( '.' + settings.className + '-currentItem' ).click(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');
				if(thisList.filter(":visible").length > 0) {
					hideList( thisList );
				}else{
					showList( thisList );
				}
			});
			// конец изменений
			
			replacement.find('.' + settings.className + '-moreButton').click(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');
				if(thisList.filter(":visible").length > 0) {
					hideList( thisList );
				}else{
					showList( thisList );
				}
			}).bind('mouseenter',function(){
				jQuery(this).addClass('morebuttonhover');
			}).bind('mouseleave',function(){
				jQuery(this).removeClass('morebuttonhover');
			});
			_this.hide().replaceWith(replacement).appendTo(replacement);
		}
		
		var thisListBox = replacement.find('.' + settings.className + '-list');
		var thisListBoxSize = thisListBox.find('.' + settings.className + '-item').length;
		var thisListBoxSizeGroups = thisListBox.find('.' + settings.className + '-item_group').length;
		thisListBoxSize += thisListBoxSizeGroups;
		thisListBoxSize = thisListBoxSize > settings.listboxMaxSize ? settings.listboxMaxSize : thisListBoxSize;		

		if(thisListBoxSize == 0)
			thisListBoxSize = 1;
		
		/*доработано ChaosEremite*/
		var divWidthError = 5;
		if ( jQuery.browser.mozilla ) 
			divWidthError = 5;
		else if ( jQuery.browser.msie )
			divWidthError = 0;
		else if ( jQuery.browser.opera )
			divWidthError = 6;
		if( reloadData != true ) {
			var thisListBoxWidth = Math.round(_this.width() + 4);
			if(jQuery.browser.safari)
				thisListBoxWidth = thisListBoxWidth * 0.94;
			replacement.css('width', thisListBoxWidth + 'px');
			thisListBox.css({
				width: Math.round(thisListBoxWidth-divWidthError) + 'px',
				height: thisListBoxSize*18 + 'px'
			});
		}
		else {
			thisListBox.css( 'height' , thisListBoxSize*18 + 'px' );
		}
	}
	/* Processing settings */
	settings = jQuery.extend(settings, options || {});
	/* Wrapping all passed elements */
	
	return this.each(function() { loadList(this , settings.reloadSource ); });
}

jQuery.fn.unselectbox = function(){
	var commonClass = 'jquery-custom-selectboxes-replaced';
	return this.each(function() {
		var selectToRemove = jQuery(this).filter('.' + commonClass);
		selectToRemove.replaceWith(selectToRemove.find('select').show());		
	});
}

jQuery.fn.changebox = function(options){
	var settings = {
		className: 'jquery-selectbox',
		newIndex: 0
	};
	var commonClass = 'jquery-custom-selectboxes-replaced';
	settings = jQuery.extend(settings, options || {});
	return this.each(function() {
		var _this = jQuery(this);
		var replacement = jQuery( '#' + _this.attr( "id" ) + "_replacement" );
		jQuery('option', _this).each(function(k,v){
			var v_tmp = jQuery(v);
			if( v.value == settings.newIndex ) {
				v.selected = true;
				_this.selectedIndex = k;
				replacement.find('.' + settings.className + '-currentItem').text( v_tmp.text() );
			}
			else{
				v.selected = false;
			}
		});

	});
}
