/* Copyright (c) 2006 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 33 2008-12-10 22:55:28Z kelvin.luck $
 */
(function(A){A.jScrollPane={active:[]};A.fn.jScrollPane=function(C){C=A.extend({},A.fn.jScrollPane.defaults,C);var B=function(){return false};return this.each(function(){var O=A(this);O.css("overflow","hidden");var X=this;if(A(this).parent().is(".jScrollPaneContainer")){var Ac=C.maintainPosition?O.position().top:0;var L=A(this).parent();var d=L.innerWidth();var Ad=L.outerHeight();var M=Ad;A(">.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown",L).remove();O.css({top:0})}else{var Ac=0;this.originalPadding=O.css("paddingTop")+" "+O.css("paddingRight")+" "+O.css("paddingBottom")+" "+O.css("paddingLeft");this.originalSidePaddingTotal=(parseInt(O.css("paddingLeft"))||0)+(parseInt(O.css("paddingRight"))||0);var d=O.innerWidth();var Ad=O.innerHeight();var M=Ad;O.wrap(A("<div></div>").attr({className:"jScrollPaneContainer"}).css({height:Ad+"px",width:d+"px"}));A(document).bind("emchange",function(Ae,Af,p){O.jScrollPane(C)})}if(C.reinitialiseOnImageLoad){var N=A.data(X,"jScrollPaneImagesToLoad")||A("img",O);var G=[];if(N.length){N.each(function(p,Ae){A(this).bind("load",function(){if(A.inArray(p,G)==-1){G.push(Ae);N=A.grep(N,function(Ag,Af){return Ag!=Ae});A.data(X,"jScrollPaneImagesToLoad",N);C.reinitialiseOnImageLoad=false;O.jScrollPane(C)}}).each(function(Af,Ag){if(this.complete||this.complete===undefined){this.src=this.src}})})}}var o=this.originalSidePaddingTotal;var l={height:"auto",width:d-C.scrollbarWidth-C.scrollbarMargin-o+"px"};if(C.scrollbarOnLeft){l.paddingLeft=C.scrollbarMargin+C.scrollbarWidth+"px"}else{l.paddingRight=C.scrollbarMargin+"px"}O.css(l);var m=O.outerHeight();var i=Ad/m;if(i<0.99){var H=O.parent();H.append(A("<div></div>").attr({className:"jScrollPaneTrack"}).css({width:C.scrollbarWidth+"px"}).append(A("<div></div>").attr({className:"jScrollPaneDrag"}).css({width:C.scrollbarWidth+"px"}).append(A("<div></div>").attr({className:"jScrollPaneDragTop"}).css({width:C.scrollbarWidth+"px"}),A("<div></div>").attr({className:"jScrollPaneDragBottom"}).css({width:C.scrollbarWidth+"px"}))));var z=A(">.jScrollPaneTrack",H);var P=A(">.jScrollPaneTrack .jScrollPaneDrag",H);if(C.showArrows){var g;var Ab;var S;var r;var j=function(){if(r>4||r%4==0){y(u+Ab*b)}r++};var K=function(p){A("html").unbind("mouseup",K);g.removeClass("jScrollActiveArrowButton");clearInterval(S)};var Z=function(){A("html").bind("mouseup",K);g.addClass("jScrollActiveArrowButton");r=0;j();S=setInterval(j,100)};H.append(A("<a></a>").attr({href:"javascript:;",className:"jScrollArrowUp"}).css({width:C.scrollbarWidth+"px"}).html("Scroll up").bind("mousedown",function(){g=A(this);Ab=-1;Z();this.blur();return false}).bind("click",B),A("<a></a>").attr({href:"javascript:;",className:"jScrollArrowDown"}).css({width:C.scrollbarWidth+"px"}).html("Scroll down").bind("mousedown",function(){g=A(this);Ab=1;Z();this.blur();return false}).bind("click",B));var Q=A(">.jScrollArrowUp",H);var J=A(">.jScrollArrowDown",H);if(C.arrowSize){M=Ad-C.arrowSize-C.arrowSize;z.css({height:M+"px",top:C.arrowSize+"px"})}else{var s=Q.height();C.arrowSize=s;M=Ad-s-J.height();z.css({height:M+"px",top:s+"px"})}}var w=A(this).css({position:"absolute",overflow:"visible"});var D;var Y;var b;var u=0;var V=i*Ad/2;var a=function(Ae,Ag){var Af=Ag=="X"?"Left":"Top";return Ae["page"+Ag]||(Ae["client"+Ag]+(document.documentElement["scroll"+Af]||document.body["scroll"+Af]))||0};var f=function(){return false};var v=function(){n();D=P.offset(false);D.top-=u;Y=M-P[0].offsetHeight;b=2*C.wheelSpeed*Y/m};var E=function(p){v();V=a(p,"Y")-u-D.top;A("html").bind("mouseup",T).bind("mousemove",h);if(A.browser.msie){A("html").bind("dragstart",f).bind("selectstart",f)}return false};var T=function(){A("html").unbind("mouseup",T).unbind("mousemove",h);V=i*Ad/2;if(A.browser.msie){A("html").unbind("dragstart",f).unbind("selectstart",f)}};var y=function(Ae){Ae=Ae<0?0:(Ae>Y?Y:Ae);u=Ae;P.css({top:Ae+"px"});var Af=Ae/Y;w.css({top:((Ad-m)*Af)+"px"});O.trigger("scroll");if(C.showArrows){Q[Ae==0?"addClass":"removeClass"]("disabled");J[Ae==Y?"addClass":"removeClass"]("disabled")}};var h=function(p){y(a(p,"Y")-D.top-V)};var q=Math.max(Math.min(i*(Ad-C.arrowSize*2),C.dragMaxHeight),C.dragMinHeight);P.css({height:q+"px"}).bind("mousedown",E);var k;var R;var I;var t=function(){if(R>8||R%4==0){y((u-((u-I)/2)))}R++};var Aa=function(){clearInterval(k);A("html").unbind("mouseup",Aa).unbind("mousemove",e)};var e=function(p){I=a(p,"Y")-D.top-V};var U=function(p){v();e(p);R=0;A("html").bind("mouseup",Aa).bind("mousemove",e);k=setInterval(t,100);t()};z.bind("mousedown",U);H.bind("mousewheel",function(Ae,Ag){v();n();var Af=u;y(u-Ag*b);var p=Af!=u;return !p});var F;var W;function c(){var p=(F-u)/C.animateStep;if(p>1||p<-1){y(u+p)}else{y(F);n()}}var n=function(){if(W){clearInterval(W);delete F}};var x=function(Af,p){if(typeof Af=="string"){$e=A(Af,O);if(!$e.length){return}Af=$e.offset().top-O.offset().top}H.scrollTop(0);n();var Ae=-Af/(Ad-m)*Y;if(p||!C.animateTo){y(Ae)}else{F=Ae;W=setInterval(c,C.animateInterval)}};O[0].scrollTo=x;O[0].scrollBy=function(Ae){var p=-parseInt(w.css("top"))||0;x(p+Ae)};v();x(-Ac,true);A("*",this).bind("focus",function(Ah){var Ag=A(this);var Aj=0;while(Ag[0]!=O[0]){Aj+=Ag.position().top;Ag=Ag.offsetParent()}var p=-parseInt(w.css("top"))||0;var Ai=p+Ad;var Af=Aj>p&&Aj<Ai;if(!Af){var Ae=Aj-C.scrollbarMargin;if(Aj>p){Ae+=A(this).height()+15+C.scrollbarMargin-Ad}x(Ae)}});if(location.hash){x(location.hash)}A(document).bind("click",function(Ae){$target=A(Ae.target);if($target.is("a")){var p=$target.attr("href");if(p.substr(0,1)=="#"){x(p)}}});A.jScrollPane.active.push(O[0])}else{O.css({height:Ad+"px",width:d-this.originalSidePaddingTotal+"px",padding:this.originalPadding});O.parent().unbind("mousewheel")}})};A.fn.jScrollPane.defaults={scrollbarWidth:10,scrollbarMargin:5,wheelSpeed:18,showArrows:false,arrowSize:0,animateTo:false,dragMinHeight:1,dragMaxHeight:99999,animateInterval:100,animateStep:3,maintainPosition:true,scrollbarOnLeft:false,reinitialiseOnImageLoad:false};A(window).bind("unload",function(){var C=A.jScrollPane.active;for(var B=0;B<C.length;B++){C[B].scrollTo=C[B].scrollBy=null}})})(jQuery);

/* Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 * 
 * Requires: 1.2.2+
 */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);



/*

styledSelectBox
modified to work with OptGroups And JScrollpane Plugin 

based on
Stylish Select 0.4.1 - $ plugin to replace a select drop down box with a stylable unordered list
http://scottdarby.com/

Requires: jQuery 1.3 or newer

Contributions from Justin Beasley: http://www.harvest.org/ & Anatoly Ressin: http://www.artazor.lv/

Dual licensed under the MIT and GPL licenses.

*/
(function($){

    //create cross-browser indexOf
    Array.prototype.indexOf = function (obj, start) {
        for (var i = (start || 0); i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
    }
	
    //utility methods
    $.fn.extend({
        getSetSSValue: function(value){
            if (value){
                //set value and trigger change event
                $(this).val(value).change();
                return this;
            } else {
                return $(this).find(':selected').val();
            }
        },
        //added by Justin Beasley
        resetSS: function(){
            var oldOpts = $(this).data('ssOpts');
            $(this).next().remove();
            //unbind all events and redraw
            $(this).unbind().styledSelectBox(oldOpts);
        }
    });

    $.fn.styledSelectBox = function(options) {
	
        return this.each(function(){
			
            var defaults = {
            	useJScrollPane: false,
            	useFocus: false,
            	defaultText: "Please choose..."
            };

            //initial variables
            var opts = $.extend(defaults, options),
            input = $(this),
            
            styledSelectBox = $('<div class="styledSelectBox"></div>'),

            styledSelectBoxChooser = $('<div class="styledSelectBoxChooser"></div>'),     
            
            styledSelectBoxChooserTextHolder = $('<div class="styledSelectBoxChooserTextHolder"></div>'),
            
            styledSelectBoxListContainer = $('<div class="styledSelectBoxListContainer"></div>'),
            
            styledSelectBoxList = $('<ul class="styledSelectBoxList"></ul>'),
            
            itemIndex = -1,
            currentIndex = -1,
            keys = [],
            prevKey = false,
            akeywaspressed = false;

            //added by Justin Beasley
            $(this).data('ssOpts',options);
			
            //build new list
            styledSelectBox.insertAfter(input);
            styledSelectBoxChooser.prependTo(styledSelectBox);
            styledSelectBoxChooserTextHolder.appendTo(styledSelectBoxChooser);
            styledSelectBoxListContainer.appendTo(styledSelectBox);
            styledSelectBoxList.appendTo(styledSelectBoxListContainer);
            input.hide();
            
            //test for optgroup
	        input.children().each(function(){
	    
	    		if(this.tagName=='OPTGROUP') {
	
	
		            var optionTitle = $(this).attr('label'),
		            optGroup = $('<li class="styledSelectBoxListOptionGroup">'+optionTitle+'</li>');
						
		            optGroup.appendTo(styledSelectBoxList);
		
		            var optGroupList = $('<ul></ul>');
		
		            optGroupList.appendTo(optGroup);
	
		            $(this).children().each(function(){
	                
		            	++itemIndex;
		            	
		                var option = $(this).text();
		                var key = $(this).val();
		                
		                //add first letter of each word to array
		                keys.push(option.charAt(0).toLowerCase());
		                
		                if ($(this).attr('selected') == true){
		                    currentIndex = itemIndex;
		                }

		                optGroupList.append($('<li '+ ((itemIndex==0)?'style="display:none;"':'') +'><a href="JavaScript:void(0);">'+option+'</a></li>').data('key',key));

	                })
	
	                
	            } else {
	                
                	++itemIndex;

                    var option = $(this).text();
                    var key = $(this).val();

                    //add first letter of each word to array
                    keys.push(option.charAt(0).toLowerCase());                    
                    
                   // $(this).parent().children(":selected");
                    
                   // alert($(this).parent().val() );
                    
                    if ($(this).attr('selected') == true){
                    	currentIndex = itemIndex;
                    }  
	                    
                	styledSelectBoxList.append($('<li '+ ((itemIndex==0)?'style="display:none;"':'') +'><a href="JavaScript:void(0);">'+option+'</a></li>').data('key', key));
	            }

	        });

            //check if a value is selected
            if (currentIndex != -1){
                navigateList(currentIndex, true);
            } 
            
            styledSelectBoxChooser.click(function(event){

            	event.stopPropagation();

                //hide all menus apart from this one
                $('.styledSelectBoxListContainer').not($(this).next()).hide();

                //show/hide this menu
                styledSelectBoxListContainer.toggle();
                
                if (opts.useFocus == true) {
	                if (styledSelectBoxListContainer.css("display") == "block") {
	                	styledSelectBoxList.find('a').eq(currentIndex).focus();
	                } 	
                }

            });

            styledSelectBoxList.find('a').click(function(e){
            	
                //update counter
            	currentIndex = styledSelectBoxList.find('a').index($(e.target));
                
           		navigateList(currentIndex);
            	styledSelectBoxListContainer.hide();
            });
			
            function navigateList(currentIndex, init){
              
                if (opts.useFocus == true) {            	
                	styledSelectBoxList.find('a').eq(currentIndex).focus();
                }
                
                styledSelectBoxList.find('a').removeClass('selected').eq(currentIndex).addClass('selected');

                var text = styledSelectBoxList.find('a').eq(currentIndex).text();
                var val = styledSelectBoxList.find('a').eq(currentIndex).parent().data('key');

                //page load
                if (init == true){
                	input.val(val);
                	styledSelectBoxChooserTextHolder.text(text);
                    return false;
                }
                
                styledSelectBoxChooserTextHolder.text(text);
                input.val(val);
                
                //stop change function from firing if key is pressed
                if (akeywaspressed == true){	
                	akeywaspressed = false;
                } else {
                	input.change();
                }	
            };


            //handle up and down keys
            function keyPress(element) {
                //when keys are pressed

            	element.onkeydown = function(e){
                    var keycode;
                    if (e == null) { //ie
                        keycode = event.keyCode;
                    } else { //everything else
                        keycode = e.which;
                    }
                    
                    akeywaspressed = true;

                    switch(keycode)
                    {
                        case 40: //down
                        case 39: //right
                            incrementList();
                            return false;
                            break;
                        case 38: //up
                        case 37: //left
                            decrementList();
                            return false;
                            break;
                        case 33: //page up
                        case 36: //home
                            gotoFirst();
                            return false;
                            break;
                        case 34: //page down
                        case 35: //end
                            gotoLast();
                            return false;
                            break;
                        case 13:
                        case 27:
                        	styledSelectBoxListContainer.hide();
                          //  positionHideFix();
                            return false;
                            break;
                    }

                    //check for keyboard shortcuts
                    keyPressed = String.fromCharCode(keycode).toLowerCase();
                    
                    var currentKeyIndex = keys.indexOf(keyPressed);

                    if (typeof currentKeyIndex != 'undefined') { //if key code found in array
                        ++currentIndex;
                        currentIndex = keys.indexOf(keyPressed, currentIndex); //search array from current index
                        if (currentIndex == -1 || currentIndex == null || prevKey != keyPressed) currentIndex = keys.indexOf(keyPressed); //if no entry was found or new key pressed search from start of array

                        
                        navigateList(currentIndex);
                        //store last key pressed
                        prevKey = keyPressed;
                        
                        return false;
                    }
                    
                    
                }
            	
            	
            }

            function incrementList(){
                if (currentIndex < (styledSelectBoxList.find('a').length-1)) {
                    ++currentIndex;
                    navigateList(currentIndex);
                }
            }

            function decrementList(){
                if (currentIndex > 0) {
                    --currentIndex;
                    navigateList(currentIndex);
                }
            }

            function gotoFirst(){
                currentIndex = 0;
                navigateList(currentIndex);
            }
			
            function gotoLast(){
                currentIndex = styledSelectBoxList.find('a').length-1;
                navigateList(currentIndex);
            }
            
            $('body').click(function(){
            	styledSelectBoxListContainer.hide();
            });      

            styledSelectBox.click(function(event){
            	event.stopPropagation();
            	
            	if (opts.useFocus == true) {
	                if (styledSelectBoxListContainer.css("display") == "block") {
	                   	styledSelectBoxList.find('a').eq(currentIndex).focus();
	                } 
	            	keyPress(this);
            	}
            });
            
            if (opts.useFocus == true) {
	            styledSelectBox.focus(function(event){
	                 keyPress(this);
	            });
            }
            
            if (opts.useJScrollPane == true) {
    	        styledSelectBoxList.jScrollPane({scrollbarWidth:7, scrollbarMargin:0});
            } 

        	function changeCssFunc () {
        		styledSelectBoxListContainer.hide().css('left','0');
            }            
            
            if ($.browser.msie == true) {
            	window.setTimeout(changeCssFunc, 100);
            } else {
            	changeCssFunc();
            }
        });
    };
})(jQuery);
