$.fn.SelectCustomizer = function(){
    // Select Customizer jQuery plug-in
    // based on customselect by Ace Web Design http://www.adelaidewebdesigns.com/2008/08/01/adelaide-web-designs-releases-customselect-with-icons/
    // modified by David Vian http://www.ildavid.com/dblog
    // modified by Janet Khuu @ nijn.nu
    var fadeRate = 0;
    var ij = 0;
    return this.each(function()
    {
        var obj = $(this);
		var tabindex = '';
		if(obj.attr('tabindex')!='')
			tabindex = 'tabindex="'+obj.attr('tabindex')+'"';
        var pos = $(this).offset();
        var name = obj.attr('id');
        var id_slc_options = '';
        var id_icn_select = '';
        var id_holder = '';
        var custom_select = '';
        if (name != "") {
            id_slc_options = name+'_options';
            id_icn_select = name+'_iconselect';
            id_holder = name+'_holder';
            custom_select = name+'_customselect';
        }
        else {
            ij++;
            id_slc_options = 'options_'+ij;
            id_icn_select = 'iconselect_'+ij;
            id_holder = 'holder_'+ij;
            custom_select = 'customselect_'+ij;
        }
		var selected_val;
        var selected_html;
        // wrapper for the list of options
        obj.after('<ul id="'+id_slc_options+'" class="optionswrapper"></ul>');
        // duplicate the option items
        obj.find('option').each(function(i) {
            $("#"+id_slc_options).append('<li title="' + $(this).val() + '" class="selectitems">' + $(this).html() + '</li>');
              // find if there is a pre-selected option

              if ($(this).attr('selected')) {
              selected_val = $(this).val();
              selected_html = $(this).html();
              $("#"+id_slc_options + ' li:last').addClass('selectedclass');
            }

         });
		  // if no option is selected, default to the first item
        if (selected_val == undefined) {
            selected_val = obj.find('option:first').val();
            selected_html = obj.find('option:first').html();
        }
        // create the overall HTML structure to replace with
        obj.before('<input type="hidden" value="'+ selected_val +'" name="'+ obj.attr('name') +'" id="'+custom_select+'" class="customselect"/><div id="'+id_icn_select+'" class="selectbox"><a href="javascript:;" '+tabindex+'>' + this.title + '</a></div><div id="'+id_holder+'" class="selectwrapper"> </div>');
        // remove the select tag
        obj.remove();
		$('#'+id_icn_select).html('<a href="javascript:;" '+tabindex+'>'+selected_html+'</a>');
        $("#"+id_icn_select).click(function(a)
        {
          
            if($('#'+id_holder).css('display') == 'none')
            {
				// close opened select boxes
               $('.selectbox ~ .selectwrapper').fadeOut(fadeRate);
                $('body').unbind('click');

                $("#"+id_holder).fadeIn(fadeRate);
				$("#"+id_holder).unbind('click');
                a.stopPropagation();

                // close opened select boxes
                $('body').click(function(){
                    $("#"+id_holder).fadeOut(fadeRate);
                    $('body').unbind('click');
                });
            }
            else {
                // close opened select boxes
                $('body').click(function(){
                    $("#"+id_holder).fadeOut(fadeRate);
                    $('body').unbind('click');
                });
            }
			$("#"+id_icn_select+" a").focus();
        });
		$("#"+id_icn_select).keydown( function(e) {
			var multiSelectOptions = $(this).next('.selectwrapper');
			var ulOptions = multiSelectOptions.find('UL');
			if( multiSelectOptions.css('display') != 'none' ) {
				// Dropdown is visible
				// Tab
				if( e.keyCode == 9 ) {
					$(this).addClass('focus').trigger('click'); // esc, left, right - hide
					multiSelectOptions.find('LI').removeClass("hoverclass")
//					$(this).focus().next(':input').focus();
					multiSelectOptions.next(':input').focus();
					return true;
				}
				// ESC, Left, Right
				if( e.keyCode == 27 || e.keyCode == 37 || e.keyCode == 39 ) {
					// Hide dropdown
					multiSelectOptions.find('LI').removeClass("hoverclass")
					$(this).addClass('focus').trigger('click');

				}
				// Down || Up
				if( e.keyCode == 40 || e.keyCode == 38) {
					var allOptions = multiSelectOptions.find('LI');
					var oldHoverIndex = allOptions.index(allOptions.filter('.hoverclass'));
					var newHoverIndex = -1;
					
					// if there is no current highlighted item then highlight the first item
					if(oldHoverIndex < 0) {
						// Default to first item
						multiSelectOptions.find('LI:first').addClass('hoverclass');
					}
					// else if we are moving down and there is a next item then move
					else if(e.keyCode == 40 && oldHoverIndex < allOptions.length - 1)
					{
						newHoverIndex = oldHoverIndex + 1;
					}
					// else if we are moving up and there is a prev item then move
					else if(e.keyCode == 38 && oldHoverIndex > 0)
					{
						newHoverIndex = oldHoverIndex - 1;
					}

					if(newHoverIndex >= 0) {
						$(allOptions.get(oldHoverIndex)).removeClass('hoverclass'); // remove the current highlight
						$(allOptions.get(newHoverIndex)).addClass('hoverclass'); // add the new highlight
						
						// Adjust the viewport if necessary
						adjustViewPort(ulOptions);
					}
					
					return false;
				}
				// Enter, Space
				if( e.keyCode == 13 || e.keyCode == 32 ) {					
					var allOptions = multiSelectOptions.find('LI').removeClass("selectedclass").filter('.hoverclass');
					if(allOptions.length>0){
						allOptions.addClass("selectedclass");
						$("#"+custom_select).val(allOptions.attr('title'));
						$("#"+id_icn_select).html('<a href="javascript:;" '+tabindex+'>'+allOptions.html()+'</a>');
						$("#"+id_icn_select+" a").focus()
						try
						{
							//document.getElementById('SelectId').value = $(this).attr('title') + "_" + obj.attr('title');  // Added for the Sign-up page
							genericSelect(allOptions.html(), obj.attr('title'));  // Added for the Select option to get the selected value.
						}
						catch(e)
						{}
					}
					return false;
				}
				// Any other standard keyboard character (try and match the first character of an option)
				if( e.keyCode >= 33 && e.keyCode <= 126 ) {
					// find the next matching item after the current hovered item
					var match = multiSelectOptions.find('LI:startsWith(' + String.fromCharCode(e.keyCode) + ')');
					var allOptions = multiSelectOptions.find('LI').removeClass("selectedclass").filter('.hoverclass');
					var currentHoverIndex = match.index(match.filter('LI.hoverclass'));
					
					// filter the set to any items after the current hovered item
					var afterHoverMatch = match.filter(function (index) {
						return index > currentHoverIndex;
					});

					// if there were no item after the current hovered item then try using the full search results (filtered to the first one)
					match = (afterHoverMatch.length >= 1 ? afterHoverMatch : match).filter("LI:first");

					if(match.length == 1) {
						// if we found a match then move the hover
						multiSelectOptions.find('LI.hoverclass').removeClass('hoverclass');								
						match.addClass('hoverclass');
						adjustViewPort(ulOptions);
						genericSelect(allOptions.html(), match.attr('title'));  // Added for the Select option to get the selected value.
					}
				}
			}else{
				// Dropdown is not visible
				if( e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 13 || e.keyCode == 32 ) { //up, down, enter, space - show
					// Show dropdown
					$(this).removeClass('focus').trigger('click');
					multiSelectOptions.find('LI:first').addClass('hoverclass');
					return false;
				}
				//  Tab key
				if( e.keyCode == 9 ) {
					// Shift focus to next INPUT element on page
					multiSelectOptions.next(':input').focus();
					return true;
				}
				// Any other standard keyboard character (try and match the first character of an option)
				if( e.keyCode >= 33 && e.keyCode <= 126 ) {
					$(this).removeClass('focus').trigger('click');
					multiSelectOptions.find('LI:first').addClass('hoverclass');
					var allOptions = multiSelectOptions.find('LI').removeClass("selectedclass").filter('.hoverclass');
					// find the next matching item after the current hovered item
					var match = multiSelectOptions.find('LI:startsWith(' + String.fromCharCode(e.keyCode) + ')');
					
					var currentHoverIndex = match.index(match.filter('LI.hoverclass'));
					
					// filter the set to any items after the current hovered item
					var afterHoverMatch = match.filter(function (index) {
						return index > currentHoverIndex;
					});

					// if there were no item after the current hovered item then try using the full search results (filtered to the first one)
					match = (afterHoverMatch.length >= 1 ? afterHoverMatch : match).filter("LI:first");

					if(match.length == 1) {
						// if we found a match then move the hover
						multiSelectOptions.find('LI.hoverclass').removeClass('hoverclass');								
						match.addClass('hoverclass');
						adjustViewPort(ulOptions);
						genericSelect(allOptions.html(), match.attr('title'));  // Added for the Select option to get the selected value.
					}
				}
				
			}
		})	
		if(!obj.hasClass('no-offset'))
			$('#'+id_holder).css({
				'width': parseFloat($('#'+id_icn_select).css('width'))+parseFloat($('#'+id_icn_select).css('padding-left'))+parseFloat($('#'+id_icn_select).css('padding-right'))-2,
				'left': pos.left + 'px'
			});
		else
			$('#'+id_holder).css({
				'width': parseFloat($('#'+id_icn_select).css('width'))+parseFloat($('#'+id_icn_select).css('padding-left'))+parseFloat($('#'+id_icn_select).css('padding-right'))-2
			});
        $("#"+id_holder).append($("#"+id_slc_options)[0]);
        $("#"+id_holder+ " .selectitems").mouseover(function(){
            $(this).addClass("hoverclass");
        });
        $("#"+id_holder+" .selectitems").mouseout(function(){
            $(this).removeClass("hoverclass");
        });
        $("#"+id_holder+" .selectitems").click(function(){
            try
			{
				//document.getElementById('SelectId').value = $(this).attr('title') + "_" + obj.attr('title');  // Added for the Sign-up page
				genericSelect($(this).attr('title'), obj.attr('title'));  // Added for the Select option to get the selected value.
			}
			catch(e)
			{}
            $("#"+id_holder+" .selectedclass").removeClass("selectedclass").removeClass("hoverclass");
            $(this).addClass("selectedclass");
            var thisselection = $(this).html();
            $("#"+custom_select).val($(this).attr('title'));
            $("#"+id_icn_select).html('<a href="javascript:;" '+tabindex+'>'+thisselection+'</a>');
			$("#"+id_icn_select+" a").focus()
            $("#"+id_holder).slideToggle(fadeRate);
            $("#"+id_holder).fadeOut(fadeRate);
            $('body').unbind('click');
        });
    });
	// Adjust the viewport if necessary
	function adjustViewPort(multiSelectOptions)
	{
		// check for and move down
		var selectionBottom = multiSelectOptions.find('LI.hoverclass').position().top + multiSelectOptions.find('LI.hoverclass').outerHeight();
		
		if(selectionBottom > multiSelectOptions.innerHeight()){		
			multiSelectOptions.scrollTop(multiSelectOptions.scrollTop() + selectionBottom - multiSelectOptions.innerHeight());
		}
		
		// check for and move up						
		if(multiSelectOptions.find('LI.hoverclass').position().top < 0){		
			multiSelectOptions.scrollTop(multiSelectOptions.scrollTop() + multiSelectOptions.find('LI.hoverclass').position().top);
		}
	}
	
	
}
if(jQuery) (function($){
	$.expr[":"].startsWith = function(el, i, m) {
		var search = m[3];        
		if (!search) return false;
		return eval("/^[/s]*" + search + "/i").test($(el).text());
	};
})(jQuery);
$(document).click( function(event) {
	$('.selectwrapper').css('display','none');
});
