/*
 * jQuery UI Tooltip @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Tooltip
 *
 * Depends:
 *  jquery.ui.core.js
 *  jquery.ui.widget.js
 *  jquery.ui.position.js
 */
(function($) {

var increments = 0;

$.widget("ui.tooltip", {
    options: {
        items: "[title]",
        content: function() {
            return $(this).attr("title");
        },
        position: {
            my: "left center",
            at: "right center",
            offset: "15 0"
        }
    },
    _create: function() {
        var self = this;
        this.tooltip = $("<div></div>")
            .attr("id", "ui-tooltip-" + increments++)
            .attr("role", "tooltip")
            .attr("aria-hidden", "true")
            .addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content")
            .appendTo(document.body)
            .hide();
        this.tooltipContent = $("<div></div>")
            .addClass("ui-tooltip-content")
            .appendTo(this.tooltip);
        this.opacity = this.tooltip.css("opacity");
        this.element
            .bind("focus.tooltip mouseover.tooltip", function(event) {
                self.open( event );
            })
            .bind("blur.tooltip mouseout.tooltip", function(event) {
                self.close( event );
            });
    },
    
    enable: function() {
        this.options.disabled = false;
    },
    
    disable: function() {
        this.options.disabled = true;
    },
    
    _destroy: function() {
        this.tooltip.remove();
    },
    
    widget: function() {
        return this.element.pushStack(this.tooltip.get());
    },
    
    open: function(event) {
        var target = $(event && event.target || this.element).closest(this.options.items);
        // already visible? possible when both focus and mouseover events occur
        if (this.current && this.current[0] == target[0])
            return;
        var self = this;
        this.current = target;
        this.currentTitle = target.attr("title");
        var content = this.options.content.call(target[0], function(response) {
            // IE may instantly serve a cached response, need to give it a chance to finish with _show before that
            setTimeout(function() {
                // ignore async responses that come in after the tooltip is already hidden
                if (self.current == target)
                    self._show(event, target, response);
            }, 13);
        });
        if (content) {
            self._show(event, target, content);
        }
    },
    
    _show: function(event, target, content) {
        if (!content)
            return;
        
        target.attr("title", "");
        
        if (this.options.disabled)
            return;
            
        this.tooltipContent.html(content);
        this.tooltip.css({
            top: 0,
            left: 0
        }).show().position( $.extend({
            of: target
        }, this.options.position )).hide();
        
        this.tooltip.attr("aria-hidden", "false");
        target.attr("aria-describedby", this.tooltip.attr("id"));

        this.tooltip.stop(false, true).fadeIn();

        this._trigger( "open", event );
    },
    
    close: function(event) {
        if (!this.current)
            return;
        
        var current = this.current;
        this.current = null;
        current.attr("title", this.currentTitle);
        
        if (this.options.disabled)
            return;
        
        current.removeAttr("aria-describedby");
        this.tooltip.attr("aria-hidden", "true");
        
        this.tooltip.stop(false, true).fadeOut();
        
        this._trigger( "close", event );
    }
});

$.ui.tooltip.version = "@VERSION";

})(jQuery);

 /*
 * jQuery UI selectmenu
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */

