// check for safari 1.0+ up to 2.0
var safariStr = "Safari";
var browserInfo = navigator.userAgent;
var safariIndex = browserInfo.indexOf(safariStr);
var safariVersion = safariIndex > -1 ? parseFloat(browserInfo.substring(safariIndex + safariStr.length + 1)) : null;
var isSafari10 = false;
if (safariVersion && safariVersion < 419) {
    isSafari10 = true;
}

// create a reference for the Script Manager to use
var LMSelects = null;
var LMScrollbars = null;

// create a reference for the Script Manager to use
var LMPressSelects = null;
var LMPressScrollbars = null;

window.addEvent('domready', function()
{
    renderDHTMLSelects();
});


var renderDHTMLSelects = function() {
    LMSelects = DHTMLDropdowns;
    LMScrollbars = Scrollbars;                 // from scrollbars.js
    
    LMSelects.firstOptionIndex = 1;
    LMSelects.init($$('select.dhtml'), LMScrollbars);
    LMScrollbars.init($$('.scrollCont'));
}


// indicate whether the document body was the initial mousedown positoin
// useful for scrollbar dragging outside of the dropdown area.
document.onmousedown=function() {
	document.beginClick = true;
}



function closeDHTMLDrops(force) {
    var drops = $$("ul.dhtmlList li.dhtml_selectedValue");      // get all lists
    for (var i = 0; i < drops.length; i++) {
        // only close the list if it is forced closed or if they are not opening that list
        if (force || !drops[i].opening) {
            drops[i].className=drops[i].className.replace(new RegExp(" over\\b"), "");
            // hide the iframe
            var iframe = $$("#" + drops[i].id + " .dhtml_dropdown_iframe");
            for (var a = 0; a < iframe.length; a++) {
                iframe[a].style.visibility = "hidden";
            }
        }
        else {
            drops[i].opening = false;       // reset the opened list's indicator
        }
    }
}


