﻿//use : SelectSorter.sort ( select );
//notes : if you include prototype.js (http://prototype.conio.net) then you can pass in the id of the select, or the select object

SelectSorter = {
	sort : function ( s ) {
	        var select = ( $ ) ? $(s) : s;
	        if ( !s ) return;
	    var duplicateOption = function ( option ) {
		    var newOption = new Option ( option.text, option.value);
		    newOption.selected = option.selected;
		    return newOption;
        	}
		var copyOptions = function ( fromOptions, toOptions ) {
			toOptions.length = 0;
			for ( var i = fromOptions.length - 1; i >= 0; -- i ) {
				toOptions[toOptions.length] = duplicateOption(fromOptions[i]) ;
			}
			return toOptions;
		};
		var compareOptions = function ( a, b ) 
		{ 
			if ( !a || !b ) return 0; if ( !a.text || !b.text || !a.text.toLowerCase || !b.text.toLowerCase ) return 0;
			var x = a.text.toLowerCase(), y = b.text.toLowerCase();
			try { if ( x == y )return  0 ; if ( x > y ) return -1 ; return 1; } catch (e) { }
			return 0;
		};

		sortedOptions = copyOptions ( select.options, new Array() ); 
		sortedOptions.sort ( compareOptions ); 
		copyOptions ( sortedOptions, select.options );
       }
}