(function($) {

$.widget("ui.selectmenu", {
    _init: function() {
        var self = this, o = this.options;
        
        //quick array of button and menu id's
        this.ids = [this.element.attr('id') + '-' + 'button', this.element.attr('id') + '-' + 'menu'];
        
        //define safe mouseup for future toggling
        this._safemouseup = true;
        
        //create menu button wrapper
        this.newelement = $('<a class="'+ this.widgetBaseClass +' ui-widget ui-state-default ui-corner-all" id="'+this.ids[0]+'" role="button" href="#" aria-haspopup="true" aria-owns="'+this.ids[1]+'"></a>')
            .insertAfter(this.element);
        
        //transfer tabindex
        var tabindex = this.element.attr('tabindex');
        if(tabindex){ this.newelement.attr('tabindex', tabindex); }
        
        //save reference to select in data for ease in calling methods
        this.newelement.data('selectelement', this.element);
        
        //menu icon
        this.selectmenuIcon = $('<span class="'+ this.widgetBaseClass +'-icon ui-icon"></span>')
            .prependTo(this.newelement)
            .addClass( (o.style == "popup")? 'ui-icon-triangle-2-n-s' : 'ui-icon-triangle-1-s' );   

            
        //make associated form label trigger focus
        $('label[for='+this.element.attr('id')+']')
            .attr('for', this.ids[0])
            .bind('click', function(){
                self.newelement[0].focus();
                return false;
            }); 

        //click toggle for menu visibility
        this.newelement
            .bind('mousedown', function(event){
                self._toggle(event);
                //make sure a click won't open/close instantly
                if(o.style == "popup"){
                    self._safemouseup = false;
                    setTimeout(function(){self._safemouseup = true;}, 300);
                }   
                return false;
            })
            .bind('click',function(){
                return false;
            })
            .keydown(function(event){
                var ret = true;
                switch (event.keyCode) {
                    case $.ui.keyCode.ENTER:
                        ret = true;
                        break;
                    case $.ui.keyCode.SPACE:
                        ret = false;
                        self._toggle(event);    
                        break;
                    case $.ui.keyCode.UP:
                    case $.ui.keyCode.LEFT:
                        ret = false;
                        self._moveSelection(-1);
                        break;
                    case $.ui.keyCode.DOWN:
                    case $.ui.keyCode.RIGHT:
                        ret = false;
                        self._moveSelection(1);
                        break;  
                    case $.ui.keyCode.TAB:
                        ret = true;
                        break;  
                    default:
                        ret = false;
                        self._typeAhead(event.keyCode, 'mouseup');
                        break;  
                }
                return ret;
            })
            .bind('mouseover focus', function(){ 
                $(this).addClass(self.widgetBaseClass+'-focus ui-state-hover'); 
            })
            .bind('mouseout blur', function(){  
                $(this).removeClass(self.widgetBaseClass+'-focus ui-state-hover'); 
            });
        
        //document click closes menu
        $(document)
            .mousedown(function(event){
                self.close(event);
            });

        //change event on original selectmenu
        this.element
            .click(function(){ this._refreshValue(); })
            .focus(function(){ this.newelement[0].focus(); });
        
        //create menu portion, append to body
        var cornerClass = (o.style == "dropdown")? " ui-corner-bottom" : " ui-corner-all"
        this.list = $('<ul class="' + self.widgetBaseClass + '-menu ui-widget ui-widget-content'+cornerClass+'" aria-hidden="true" role="listbox" aria-labelledby="'+this.ids[0]+'" id="'+this.ids[1]+'"></ul>').appendTo('body');              
        
        //serialize selectmenu element options  
        var selectOptionData = [];
        this.element
            .find('option')
            .each(function(){
                selectOptionData.push({
                    value: $(this).attr('value'),
                    text: self._formatText(jQuery(this).text()),
                    selected: $(this).attr('selected'),
                    classes: $(this).attr('class'),
                    parentOptGroup: $(this).parent('optgroup').attr('label')
                });
            });     
                
        //active state class is only used in popup style
        var activeClass = (self.options.style == "popup") ? " ui-state-active" : "";
        
        //write li's
        for(var i in selectOptionData){
            var thisLi = $('<li role="presentation"><a href="#" tabindex="-1" role="option" aria-selected="false">'+ selectOptionData[i].text +'</a></li>')
                .data('index',i)
                .addClass(selectOptionData[i].classes)
                .data('optionClasses', selectOptionData[i].classes|| '')
                .mouseup(function(event){
                        if(self._safemouseup){
                            var changed = $(this).data('index') != self._selectedIndex();
                            self.value($(this).data('index'));
                            self.select(event);
                            if(changed){ self.change(event); }
                            self.close(event,true);
                        }
                    return false;
                })
                .click(function(){
                    return false;
                })
                .bind('mouseover focus', function(){ 
                    self._selectedOptionLi().addClass(activeClass); 
                    self._focusedOptionLi().removeClass(self.widgetBaseClass+'-item-focus ui-state-hover'); 
                    $(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover'); 
                })
                .bind('mouseout blur', function(){ 
                    if($(this).is( self._selectedOptionLi() )){ $(this).addClass(activeClass); }
                    $(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover'); 
                });
                
            //optgroup or not...
            if(selectOptionData[i].parentOptGroup){
                var optGroupName = self.widgetBaseClass + '-group-' + selectOptionData[i].parentOptGroup;
                if(this.list.find('li.' + optGroupName).size()){
                    this.list.find('li.' + optGroupName + ':last ul').append(thisLi);
                }
                else{
                    $('<li role="presentation" class="'+self.widgetBaseClass+'-group '+optGroupName+'"><span class="'+self.widgetBaseClass+'-group-label">'+selectOptionData[i].parentOptGroup+'</span><ul></ul></li>')
                        .appendTo(this.list)
                        .find('ul')
                        .append(thisLi);
                }
            }
            else{
                thisLi.appendTo(this.list);
            }
            
            //this allows for using the scrollbar in an overflowed list
            this.list.bind('mousedown mouseup', function(){return false;});
            
            //append icon if option is specified
            if(o.icons){
                for(var j in o.icons){
                    if(thisLi.is(o.icons[j].find)){
                        thisLi
                            .data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon')
                            .addClass(self.widgetBaseClass + '-hasIcon');
                        var iconClass = o.icons[j].icon || "";
                        
                        thisLi
                            .find('a:eq(0)')
                            .prepend('<span class="'+self.widgetBaseClass+'-item-icon ui-icon '+iconClass + '"></span>');
                    }
                }
            }
        }   
        
        //add corners to top and bottom menu items
        this.list.find('li:last').addClass("ui-corner-bottom");
        if(o.style == 'popup'){ this.list.find('li:first').addClass("ui-corner-top"); }
        
        //transfer classes to selectmenu and list
        if(o.transferClasses){
            var transferClasses = this.element.attr('class') || ''; 
            this.newelement.add(this.list).addClass(transferClasses);
        }
        
        //original selectmenu width
        var selectWidth = this.element.width();
        
        //set menu button width
        this.newelement.width( (o.width) ? o.width : selectWidth);
        
        //set menu width to either menuWidth option value, width option value, or select width 
        if(o.style == 'dropdown'){ this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width : selectWidth)); }
        else { this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width - o.handleWidth : selectWidth - o.handleWidth)); }   
        
        //set max height from option 
        if(o.maxHeight && o.maxHeight < this.list.height()){ this.list.height(o.maxHeight); }   
        
        //save reference to actionable li's (not group label li's)
        this._optionLis = this.list.find('li:not(.'+ self.widgetBaseClass +'-group)');
                
        //transfer menu click to menu button
        this.list
            .keydown(function(event){
                var ret = true;
                switch (event.keyCode) {
                    case $.ui.keyCode.UP:
                    case $.ui.keyCode.LEFT:
                        ret = false;
                        self._moveFocus(-1);
                        break;
                    case $.ui.keyCode.DOWN:
                    case $.ui.keyCode.RIGHT:
                        ret = false;
                        self._moveFocus(1);
                        break;  
                    case $.ui.keyCode.HOME:
                        ret = false;
                        self._moveFocus(':first');
                        break;  
                    case $.ui.keyCode.PAGE_UP:
                        ret = false;
                        self._scrollPage('up');
                        break;  
                    case $.ui.keyCode.PAGE_DOWN:
                        ret = false;
                        self._scrollPage('down');
                        break;
                    case $.ui.keyCode.END:
                        ret = false;
                        self._moveFocus(':last');
                        break;          
                    case $.ui.keyCode.ENTER:
                    case $.ui.keyCode.SPACE:
                        ret = false;
                        self.close(event,true);
                        $(event.target).parents('li:eq(0)').trigger('mouseup');
                        break;      
                    case $.ui.keyCode.TAB:
                        ret = true;
                        self.close(event,true);
                        break;  
                    case $.ui.keyCode.ESCAPE:
                        ret = false;
                        self.close(event,true);
                        break;  
                    default:
                        ret = false;
                        self._typeAhead(event.keyCode,'focus');
                        break;      
                }
                return ret;
            });
            
        //selectmenu style
        if(o.style == 'dropdown'){
            this.newelement
                .addClass(self.widgetBaseClass+"-dropdown");
            this.list
                .addClass(self.widgetBaseClass+"-menu-dropdown");   
        }
        else {
            this.newelement
                .addClass(self.widgetBaseClass+"-popup");
            this.list
                .addClass(self.widgetBaseClass+"-menu-popup");  
        }
        
        //append status span to button
        this.newelement.prepend('<span class="'+self.widgetBaseClass+'-status">'+ selectOptionData[this._selectedIndex()].text +'</span>');
        
        //hide original selectmenu element
        this.element.hide();
        
        //transfer disabled state
        if(this.element.attr('disabled') == true){ this.disable(); }
        
        //update value
        this.value(this._selectedIndex());
    },
    destroy: function() {
        this.element.removeData(this.widgetName)
            .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
            .removeAttr('aria-disabled');
    
        //unbind click on label, reset its for attr
        $('label[for='+this.newelement.attr('id')+']')
            .attr('for',this.element.attr('id'))
            .unbind('click');
        this.newelement.remove();
        this.list.remove();
        this.element.show();    
    },
    _typeAhead: function(code, eventType){
        var self = this;
        //define self._prevChar if needed
        if(!self._prevChar){ self._prevChar = ['',0]; }
        var C = String.fromCharCode(code);
        c = C.toLowerCase();
        var focusFound = false;
        function focusOpt(elem, ind){
            focusFound = true;
            $(elem).trigger(eventType);
            self._prevChar[1] = ind;
        };
        this.list.find('li a').each(function(i){    
            if(!focusFound){
                var thisText = $(this).text();
                if( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){
                        if(self._prevChar[0] == C){
                            if(self._prevChar[1] < i){ focusOpt(this,i); }  
                        }
                        else{ focusOpt(this,i); }   
                }
            }
        });
        this._prevChar[0] = C;
    },
    _uiHash: function(){
        return {
            value: this.value()
        };
    },
    open: function(event){
        var self = this;
        var disabledStatus = this.newelement.attr("aria-disabled");
        if(disabledStatus != 'true'){
            this._refreshPosition();
            this._closeOthers(event);
            this.newelement
                .addClass('ui-state-active');
            
            this.list
                .appendTo('body')
                .addClass(self.widgetBaseClass + '-open')
                .attr('aria-hidden', false)
                .find('li:not(.'+ self.widgetBaseClass +'-group):eq('+ this._selectedIndex() +') a')[0].focus();    
            if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-all').addClass('ui-corner-top'); } 
            this._refreshPosition();
            this._trigger("open", event, this._uiHash());
        }
    },
    close: function(event, retainFocus){
        if(this.newelement.is('.ui-state-active')){
            this.newelement
                .removeClass('ui-state-active');
            this.list
                .attr('aria-hidden', true)
                .removeClass(this.widgetBaseClass+'-open');
            if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all'); }
            if(retainFocus){this.newelement[0].focus();}    
            this._trigger("close", event, this._uiHash());
        }
    },
    change: function(event) {
        this.element.trigger('change');
        this._trigger("change", event, this._uiHash());
    },
    select: function(event) {
        this._trigger("select", event, this._uiHash());
    },
    _closeOthers: function(event){
        $('.'+ this.widgetBaseClass +'.ui-state-active').not(this.newelement).each(function(){
            $(this).data('selectelement').selectmenu('close',event);
        });
        $('.'+ this.widgetBaseClass +'.ui-state-hover').trigger('mouseout');
    },
    _toggle: function(event,retainFocus){
        if(this.list.is('.'+ this.widgetBaseClass +'-open')){ this.close(event,retainFocus); }
        else { this.open(event); }
    },
    _formatText: function(text){
        return this.options.format ? this.options.format(text) : text;
    },
    _selectedIndex: function(){
        return this.element[0].selectedIndex;
    },
    _selectedOptionLi: function(){
        return this._optionLis.eq(this._selectedIndex());
    },
    _focusedOptionLi: function(){
        return this.list.find('.'+ this.widgetBaseClass +'-item-focus');
    },
    _moveSelection: function(amt){
        var currIndex = parseInt(this._selectedOptionLi().data('index'), 10);
        var newIndex = currIndex + amt;
        return this._optionLis.eq(newIndex).trigger('mouseup');
    },
    _moveFocus: function(amt){
        if(!isNaN(amt)){
            var currIndex = parseInt(this._focusedOptionLi().data('index'), 10);
            var newIndex = currIndex + amt;
        }
        else { var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10); }
        
        if(newIndex < 0){ newIndex = 0; }
        if(newIndex > this._optionLis.size()-1){
            newIndex =  this._optionLis.size()-1;
        }
        var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);
        
        this._focusedOptionLi().find('a:eq(0)').attr('id','');
        this._optionLis.eq(newIndex).find('a:eq(0)').attr('id',activeID)[0].focus();
        this.list.attr('aria-activedescendant', activeID);
    },
    _scrollPage: function(direction){
        var numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight());
        numPerPage = (direction == 'up') ? -numPerPage : numPerPage;
        this._moveFocus(numPerPage);
    },
    _setData: function(key, value) {
        this.options[key] = value;
        if (key == 'disabled') {
            this.close();
            this.element
                .add(this.newelement)
                .add(this.list)
                    [value ? 'addClass' : 'removeClass'](
                        this.widgetBaseClass + '-disabled' + ' ' +
                        this.namespace + '-state-disabled')
                    .attr("aria-disabled", value);
        }
    },
    value: function(newValue) {
        if (arguments.length) {
            this.element[0].selectedIndex = newValue;
            this._refreshValue();
            this._refreshPosition();
        }
        return this.element[0].selectedIndex;
    },
    _refreshValue: function() {
        var activeClass = (this.options.style == "popup") ? " ui-state-active" : "";
        var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);
        //deselect previous
        this.list
            .find('.'+ this.widgetBaseClass +'-item-selected')
            .removeClass(this.widgetBaseClass + "-item-selected" + activeClass)
            .find('a')
            .attr('aria-selected', 'false')
            .attr('id', '');
        //select new
        this._selectedOptionLi()
            .addClass(this.widgetBaseClass + "-item-selected"+activeClass)
            .find('a')
            .attr('aria-selected', 'true')
            .attr('id', activeID);
            
        //toggle any class brought in from option
        var currentOptionClasses = this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : "";
        var newOptionClasses = this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : "";
        this.newelement
            .removeClass(currentOptionClasses)
            .data('optionClasses', newOptionClasses)
            .addClass( newOptionClasses )
            .find('.'+this.widgetBaseClass+'-status')
            .html( 
                this._selectedOptionLi()
                    .find('a:eq(0)')
                    .html() 
            );
            
        this.list.attr('aria-activedescendant', activeID)
    },
    _refreshPosition: function(){   
        //set left value
        this.list.css('left', this.newelement.offset().left);
        
        //set top value
        var menuTop = this.newelement.offset().top;
        var scrolledAmt = this.list[0].scrollTop;
        this.list.find('li:lt('+this._selectedIndex()+')').each(function(){
            scrolledAmt -= $(this).outerHeight();
        });
        
        if(this.newelement.is('.'+this.widgetBaseClass+'-popup')){
            menuTop+=scrolledAmt; 
            this.list.css('top', menuTop); 
        }   
        else { 
            menuTop += this.newelement.height();
            this.list.css('top', menuTop); 
        }
    }
});

