$.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
	// and then modified AGAIN be Dean Collins http://www.dblog.com.au
	// 3rd Sept 09 - R.L. Modified for Optus Business.

    return this.each(function(){
    var obj = $(this);
	var name = obj.attr('id');
	var id_slc_options = name + '_options';
	var id_icn_select = name + '_iconselect';
	var id_holder = name + '_holder';
	var custom_select = name + '_customselect';
	var selectItemElement = name + '_options_item_';
	var selectItemElementValue = name + '_options_item_value_';
	var selectItemElementText = name + '_options_item_text_';
	var selectItemCounter = 0;
		
	obj.after("<input type=\"hidden\" id=\"selectBoxCurrentlyOpen\" class=\"notdisplayed\" />");	
        obj.after("<div id=\""+id_slc_options+"\" class=\"optionswrapper\"> </div>");        
        obj.find('option').each(function(i){
		$("#"+id_slc_options).append("<div id=\"" + selectItemElement + selectItemCounter  + "\" class=\"selectitems\"><span id=\"" + selectItemElementText + selectItemCounter  + "\" class=\"selected\">" + $(this).html() + "</span><span id=\"" + selectItemElementValue + selectItemCounter  + "\" class=\"notdisplayed\">" + $(this).attr("value") + "</span></div>");
		selectItemCounter = selectItemCounter + 1;
        });
                
        //if number of items is greater than 9 we need to apply the 'with-scroll' class to the generated options list

        if(($("select[id='" + name + "']>option").length) > 9)
        {
        	//the 'remove' command causes a screen refresh in IE6 so we no longer call it, and instead set visibility to none
			obj.before("<input type=\"hidden\" class=\"notdisplayed\" value =\"\" name=\"" + this.name + "\" id=\""+custom_select+"\"/><div id=\""+id_icn_select+"\" class=\"fancy"+($('#'+name).hasClass('small')?" small":"")+"\">" + this.title + "</div><div id=\""+id_holder+"\" class=\"selectwrapper with-scroll"+($('#'+name).hasClass('small')?" small":"")+"\"> </div>");
        } else if(($("select[id='" + name + "']>option").length) > 4 && name == 'travelling_to' ) {
        	obj.before("<input type=\"hidden\" class=\"notdisplayed\" value =\"\" name=\"" + this.name + "\" id=\""+custom_select+"\"/><div id=\""+id_icn_select+"\" class=\"fancy"+($('#'+name).hasClass('small')?" small":"")+"\">" + this.title + "</div><div id=\""+id_holder+"\" class=\"selectwrapper with-scroll-travel"+($('#'+name).hasClass('small')?" small":"")+"\"> </div>");
        } else {
		obj.before("<input type=\"hidden\" class=\"notdisplayed\" value =\"\" name=\"" + this.name + "\" id=\""+custom_select+"\"/><div id=\""+id_icn_select+"\" class=\"fancy"+($('#'+name).hasClass('small')?" small":"")+"\">" + this.title + "</div><div id=\""+id_holder+"\" class=\"selectwrapper"+($('#'+name).hasClass('small')?" small":"")+"\"> </div>");
	}
        //in place of 'remove()' which causes refreshes in IE6, we are removing the original select lists in a different manner to overcome this problem
        obj.css("display","none");
        
        $("#"+id_icn_select).click(function(a){
            

            //unselect any selected content on the previously opened select list
            //var lastSelectedRowClass = $("#" + document.getElementById("selectBoxCurrentlyOpen").value + '_holder' + " .selectedclass");
            //lastSelectedRowClass.removeClass("selectedclass");
            
            //close any existing open select list to prevent overlaps
            $("#" + document.getElementById("selectBoxCurrentlyOpen").value + '_holder').fadeOut(50);
            
            
            $('body').unbind('click');
			$(document).unbind('keyup');
			$(document).unbind('keypress');
            
			if($("#"+id_holder).css('display') == 'none') {
				$("#"+id_holder).fadeIn(200);
				
				//keep track of currently opened list to be able to fade it out once another list is opened
				document.getElementById("selectBoxCurrentlyOpen").value = name;
				
				$("#"+id_holder).focus();
				a.stopPropagation();
				$(document).keypress(function(e) {
					if(!e) var e = window.event;
					e.cancelBubble = true;
					e.returnValue = false;
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
				});
				$(document).keyup(function(e) {
					
					if(e.which == 40) {
						var lastSelected = $("#"+id_holder+" .selectedclass");
						var lastSelectedValue = "";
						
						
						if(lastSelected.size() == 0) {
							var nextSelected =  $("#"+id_slc_options+" div:first:");
						} else {
							var nextSelected = lastSelected.next(".selectitems");
						}
						if(nextSelected.size() == 1) {
							lastSelected.removeClass("selectedclass");
							nextSelected.addClass("selectedclass");
							$("#"+custom_select).val(nextSelected.title);
           					$("#"+id_icn_select).html(nextSelected.html());
							var rowOffset = (nextSelected.offset().top - $("#"+id_holder).offset().top);
							if(rowOffset > 130) {
								$("#"+id_slc_options).scrollTo(($("#"+id_slc_options).scrollTop() + 27) +  "px");
							}
						}
						
					} else if(e.which == 38) {
						var lastSelected = $("#"+id_holder+" .selectedclass");
						var nextSelected = lastSelected.prev(".selectitems");
						if(nextSelected.size() == 1) {
							lastSelected.removeClass("selectedclass");
							nextSelected.addClass("selectedclass");
							$("#"+custom_select).val(nextSelected.title);
           					$("#"+id_icn_select).html(nextSelected.html());
							var rowOffset = (nextSelected.offset().top - $("#"+id_holder).offset().top);
							if(rowOffset > 0) {
								$("#"+id_slc_options).scrollTo(($("#"+id_slc_options).scrollTop() - 27) +  "px");
							}
						}
					} else if(e.which == 13) {
						$("#"+id_holder).fadeOut(50);
						$(document).unbind('keyup');
						$(document).unbind('keypress');
						$('body').unbind('click');
					}
					
				});
				$('body').click(function(){
					$("#"+id_holder).fadeOut(50);
					$('body').unbind('click');
					$(document).unbind('keyup');
					$(document).unbind('keypress');
				});
			} else {
				$("#"+id_holder).fadeOut(50);
				$('body').unbind('click');
				$(document).unbind('keyup');
				$(document).unbind('keypress');
			}
			
			
        });
        $("#"+id_holder).append($("#"+id_slc_options)[0]);
		$("#"+id_holder).append("<div class=\"selectfooter\"></div>");
		$("#"+id_slc_options+" > div:last").addClass("last");
        $("#"+id_holder+ " .selectitems").mouseover(function(){
            $(this).addClass("hoverclass");
        });
        $("#"+id_holder+" .selectitems").mouseout(function(){
            $(this).removeClass("hoverclass");
        });
        $("#"+id_holder+" .selectitems").click(function(){
        	
	    // every item has its position in the id, so we can refer to the position using: (this.id.substring(this.id.lastIndexOf("_") + 1))
	    
	    
            $("#"+id_holder+" .selectedclass").removeClass("selectedclass");
            $(this).addClass("selectedclass");
            var thisselection = $(this).html();
            $("#"+custom_select).val( $("#" + selectItemElementValue + this.id.substring(this.id.lastIndexOf("_") + 1)).html() );
            $("#"+id_icn_select).html(thisselection);
            $("#"+id_holder).fadeOut(50);
			$(document).unbind('keyup');
			$(document).unbind('keypress');
			$('body').unbind('click');
        });
    });
}