var StyledSelects = new Array();

jQuery(window).load(function() {
    jQuery('select').each(function(i) {
        if (jQuery(this).attr("normality") == null)
            StyledSelects[i] = new StyledSelectField(jQuery(this).attr("id"), i);
        else if (jQuery(this).attr("normality") == 'true')
            jQuery(this).css('visibility', 'visible');
    });
});

//DFH 2009-11-25 Re-styles selects when UpdatePanels reload (nuking the styles):
$(document).ready(function() {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {
        for (var i = 0; i < sender._updatePanelClientIDs.length; i++) {
            jQuery('#' + sender._updatePanelClientIDs[i] + ' SELECT[normality!="true"]').each(function() {
                for (i = 0; i < StyledSelects.length; i++) {
                    if (StyledSelects[i].id == jQuery(this).attr("id"))
                        if (jQuery(this).attr("normality") == null)
                        StyledSelects[i] = new StyledSelectField(jQuery(this).attr("id"), i);
                }
            });
        }
    });
});

function StyledSelectField(id,index){
    this.init = function(){
        var that = this;
        this.selectArray = new Array();
        this.index = index;
        this.id = id;
        this.selectWidth = jQuery('#'+this.id).css('width');
        this.elId = 'selectedOptionEl' + this.id;
        this.styledSelect = new Object(); 																																														// initialised after div is created/filled
        this.backgroundCSS = 'transparent url(/images/bg-styled-select.png) no-repeat';
        this.selectID = this.id + '_SelectField';
        this.optionValue = jQuery('#' + this.selectField).children().attr('value');
        this.selectClassName = 'styledSelect';
        this.selectedOption = 'selectedOption';
        this.selectedOptionID = this.selectID + '_selectedOption';
        this.opened = false; 																																																					// store the state of this element
        this.mouseIn = false; 																																																				// this.opened only modified in this.closeSelect() and this.openSelect()
        this.optionHolder = 'optionHolder'; 																																													// class of option holder
        this.optionHolderId = 'optionHolder_' + this.elId; 																																						// id of option holder
        this.selectWrapper = 'selectWrapper';																																													// classname of <select> wrapping element
        this.selectWrapperId = 'Styled'+this.selectWrapper+this.index;
        this.arrowWidth = 25;
        this.selectArray[this.index] = this.id;
        this.hideSelectElement();
    }
	
    this.hideSelectElement = function(){
        jQuery('#' + this.id).css({
            'opacity': 0
        });
        this.buildHTMLSelectField();
    }
	
    this.buildHTMLSelectField = function() {
        jQuery("#"+this.id).wrap(jQuery('<div></div>').attr({
            'id':this.selectWrapperId,
            'className':this.selectWrapper
            }));
        var newSelect = jQuery('<div></div>').attr({
            id: this.selectID,
            'className': this.selectClassName
        });
        var selectedOpt = jQuery('<div></div>').attr({
            id: this.selectID+'_'+this.selectedOption,
            'className': this.selectedOption
        });
        var optionHolder = jQuery('<div></div>').attr({
            id: this.optionHolderId,
            'className': this.optionHolder
        });
        var arrow = jQuery('<div></div>').attr({
            id: this.selectID+"Arrow",
            'className': 'selectArrow'
        });
		
        jQuery('#'+this.selectWrapperId).append(newSelect);
        newSelect.append(arrow);
        newSelect.append(selectedOpt);
        newSelect.append(optionHolder);
        optionHolder.css({
            'opacity': 0,
            'height':'0px',
            'overflow':'auto'
        });
		
        this.addOptions(newSelect,selectedOpt,optionHolder);
    }
	
    this.addOptions = function(selectInput,selectedOption,optionHolder) {
        var selectOptions = jQuery('#' + this.id).children();
        var defaultSet = false;
        var _this = this;
		
        selectOptions.each(function(i) {
            var actualOptionValue = jQuery(this).attr('value');
            var optionValue = jQuery(this).html();
            var opt = jQuery('<div></div>').attr({
                'className': 'option',
                rel: actualOptionValue
            });
            var optionText = jQuery('<span></span>').attr('class','optionText').html(optionValue);
            jQuery(opt).append(optionText);
            jQuery('#' + _this.optionHolderId).append(opt);
			
            if (jQuery(this).attr('selected') == true) {
                defaultSet = true;
                jQuery(selectedOption).html('<div class="option" id="' + _this.elId + '" rel="'+actualOptionValue+'">'+jQuery(opt).html()+'</div>');
            }
			
        });
		
        if(!defaultSet){
            jQuery(selectedOption).html('<div class="option" id="' + this.elId + '" rel="'+jQuery(selectOptions[0]).attr('value')+'">'+jQuery(selectOptions[0]).html()+'</div>');
        }
		
        var selectBottom = jQuery('<div></div>').attr({
            'className': 'selectFooter'
        });
        var selectBottomRight = jQuery('<span></span>');
        jQuery(selectInput).append(selectBottom);
        jQuery(selectBottom).append(selectBottomRight);
		
        this.styledSelect = jQuery(this.elId);
        this.applyStyles();
    }
	
    this.applyStyles = function() {
        var that = this;
		
        jQuery('#'+this.selectWrapperId).css({
            'z-index': 998+(-this.index),
            'width':that.selectWidth
        });
		
        jQuery('#' + this.elId).css({
            'width':parseInt(that.selectWidth)-(parseInt(that.arrowWidth))
        });
		
        jQuery('#' + this.optionHolderId).css({
            'width':parseInt(that.selectWidth)-2
        });

        jQuery('#'+this.selectWrapperId+' .selectFooter').each(function(i) {
            jQuery(this).hide();
        });
		
        jQuery('#'+this.selectWrapperId+' .selectArrow').css({
            'width':that.arrowWidth
        });
		
        this.doEventHandlers();
    }

    this.doEventHandlers = function() {
        var that = this;
        jQuery('#' + this.selectWrapperId).hover(function() {
            if (!that.opened) {
                jQuery('#' + that.selectWrapperId).css({
                    'background-position': 'left -21px'
                });
                jQuery('#' + that.selectWrapperId + ' .selectArrow').css({
                    'background-position': 'left -21px'
                });
            }
        }, function() {
            if (!that.opened) {
                jQuery('#' + that.selectWrapperId).css({
                    'background-position': 'left top'
                });
                jQuery('#' + that.selectWrapperId + ' .selectArrow').css({
                    'background-position': 'left top'
                });
            }
        });

        jQuery('#' + this.selectWrapperId).click(function(event) {
            that.toggleSelect();
        });

        jQuery('#optionHolder_' + this.elId + ' .option').each(function(i) {
            jQuery(this).hover(function() {
                that.mouseIn = true;
                jQuery(this).addClass('optionHover');
            }, function() {
                this.mouseIn = false;
                jQuery(this).removeClass('optionHover');
            });

            jQuery(this).click(function(event) {
                if (that.opened) {
                    that.optionSelect(this);
                }
            });
        });

        jQuery(document).click(function(e) {
            // DB Commented code and used single line as it was buggy in IE. Single line fixed it
            //var target = jQuery(e.target);
//            var classes = Array();
//            classes.push('.' + that.selectWrapper);
//            classes.push('.' + that.selectClassName);
//            classes.push('.' + that.selectedOption);
//            classes.push('.selectArrow');
//            classes.push('.option');
//            classes.push('.optionText');
            //            var doIt = true;
            //            jQuery.each(classes, function() {
            //                if (jQuery(target).is(jQuery(this)[0])) {
            //                    doIt = false;
            //                }
            //            });
            var doIt = !jQuery(e.target).is('.selectArrow,.option,.optionText,.' + that.selectWrapper + ',.' + that.selectClassName + ',.' + that.selectedOption);
            if (doIt) {
                for (var i in StyledSelects) {
                    if (StyledSelects[i].opened) {
                        StyledSelects[i].closeSelect();
                    }
                }
            }
        });
    }
	
    this.toggleSelect = function(){
        for(i=0;i<StyledSelects.length;i++){
            if(i!=this.index){
                StyledSelects[i].closeSelect();
            }else{
                if(StyledSelects[i].opened){
                    StyledSelects[i].closeSelect();
                }else{
                    StyledSelects[i].openSelect();
                }
            }
        }
    }

    this.closeSelect = function() {
        jQuery('#'+this.selectWrapperId+' .selectFooter').hide();
        jQuery('#'+this.selectWrapperId+' .selectArrow').css({
            'background-position': 'left top'
        });
        jQuery('#'+this.selectWrapperId).css({
            'background-position':'left top'
        });
        jQuery('#' + this.optionHolderId).css({
            'opacity': 0,
            'height':'0px',
            'overflow':'hidden'
        });
        this.opened = false;
    }

    this.openSelect = function() {
        jQuery('#' + this.optionHolderId).css({
            'opacity': 1,
            'max-height': '350px',
            'height': 'auto',
            'overflow': 'auto'
        });
        jQuery('#' + this.selectWrapperId).css({
            'background-position': 'left -42px'
        });
        jQuery('#' + this.selectWrapperId + ' .selectArrow').css({
            'background-position': 'left -42px'
        });
        jQuery('#' + this.selectWrapperId + ' .selectFooter').show();
        this.opened = true;
    }

    this.optionSelect = function(optionElement) {
        var text = jQuery(optionElement).text();
        var rel = jQuery(optionElement).attr('rel');
        var fireEvent = true;
        var actualOptions = jQuery('#' + this.id).children();
        actualOptions.each(function(element, i) {
            if (jQuery(this).attr('value') == rel) {
                if (this.selected == false)
                    this.selected = true;
                else
                    fireEvent = false;
            } else {
                this.selected = false;
            }
        });

        jQuery('#' + this.elId).find('span').text(text);
        this.opened = false;
        this.toggleSelect();
        // execute default change event if value changed
        if (fireEvent)
            jQuery('#' + this.id).trigger('onchange');
    }
	
    this.message = function(){
        return alert("here");
    }
	
    this.init();
    jQuery('#' + this.id).css({
        'display':'none'
    });
}