$.extend($.ui.selectmenu, {
    getter: "value",
    version: "@VERSION",
    eventPrefix: "selectmenu",
    defaults: {
        transferClasses: true,
        style: 'popup', 
        width: null, 
        menuWidth: null, 
        handleWidth: 26, 
        maxHeight: null,
        icons: null, 
        format: null
    }
});

})(jQuery);

/* Turkish initialisation for the jQuery UI date picker plugin. */
/* Written by Izzet Emre Erkan (kara@karalamalar.net). */
$(function($){
	$.datepicker.regional['tr'] = {
		closeText: 'kapat',
		prevText: '&#x3c;geri',
		nextText: 'ileri&#x3e',
		currentText: 'bugün',
		monthNames: ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran',
		'Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'],
		monthNamesShort: ['Oca','Şub','Mar','Nis','May','Haz',
		'Tem','Ağu','Eyl','Eki','Kas','Ara'],
		dayNames: ['Pazar','Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi'],
		dayNamesShort: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
		dayNamesMin: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
		weekHeader: 'Hf',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['tr']);
});

/*
 * jQuery UI Spinner @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Spinner
 *
 * Depends:
 *  jquery.ui.core.js
 *  jquery.ui.widget.js
 */
(function($) {

$.widget('ui.spinner', {
	defaultElement: "<input>",
	options: {
		incremental: true,
		max: null,
		min: null,
		numberformat: null,
		page: 10,
		step: null,
		value: null
	},
	
	_create: function() {
		this._draw();
		this._markupOptions();
		this._mousewheel();
		this._aria();
	},
	
	_markupOptions: function() {
		var _this = this;
		$.each({
			min: -Number.MAX_VALUE,
			max: Number.MAX_VALUE,
			step: 1
		}, function(attr, defaultValue) {
			if (_this.options[attr] === null) {
				var value = _this.element.attr(attr);
				_this.options[attr] = typeof value == "string" && value.length > 0 ? _this._parse(value) : defaultValue;
			}
		});
		this.value(this.options.value !== null ? this.options.value : this.element.val() || 0);
	},
	
	_draw: function() {
		var self = this,
			options = self.options;

		var uiSpinner = this.uiSpinner = self.element
			.addClass('ui-spinner-input')
			.attr('autocomplete', 'off')
			.wrap(self._uiSpinnerHtml())
			.parent()
				// add buttons
				.append(self._buttonHtml())
				// add behaviours
				.hover(function() {
					if (!options.disabled) {
						$(this).addClass('ui-state-hover');
					}
					self.hovered = true;
				}, function() {
					$(this).removeClass('ui-state-hover');
					self.hovered = false;
				});

		this.element
			.attr( "role", "spinbutton" )
			.bind('keydown.spinner', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self._start(event)) {
					return self._keydown(event);
				}
				return true;
			})
			.bind('keyup.spinner', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self.spinning) {
					self._stop(event);
					self._change(event);					
				}
			})
			.bind('focus.spinner', function() {
				uiSpinner.addClass('ui-state-active');
				self.focused = true;
			})
			.bind('blur.spinner', function(event) {
				self.value(self.element.val());
				if (!self.hovered) {
					uiSpinner.removeClass('ui-state-active');
				}		
				self.focused = false;
			});

		// button bindings
		this.buttons = uiSpinner.find('.ui-spinner-button')
			.attr("tabIndex", -1)
			.button()
			.removeClass("ui-corner-all")
			.bind('mousedown', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self._start(event) === false) {
					return false;
				}
				self._repeat(null, $(this).hasClass('ui-spinner-up') ? 1 : -1, event);
			})
			.bind('mouseup', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self.spinning) {
					self._stop(event);
					self._change(event);					
				}
			})
			.bind("mouseenter", function() {
				if (self.options.disabled) {
					return;
				}
				// button will add ui-state-active if mouse was down while mouseleave and kept down
				if ($(this).hasClass("ui-state-active")) {
					if (self._start(event) === false) {
						return false;
					}
					self._repeat(null, $(this).hasClass('ui-spinner-up') ? 1 : -1, event);
				}
			})
			.bind("mouseleave", function() {
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			});
					
		// disable spinner if element was already disabled
		if (options.disabled) {
			this.disable();
		}
	},
	
	_keydown: function(event) {
		var o = this.options,
			KEYS = $.ui.keyCode;

		switch (event.keyCode) {
		case KEYS.UP:
			this._repeat(null, 1, event);
			return false;
		case KEYS.DOWN:
			this._repeat(null, -1, event);
			return false;
		case KEYS.PAGE_UP:
			this._repeat(null, this.options.page, event);
			return false;
		case KEYS.PAGE_DOWN:
			this._repeat(null, -this.options.page, event);
			return false;
			
		case KEYS.ENTER:
			this.value(this.element.val());
		}
		
		return true;
	},
	
	_mousewheel: function() {
		// need the delta normalization that mousewheel plugin provides
		if (!$.fn.mousewheel) {
			return;
		}
		var self = this;
		this.element.bind("mousewheel.spinner", function(event, delta) {
			if (self.options.disabled) {
				return;
			}
			if (!self.spinning && !self._start(event)) {
				return false;
			}
			self._spin((delta > 0 ? 1 : -1) * self.options.step, event);
			clearTimeout(self.timeout);
			self.timeout = setTimeout(function() {
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			}, 100);
			event.preventDefault();
		});
	},
	
	_uiSpinnerHtml: function() {
		return '<span class="ui-spinner ui-state-default ui-widget ui-widget-content ui-corner-all"></span>';
	},
	
	_buttonHtml: function() {
		return '<a class="ui-spinner-button ui-spinner-up ui-corner-tr"><span class="ui-icon ui-icon-triangle-1-n">&#9650;</span></a>' +
				'<a class="ui-spinner-button ui-spinner-down ui-corner-br"><span class="ui-icon ui-icon-triangle-1-s">&#9660;</span></a>';
	},
	
	_start: function(event) {
		if (!this.spinning && this._trigger('start', event) !== false) {
			if (!this.counter) {
				this.counter = 1;
			}
			this.spinning = true;
			return true;
		}
		return false;
	},
	
	_repeat: function(i, steps, event) {
		var self = this;
		i = i || 500;

		clearTimeout(this.timer);
		this.timer = setTimeout(function() {
			self._repeat(40, steps, event);
		}, i);
		
		self._spin(steps * self.options.step, event);
	},
	
	_spin: function(step, event) {
		if (!this.counter) {
			this.counter = 1;
		}
		
		// TODO refactor, maybe figure out some non-linear math
		var newVal = this.value() + step * (this.options.incremental &&
			this.counter > 20
				? this.counter > 100
					? this.counter > 200
						? 100 
						: 10
					: 2
				: 1);
		
		if (this._trigger('spin', event, { value: newVal }) !== false) {
			this.value(newVal);
			this.counter++;			
		}
	},
	
	_stop: function(event) {
		this.counter = 0;
		if (this.timer) {
			window.clearTimeout(this.timer);
		}
		this.element[0].focus();
		this.spinning = false;
		this._trigger('stop', event);
	},
	
	_change: function(event) {
		this._trigger('change', event);
	},
	
	_setOption: function(key, value) {
		if (key == 'value') {
			value = this._parse(value);
			if (value < this.options.min) {
				value = this.options.min;
			}
			if (value > this.options.max) {
				value = this.options.max;
			}
		}
		if (key == 'disabled') {
			if (value) {
				this.element.attr("disabled", true);
				this.buttons.button("disable");
			} else {
				this.element.removeAttr("disabled");
				this.buttons.button("enable");
			}
		}
		// TODO see below
		//this._super( "_setOption", key, value );
		$.Widget.prototype._setOption.apply( this, arguments );
	},
	
	_setOptions: function( options ) {
		// TODO _super doesn't handle inheritance with more then one subclass
		// spinner subclass will have spinner as base, calling spinner._setOptions infinitely
		//this._super( "_setOptions", options );
		$.Widget.prototype._setOptions.apply( this, arguments );
		if ( "value" in options ) {
			this._format( this.options.value );
		}
		this._aria();
	},
	
	_aria: function() {
		this.element
			.attr('aria-valuemin', this.options.min)
			.attr('aria-valuemax', this.options.max)
			.attr('aria-valuenow', this.options.value);
	},
	
	_parse: function(val) {
		var input = val;
		if (typeof val == 'string') {
			val = $.global && this.options.numberformat ? $.global.parseFloat(val) : +val;
		}
		return isNaN(val) ? null : val;
	},
	
	_format: function(num) {
		this.element.val( $.global && this.options.numberformat ? $.global.format(num, this.options.numberformat) : num );
	},
		
	destroy: function() {
		this.element
			.removeClass('ui-spinner-input')
			.removeAttr('disabled')
			.removeAttr('autocomplete')
			.removeAttr('role')
			.removeAttr('aria-valuemin')
			.removeAttr('aria-valuemax')
			.removeAttr('aria-valuenow');
		//this._super( "destroy" );
		this.uiSpinner.replaceWith(this.element);
	},
	
	stepUp: function(steps) {
		this._spin((steps || 1) * this.options.step);
	},
	
	stepDown: function(steps) {
		this._spin((steps || 1) * -this.options.step);	
	},
	
	pageUp: function(pages) {
		this.stepUp((pages || 1) * this.options.page);		
	},
	
	pageDown: function(pages) {
		this.stepDown((pages || 1) * this.options.page);		
	},
	
	value: function(newVal) {
		if (!arguments.length) {
			return this._parse(this.element.val());
		}
		this.option('value', newVal);
	},
	
	widget: function() {
		return this.uiSpinner;
	}
});
$.ui.spinner.version = "@VERSION";
})(jQuery);

/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * 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.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.4
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },
    
    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },
    
    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});


function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";
    
    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }
    
    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;
    
    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }
    
    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
    
    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);
    
    return $.event.handle.apply(this, args);
}

})(jQuery);