var DHTMLDropdowns = {
    elements: $$('select'),
    scrollbars: null,
    firstOptionIndex: 1,    // exclude the first option by defaults
    
    init: function(ele, scrll) {
        if (ele)
            this.elements = ele;
            
        if (scrll)
            this.scrollbars = scrll;
           
        this.renderDropdowns();
    },
    
    renderDropdowns: function() {
        var selects = this.elements;
        
        // duplicate "this" for use outside of scope
        _this_drop = this;
        
        for (var i = 0; i < selects.length; i++) {
            // set the id on the original select
            selects[i].id = this.setUniqueId(selects[i], i);
            
            var dropdownid = "dhtml_select_" + i;
            if ($(dropdownid))
                continue;       // if the dropdown already exists, skip this instance
                
            //begin creating the dropdown
            var list = document.createElement("ul");
            // set select list identification settings
            list.setAttribute("id", "dthml_select_" + i);
            list.id = dropdownid;
            list.className = "dhtmlList " + selects[i].className;
            list.refSelect = selects[i].id;     // pass the id of the reference select list
		    list.style.width = selects[i].offsetWidth + "px";
            selects[i].refList = list.id;       // pass the id of the reference dhtml list
            
            // create the first list item (the selected item)
            var selectedItem = document.createElement("li");
            selectedItem.setAttribute("id", "dhtml_select_" + i + "_selectedValue");
            selectedItem.id = "dhtml_select_" + i + "_selectedValue";
            selectedItem.className = "dhtml_selectedValue";
			selectedItem.selectElement =  selects[i];
            
            // create a span to house the selected item's text
            var selSpan = document.createElement("span");
            selSpan.className = "displayValue";
            
            // create the area for the collapse/expand button
            var button = document.createElement("span");
            button.className = "actionButton";
            
            // get the reference select list's selected item
            var val = "";
            if (selects[i].options.length > 0) {
                val = selects[i].selectedIndex ? selects[i].options[selects[i].selectedIndex].innerHTML : selects[i].options[0].innerHTML;
            }
            
		    //createTextNode() does not interpret HTML entities (using innerHTML instead)
            selSpan.innerHTML = val;
            
		    //selSpan.appendChild(button);
            selectedItem.appendChild(selSpan);
		    selectedItem.appendChild(button);
            
            // create a wrapper for the dropdown items (this prevents the z-index bug in IE)
            var ulWrap = document.createElement("span");
            ulWrap.className = "dropdownWrapper";
            selectedItem.appendChild(ulWrap);
            
            var scrl = document.createElement("div");
            scrl.className = "scrollContainer";
            ulWrap.appendChild(scrl);
    		
            
		    var scroller = document.createElement("div");
		    scroller.className = "scroller";
		    scrl.appendChild(scroller);
    		
            // create the dropdown item container
            var ulDropdown = document.createElement("ul");
            ulDropdown.style.zIndex = 900 - i;  // set the z-index (all dropdown should get an individual z-index
		    ulDropdown.setAttribute("id", "dhtml_list" + i);
		    ulDropdown.id = "dhtml_list" + i;
		    selectedItem.elementToScroll = ulDropdown;
            
            scroller.appendChild(ulDropdown);
            list.appendChild(selectedItem);
            
            // capture the onchange event from the reference select list
            var changeEvent = selects[i].onchange ? selects[i].onchange : null;
            
            // begin creating the dropdown items
            var options = $$("select#" + selects[i].id + " option");
    		
		    // start at index 1 - assume the first option will always be the label
            for (var a = this.firstOptionIndex; a < options.length; a++) {
                var li = document.createElement("li");
                // li identification settings
                li.setAttribute("id", "dhtml_select_" + i + "_item_" + a);
                li.id = "dhtml_select_" + i + "_item_" + a;
                li.setAttribute("class", "dhtmlListItem");
                li.className = "dhtmlListItem";
                li.refSelect = list.refSelect;          // store the item's reference select list's id
                li.index = a;                           // store the item's position in the collection
                li.valueField = selectedItem.id;        // store the id of the value field that will need to be filled
                
			    // add the suckerfish :hover method to the items
			    // remove item hover states for Safari 1.0 : this causes issues with underlying sIfr
			    if (!isSafari10) {
			        li.onmouseover = function() {
				        if (this.className.indexOf(" over") == -1) {
					        this.className+=" over";
				        }
        				
			        // disable the selectedItem.onclick function that keeps the list open
				        var val = $(this.valueField);
				        _this_drop.disableOnclick(val);
			        }
			        li.onmouseout = function() {
				        this.className=this.className.replace(new RegExp(" over\\b"), "");
        				
				        // enable the selectedItem.onclick function that keeps the list open
				        var val = $(this.valueField);
				        _this_drop.reenableOnclick(val);
			        }
			    }
    			
			    li.onclick = function() {
				    // trigger the child <a> onclick method
				    // this allows the click area to span the entire width of the item (not just the a tag)
				    var a = $$("#" + this.id + " a")[0];
    				
				    // began causing duplicate popup windows - removing for now
				    //a.onclick();
			    }
    			
                var liA = new Element("a");  //create a link for user interaction
                liA.setAttribute("href", options[a].value);
                liA.style.width = "100%";
    			if (selects[i].className.indexOf('remote') > -1) {
    			    liA.className = "remote";
    			    liA.rel = options[a].getAttribute('rel');
					if (options[a].onclick){
						liA.setAttribute("onclick", options[a].getAttribute('onclick'));
					}
    			    liA.target = "_blank";
    			}
			    //createTextNode() does not interpret HTML entities (using innerHTML instead)
			    liA.innerHTML = options[a].innerHTML;
                li.appendChild(liA);
                ulDropdown.appendChild(li);
                
                // add the onlick events
                liA.addEvent('click', function() {
                    var parent = this.parentNode ? this.parentNode : this.parentElement;
                    var ref = document.getElementById(parent.refSelect);
                    
                    // only change the selectedIndex if the index is, in fact, changing
                    if (ref.selectedIndex != parent.index) {
                        ref.selectedIndex = parent.index;       // change the selected item of the reference select list
                        // populate the value field
                        var val = $$("#" + parent.valueField + " span.displayValue");
                        if (val[0].innerText)
                            val[0].innerText = this.innerText;
                        else
                            val[0].innerHTML = this.innerHTML;
                        
                        // if there was an onchange event bind that to the link
                        if (ref.onchange) {
                            ref.onchange();
                        }
                    }
                    return false;
                });
    			
            }
    		
		    // create dhtml scrollbars
		    var scroll_wrap = document.createElement("div");
		    scroll_wrap.className = "scrollWrapper";
    		
		    var scroll_cont = document.createElement("div");
		    scroll_cont.setAttribute("id", "dhtml_select" + i + "_scrollCont");
		    scroll_cont.id = "dhtml_select" + i + "_scrollCont";
		    scroll_cont.className = "scrollCont";
		    scroll_cont.refList = selectedItem.id;
    		
		    var scroll_thumb = document.createElement("div");
		    scroll_thumb.setAttribute("id", "dhtml_select" + i + "_scrollThumb");
		    scroll_thumb.id = "dhtml_select" + i + "_scrollThumb";
		    scroll_thumb.className = "scrollThumb";
		    scroll_thumb.elementToScroll = ulDropdown.id;
    		
		    var arrowupBtn = document.createElement("a");
		    arrowupBtn.className = "arrowUpBtn";
		    arrowupBtn.elementToScroll = ulDropdown.id;
		    arrowupBtn.thumbElement = scroll_thumb.id;
		    arrowupBtn.setAttribute("id", "dhtml_select_" + i + "_up");
		    arrowupBtn.id = "dhtml_select_" + i + "_up";
    		
		    var arrowdownBtn = document.createElement("a");
		    arrowdownBtn.className = "arrowDownBtn";
		    arrowdownBtn.elementToScroll = ulDropdown.id;
		    arrowdownBtn.thumbElement = scroll_thumb.id;
		    selectedItem.thumbElement = scroll_thumb.id;
		    arrowdownBtn.setAttribute("id", "dhtml_select_" + i + "_down");
		    arrowdownBtn.id = "dhtml_select_" + i + "_down";
    		
    		
		    scroll_cont.onmouseover = function() {
			    var sel = $$("#" + this.refList)[0];
			    _this_drop.disableOnclick(sel);
			    _this_drop.disableOnclick(document);
		    }
    		
		    scroll_cont.onmouseout = function() {
			    var sel = $$("#" + this.refList)[0];
			    _this_drop.reenableOnclick(sel);
			    _this_drop.reenableOnclick(document);
		    }
    				
		    scroll_cont.appendChild(scroll_thumb);
		    scroll_wrap.appendChild(scroll_cont);
		    scroll_wrap.appendChild(arrowupBtn);
		    scroll_wrap.appendChild(arrowdownBtn);
		    scrl.insertBefore(scroll_wrap, scroller);
            
            // insert the dhtml list right before the original select
            var parent = selects[i].parentNode ? selects[i].parentNode : selects[i].parentElement;
            parent.insertBefore(list, selects[i]);
            
            scrl.style.width = (scrl.offsetWidth - 3) + "px";
    		
            //remove the original select list from view
            selects[i].style.position = "absolute";
            selects[i].style.left = "-9999px";
            
		    this.buildIEIFrame(ulWrap, scrl);
                   
            //apply the suckerfish dropdown code to the dhtml select
            selectedItem.onclick=function() {
            
                this.opening = true;        // tell the close function that this item should not be closed
                // only change the classname if it hasn't been changed already
                if (this.className.indexOf(" over") == -1) {
                    this.className+=" over";
                }
                
                // drop the height of the ul if the list doesn't require scrolling
                var wrapper = $$("li#" + this.id + " .scrollContainer")[0];
                var ul = $$("li#" + this.id + " ul")[0];
    			
                var totHeight = ul.offsetHeight;
                
			    if (!wrapper.borderFix) {
				    wrapper.style.width = (wrapper.offsetWidth - 3) + "px";
				    wrapper.borderFix = true;
			    }
    			
			    this.requiresScrolling = true;
			    // reduce height of dropdown if required or else show dhtml scrollbars
			    if (wrapper.offsetHeight > totHeight) { 
				    wrapper.origHeight = wrapper.offsetHeight;	// store the original height for later use
                    wrapper.style.height = totHeight + "px";
                    wrapper.style.overflow = "visible";
				    this.requiresScrolling = false;
                }
    			
			    if (this.requiresScrolling) {
				    // drop width by 20px to make room for the scrollbars
				    if (!this.scrollAffixed) {
    					
					    ul.style.width = (ul.offsetWidth - 18) + "px";
					    this.scrollAffixed = true;
				    }
    				
				    // attach the mousewheel event
		            ul.addEvent('mousewheel', _this_drop.captureMouseWheel.bindWithEvent(ul, this));
			    }
			    else {
				    var scroller = $$("li#" + this.id + " .scrollWrapper")[0];
				    scroller.style.display = "none";
			    }
    			
                // display the iframe and set the height
                var iframe = $$("#" + this.id + " .dhtml_dropdown_iframe");
                for (var i = 0; i < iframe.length; i++) {
                    iframe[i].style.visibility = "visible";
                    iframe[i].style.height = wrapper.offsetHeight + "px";
                }


				
                if (wrapper) {
                    wrapper.setStyles({'top': '100%', 'border-top': 0});
					
					var overflow = window;
					
					if ( this.selectElement.getAttribute('rel') ) { 
						overflowID = parseLinkRel(this.selectElement.getAttribute('rel')).overflow;
						overflow = $(overflowID);
					}
					
					var ddownPosition = wrapper.getCoordinates().top + wrapper.offsetHeight - overflow.getScroll().y;
                    if (ddownPosition > overflow.getSize().y) {
		                wrapper.setStyles({'top': -1 * wrapper.offsetHeight - list.offsetHeight, 'border-top': wrapper.getStyle('border-bottom')});
		            }
		        }
            }
    		
            /* removing focus and blur events - this disables selecting items (that won't work)
            // set the onfocus function (used when a user tabs to the select field)
            selects[i].onfocus=function() {
                var list = $$("#" + this.refList + " li.dhtml_selectedValue")[0];
                list.onclick();     // trigger the onclick function for the list
            }
            
            
            // set the onfocus function (used when a user tabs to the select field)
            selects[i].onblur=function() {
                var list = $$("#" + this.refList + " li.dhtml_selectedValue")[0];
                list.opening = false;
                closeDHTMLDrops();
            }
            */
		    selSpan.style.width = (ulDropdown.offsetWidth - button.offsetWidth -1) + "px";
		    
        }
        
        this.setBodyCloseEvent();
    },
        
    setUniqueId: function(ele, interval) {
        if (!ele.id)
            return "orig_select_" + interval;
        else
            return ele.id;
    },
    
    setBodyCloseEvent: function() {
    
        // set the close function when a user clicks outside of the select list
        document.onclick=function() {
	        if (document.beginClick) {
		        closeDHTMLDrops();
	        }
	        document.beginClick = false;
        }
    },
    
    buildIEIFrame: function(ulWrap, scrl) {
        if (window.ie6) {
            // create an iframe for IE6 (prevents items from showing through the dropdown)
            var iframe = document.createElement("iframe");
            iframe.setAttribute("frameborder", "0");
            iframe.setAttribute("marginwidth", "0");
            iframe.setAttribute("marginheight", "0");
            iframe.setAttribute("scrolling", "no");
            iframe.style.width = (scrl.offsetWidth - 1) + "px";
            iframe.style.height = "100%";
            iframe.style.position = "absolute";
            iframe.style.top = "0px";
            iframe.style.left = "0px";
            iframe.className = "dhtml_dropdown_iframe";
            iframe.style.visibility = "hidden";
            iframe.src = "";
            ulWrap.insertBefore(iframe, scrl);
        }
    },
    
    disableOnclick: function (obj) {
	    obj.onclickHolder = obj.onclick;
	    obj.onclick = null;
    },

    reenableOnclick: function (obj) {
	    obj.onclick = obj.onclickHolder;
	    obj.onclickHolder = null;
    },
    
    captureMouseWheel: function(event, obj) {
        var direction = event.wheel;
        var ele = obj.elementToScroll;
	    var parent = ele.parentElement ? ele.parentElement.parentElement : ele.parentNode.parentNode;
    	
	    var wheelJump = 10 * direction;
        if (ele.offsetTop + wheelJump >= (ele.offsetHeight - parent.offsetHeight) * -1 && ele.offsetTop + wheelJump <= 0) {
		    ele.style.top = (ele.offsetTop + wheelJump) + "px";
		    var contentpercent = (ele.offsetTop / (ele.offsetHeight - parent.offsetHeight)) * -1;
		    Scrollbars.moveThumb(contentpercent, obj.thumbElement);
	    }
	    else if (ele.offsetTop + wheelJump < (ele.offsetHeight - parent.offsetHeight) * -1 && direction < 0) {
		    ele.style.top = ((ele.offsetHeight - parent.offsetHeight) * -1) + "px";
		    Scrollbars.moveThumb(1, obj.thumbElement);
	    }
	    else if (ele.offsetTop + wheelJump > 0 && direction > 0) {
	        ele.style.top = "0px";
	        Scrollbars.moveThumb(0, obj.thumbElement);
        }
        return false;
//	    if (ele.offsetTop + wheelJump <= 0) {
//		    ele.style.top = (ele.offsetTop + wheelJump) + "px";
//		    var contentpercent = (ele.offsetTop / (ele.offsetHeight - parent.offsetHeight)) * -1;
//		    moveThumb(contentpercent, obj.thumbElement);
//	    }
//	    else {
    }

};