(function($){
		//bottom position
		$.fn.offsetBottom = function() {	
			var h = $(this).outerHeight();	
			var dh = $(document).height();
			var offset = $(this).offset();
			return dh - offset.top - h;
	    };
})(jQuery);

(function($){
	var visibleDD = null;
	var methods = {
		init : function( options ) {



			return this.each(function(){

				if (this.tagName.toUpperCase() == 'SELECT') {

					var $this = $(this),
					data = $this.data('customSelect'),
					getText = typeof options != "undefined" && typeof options.formatItem == "function" ? options.formatItem : function(text) { return text; },
					getListText = typeof options != "undefined" && typeof options.formatListItem == "function" ? options.formatListItem : function(text) { return text; },
					onChange = typeof options != "undefined" && typeof options.onChange == "function" ? options.onChange : function(value) { },
					link = $('<a/>', {
						href: '#',
						html: getText($('option:selected', this).text()),
						'class': $('option:selected', this).attr('class')
					}).addClass('custom-select').addClass($(this).attr('class')),
					listData = [],
					selected = null;

					var dropdown = $('<ul></ul>').hide().addClass('custom-select');

					$('option', this).each(function(i, v){
						var value = $(v).attr('value'),
						    text = $(v).text(),
							cName = $(v).attr('class');
						listData.push({
							title: text,
							value: (typeof value !== 'undefined' && value !== false ? value : text),
							className: (typeof cName !== 'undefined' && cName !== false ? cName : ''),
							element : v
						});
					});

					var setDropdownPos = function () {
						var pos = link.position(),
							h = link.outerHeight(),
							w = link.outerWidth() - parseInt(link.css('border-left-width')) - parseInt(link.css('border-right-width'));
						var ob = link.offsetBottom();
						var ddH = dropdown.outerHeight();
						if (ddH > 150) {
							ddH = 150;	
							dropdown.css({'overflow-y':'auto','overflow-x':'hidden','height':'150px'});
						}
						if ( ob < ddH ) {	
							dropdown.css({position:'absolute',left: pos.left + 'px', bottom: (ob + h) + 'px', top: 'auto', 'min-width': w + 'px'});
						} else {
							dropdown.css({position:'absolute',left: pos.left + 'px', top: (pos.top + h) + 'px', bottom: 'auto', 'min-width': w + 'px'});
						}
					};

					var selectElement = function(data){
						link.html(getText(data.title)).addClass(data.className);
						setDropdownPos();
					};

					
					$.each(listData, function(i, v){
						var li = $('<li>'+ getListText(v.title) +'</li>');
							li.attr('class', v.className).data('customSelect', v);
						if (i == 0) {
							li.addClass('first');
						}
						dropdown.append(li);

						if ($(v.element).is(':selected')) {
							$(li).addClass('custom-select-selected');
							selected = $(li);
							//$(link).addClass('first');
							
							if (v.value == 0) {
								$(link).addClass('first');
							}
						}

						li.click(function(e){
							e.preventDefault();
							e.stopPropagation();

							if (selected) {
								selected.removeClass('custom-select-selected');
								link.removeClass(selected.data('customSelect').className);
							}

							$(this).addClass('custom-select-selected');
							selected = $(this);
							selectElement($(this).data('customSelect'));
							$this.val($(this).data('customSelect').value);
							if ($(this).data('customSelect').value == 0) {
								$(link).addClass('first');
							} else {
								$(link).removeClass('first');
							}
							onChange.apply( $this );
							methods.hideList.apply( $this );
						});
					});

					
					$('html, body').bind('click', function(){
						methods.hideList.apply( $this );
					}); 

					$this.before(link).before(dropdown).hide();
					setDropdownPos();
					link.click(function(e){
						e.preventDefault();
						e.stopPropagation();
						setDropdownPos();
						methods.toggleList.apply( $this );
					});

					$(this).data('customSelect', {
						target : $this,
						dropdown : dropdown
					}); 

				} //select tag
			});
		},
		destroy : function( ) {

			return this.each(function(){

				var $this = $(this),
				data = $this.data('tooltip');

				// Namespacing FTW
				$(window).unbind('.tooltip');
				data.tooltip.remove();
				$this.removeData('tooltip');

			})

		},
		showList : function( ) {
			if (visibleDD && visibleDD != $(this).data('customSelect').dropdown) {
				visibleDD.slideUp();
			}
			$(this).data('customSelect').dropdown.slideDown('fast');
			visibleDD = $(this).data('customSelect').dropdown;
		},
		hideList : function( ) {
			if ($(this).data('customSelect')) {
				$(this).data('customSelect').dropdown.slideUp('fast', function() { $(this).css({'overflow-y':'auto','overflow-x':'hidden','height':'auto'}); });
			}
		},
		toggleList : function( ) {
			if ($(this).data('customSelect').dropdown.is(':visible')) {
				methods.hideList.apply( this );
			} else {
				methods.showList.apply( this );
			}
		},
		value: function () {
			return $($(this).data('customSelect').target).val();
		},
		setValues: function (values) {
			
			var dd = $(this).data('customSelect').dropdown;
			$('li', dd).each(function(){
				var val = $(this).data('customSelect').value;
				if (val != 0 && val != "0") {
					if (typeof values[val] != 'undefined') {
						$(this).show();
					} else {
						$(this).hide();
					}
				}
			});

		}
	};

	$.fn.customSelect = function( method ) {

		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.customSelect' );
		}

	};


})(jQuery);
