var jqkit_seq_id = 1;

function msgBox(options)
{
		var defaults = {
				msg:'',
				type:''
		}

		var opts = $.extend({}, defaults, options);
		var className = '';
		var title = '';

		switch(opts.type)
		{
				case 'alert':
						title = 'Warning';
						className = 'jqkit_window_alert';
						break;
				case 'info':
						title = 'Information';
						className = 'jqkit_window_info';
						break;
				case 'error':
						title = 'Error';
						className = 'jqkit_window_error';
						break;
				case 'wait':
						title = 'Please Wait';
						className = 'jqkit_window_wait';
						break;
				default:
						title = 'Message';
						className = 'jqkit_window_blank';
						break;
		}

		makeWindow(
				{
						title:title,
						width:opts.width,
						content:'<div align="left" class="' + className + '">'+ opts.msg + '</div>'
				}
		);

}
/*
function makeWindow(options)
{
		//constants
		var buttonAreaHeight = 40;
		var titleAreaHeight = 32;
		var bottomEdgeHeight = 5;
		var leftEdgeWidth = 7;
		var rightEdgeWidth = 7;
		var windowMinWidth = 180;
		var windowMinHeight = titleAreaHeight + buttonAreaHeight + bottomEdgeHeight;// + 40;

		var defaults = {
				id:false,
				modal:true,
				buttons:'OK',
				success:function() {return true;},
				cancel:false,
				width:180,
				height:120,
				left:false,
				top:false,
				anchor:true,
				draggable:true,
				resizable:false,
				closeable:true,
				title:'',
				content:'',
				fitWidth:true,
				fitHeight:true,
				contentWidth:977 //width of body content area, to discount any unused area on the left, caused by wide screens
		}

		var opts = $.extend({}, defaults, options);

		if(!opts.id)
		{
				opts.id = 'jqkit_window' + jqkit_seq_id;
				jqkit_seq_id++;
		}

		var height = 0;
		var innerHeight = 0;

		var height = opts.height;
		var innerHeight = height - titleAreaHeight - bottomEdgeHeight;

		if(opts.buttons)
				height += buttonAreaHeight;

		if(height < windowMinHeight)
				height = windowMinHeight;


		var width = opts.width;
		var innerWidth = width - leftEdgeWidth - rightEdgeWidth;

		if(width < windowMinWidth)
				width = windowMinWidth;


		if(opts.fitWidth && $(opts.content).outerWidth() > innerWidth)
		{
				innerWidth = $(opts.content).outerWidth();
				width = innerWidth + leftEdgeWidth + rightEdgeWidth;
		}

		if(opts.fitHeight && $(opts.content).outerHeight() > innerHeight)
		{
				innerHeight = $(opts.content).outerHeight();
				height = innerHeight + titleAreaHeight + bottomEdgeHeight;

				if(opts.buttons)
						height += buttonAreaHeight;
		}


		var left = 0;
		var top = 0;


		if(opts.left && opts.top)
		{
				left = opts.left + (($(window).width() - opts.contentWidth) / 2);
				top = opts.top;
		}
		else
		{
				left = ($(window).width() / 2) - (width / 2);
				top =  ($(window).height() / 2) - (height / 2);
		}

		var html = '<div id="'+ opts.id +'" class="jqkit_window';

		if(opts.anchor)
		{
				html += ' jqkit_anchored" vv="' + (left - ($(window).width() - opts.contentWidth) / 2) + '"';
		}
		else
		{
				html += '"';
		}

		html += ' style="left:' + left + 'px;top:' + top + 'px;">'; //width:' + width + 'px">';

		html += '<div id="' + opts.id + '_handle' + '"><div style="background-image:url(/jqkit/assets/window/nw.png);background-repeat:no-repeat;width:7px;height:32px;float:left"></div>';

		html += '<div ';

		if(opts.draggable)
		{
				html += ' class="jqkit_window_handle" ';
		}

		html += 'style="float:left;width:' + innerWidth + 'px;height:32px;background-color:#C1D0E1"><div class="jqkit_window_title">' + opts.title + '</div>';

		if(opts.closeable)
		{
				html += '<div id="' + opts.id + '_close" class="jqkit_window_control jqkit_window_control_close"></div>';
		}


		html += '</div><div style="background-image:url(/jqkit/assets/window/ne.png);background-repeat:no-repeat;width:7px;height:32px;float:left"></div></div>';


		html += '<div><div style="float:left;width:7px;height:' + innerHeight + 'px;background-color:#C1D0E1"></div><div style="float:left;width:' + innerWidth + 'px;height:' + innerHeight + 'px;background-color:#FFF"><div style="padding:3px">' + opts.content + '</div></div><div style="float:left;width:7px;height:' + innerHeight + 'px;background-image:url(/jqkit/assets/window/e.png)"></div>';

		if(opts.buttons)
		{
				html += '<div><div style="float:left;width:7px;height:40px;background-color:#C1D0E1"></div><div align="center" style="float:left;width:' + innerWidth + 'px;height:40px;background-color:#C1D0E1">';

				switch(opts.buttons)
				{
						case 'YESNO':
								html += '<button id="'+ opts.id +'_success" class="jqkit_window_button">Yes</button> <button id="'+ opts.id + '_cancel" class="jqkit_window_button">No</button>';
								break;
						case 'OK':
								html += '<button id="'+ opts.id +'_success" class="jqkit_window_button">OK</button>';
								break;
						case 'OKCANCEL':
								html += '<button id="'+ opts.id +'_success" class="jqkit_window_button">OK</button> <buttonid="'+ opts.id + '_cancel" class="jqkit_window_button">Cancel</button>';
								break;
						case 'SAVECANCEL':
								html += '<button id="'+ opts.id +'_success" class="jqkit_window_button">Save</button> <buttonid="'+ opts.id + '_cancel" class="jqkit_window_button">Cancel</button>';
								break;
				}

				html += '</div><div style="float:left;width:7px;height:40px;background-image:url(/jqkit/assets/window/e.png)"></div></div>';
		}

		html += '</div><div style="clear:both"><div style="background-image:url(/jqkit/assets/window/ssw.png);background-repeat:no-repeat;width:7px;height:5px;float:left"></div><div style="float:left;width:' + innerWidth + 'px;height:5px;background-image:url(/jqkit/assets/window/ss.png)"></div><div style="background-image:url(/jqkit/assets/window/sse.png);background-repeat:no-repeat;width:7px;height:5px;float:left"></div></div></div>';

		if(opts.modal)
		{
				$('body').append('<div id="' + opts.id + '_overlay" class="jqkit_overlay" style="top:0;left:0;width:' + $(document).width() + 'px;height:' + $(document).height() + 'px"></div>');
		}

		$('body').append(html);


		if(opts.buttons)
		{
				$('#'+ opts.id + '_success').click(
						function()
						{
								if(opts.success)
								{
										if(opts.success())
										{
												windowClose(opts.id);
										}
										else
										{
												$(this).blur();
										}
								}
								else
								{
										windowClose(opts.id);
								}
						}
				).focus();


				$('#' + opts.id + '_cancel').click(
						function()
						{
								windowHide(opts.id);
								if(opts.cancel) opts.cancel();
								windowClose(opts.id);
						}
				).focus();
		}

		if(opts.closeable)
		{

				$('#' + opts.id + '_close').click(
						function()
						{
								windowHide(opts.id);
								if(opts.cancel) opts.cancel();
								windowClose(opts.id);
						}
				);
		}

		if(opts.draggable)
		{
				$('#'+ opts.id).draggable({cursor:'move',handle:'#'+ opts.id + '_handle'});
		}

		$(window).bind('resize.jqkit_window',
		    function()
		    {
		        $('#' + opts.id + '_overlay').css('width',$(document).width() + 'px');
		        $('#' + opts.id + '_overlay').css('height',$(document).height() + 'px');

						if($('#' + opts.id).hasClass('jqkit_anchored'))
						{
								var left = Number($('#' + opts.id).attr('vv')) + (($(window).width() - 977) / 2);
								$('#' + opts.id).css('left',left + 'px');
						}
		    }
		);
}
*/

function makeWindow(options)
{
		//constants
		var buttonAreaHeight = 40;
		var titleAreaHeight = 32;
		var bottomEdgeHeight = 5;
		var leftEdgeWidth = 7;
		var rightEdgeWidth = 7;
		var windowMinWidth = 260;
		var windowMinHeight = 70;

		var defaults = {
				id:false,
				modal:true,
				buttons:'OK',
				success:function() {return true;},
				cancel:false,
				width:false,
				height:false,
				left:false,
				top:false,
				anchor:true,
				draggable:true,
				resizable:false,
				closeable:true,
				title:'',
				content:'',
				contentWidth:977 //width of body content area, to discount any unused area on the left, caused by wide screens
		}

		var opts = $.extend({}, defaults, options);

		if(!opts.id)
		{
				opts.id = 'jqkit_window' + jqkit_seq_id;
				jqkit_seq_id++;
		}

		var height = 0;
		var innerHeight = 0;
		var width = 0;
		var innerWidth = 0;

		if(opts.width)
		{
				width = opts.width;
				innerWidth = width - leftEdgeWidth - rightEdgeWidth;
		}
		else
		{
				$('#temp').remove();
				$('body').append('<div id="temp" style="display:none">' + opts.content + '</div>');
				innerWidth = $('#temp').width();
				width = innerWidth + leftEdgeWidth + rightEdgeWidth;
		}

		if(innerWidth < windowMinWidth)
		{
				innerWidth = windowMinWidth;
				width = innerWidth + leftEdgeWidth + rightEdgeWidth;
		}

		if(opts.height)
		{
				height = opts.height;
				innerHeight = height - titleAreaHeight - bottomEdgeHeight;
		}
		else
		{
				$('#temp').remove();
				$('body').append('<div id="temp" style="display:none">' + opts.content + '</div>');
				innerHeight = $('#temp').height();
				height = innerHeight + titleAreaHeight + bottomEdgeHeight + 10;
		}

		if(opts.buttons)
				height += buttonAreaHeight;

		if(innerHeight < windowMinHeight)
		{
				innerHeight = windowMinHeight;
				height = innerHeight + titleAreaHeight + bottomEdgeHeight + 10;
		}

		var left = 0;
		var top = 0;


		if(opts.left && opts.top)
		{
				left = opts.left + (($(window).width() - opts.width) / 2);
				top = opts.top;
		}
		else
		{
				left = ($(window).width() / 2) - (width / 2);
				top =  ($(window).height() / 2) - (height / 2);
		}

		var html = '<div id="'+ opts.id +'" class="jqkit_window';

		if(opts.anchor)
		{
				html += ' jqkit_anchored" vv="' + (left - ($(window).width() - opts.contentWidth) / 2) + '"';
		}
		else
		{
				html += '"';
		}

		html += ' style="left:' + left + 'px;top:' + top + 'px;width:' + width + 'px;">';

		html += '<div id="' + opts.id + '_handle' + '">' +
                    '<div style="background-image:url(/jqkit/assets/window/nw.png);background-repeat:no-repeat;width:7px;height:32px;float:left"></div>';

		html += '<div ';

		if(opts.draggable)
		{
				html += ' class="jqkit_window_handle" ';
		}

		html += 'style="float:left;width:' + innerWidth + 'px;height:32px;background-color:#C1D0E1">' +
                '<div class="jqkit_window_title">' + opts.title + '</div>';

		if(opts.closeable)
		{
				html += '<div id="' + opts.id + '_close" class="jqkit_window_control jqkit_window_control_close"></div>';
		}


		html += '</div>' +
                '<div style="background-image:url(/jqkit/assets/window/ne.png);background-repeat:no-repeat;width:7px;height:32px;float:left"></div></div>';


		html += '<div>'+
                    '<div style="float:left;width:7px;height:' + innerHeight + 'px;background-color:#C1D0E1"></div>' +
                    '<div id="' + opts.id + '_innerContent" style="float:left;width:' + innerWidth + 'px;height:' + innerHeight + 'px;background-color:#FFF">' +
                        '<div style="padding:3px">' + opts.content + '</div>' +
                    '</div>' +
                    '<div style="float:left;width:7px;height:' + innerHeight + 'px;background-image:url(/jqkit/assets/window/e.png)"></div>';

		if(opts.buttons)
		{
				html += '<div>' +
                            '<div style="float:left;width:7px;height:40px;background-color:#C1D0E1"></div>' +
                            '<div align="center" style="float:left;width:' + innerWidth + 'px;height:40px;background-color:#C1D0E1">';

				switch(opts.buttons)
				{
						case 'YESNO':
								html += '<button id="'+ opts.id +'_success" class="jqkit_window_button">Yes</button> <button id="'+ opts.id + '_cancel" class="jqkit_window_button">No</button>';
								break;
						case 'OK':
								html += '<button id="'+ opts.id +'_success" class="jqkit_window_button">OK</button>';
								break;
						case 'OKCANCEL':
								html += '<button id="'+ opts.id +'_success" class="jqkit_window_button">OK</button> <buttonid="'+ opts.id + '_cancel" class="jqkit_window_button">Cancel</button>';
								break;
						case 'SAVECANCEL':
								html += '<button id="'+ opts.id +'_success" class="jqkit_window_button">Save</button> <buttonid="'+ opts.id + '_cancel" class="jqkit_window_button">Cancel</button>';
								break;
				}

				html +=     '</div>' +
                            '<div style="float:left;width:7px;height:40px;background-image:url(/jqkit/assets/window/e.png)"></div>' +
                        '</div>';
		}

		html += '</div>' +
                '<div style="clear:both"><div style="background-image:url(/jqkit/assets/window/ssw.png);background-repeat:no-repeat;width:7px;height:5px;float:left"></div>' +
                '<div style="float:left;width:' + innerWidth + 'px;height:5px;background-image:url(/jqkit/assets/window/ss.png)"></div>' +
                '<div style="background-image:url(/jqkit/assets/window/sse.png);background-repeat:no-repeat;width:7px;height:5px;float:left"></div>' +
                '</div></div>';

		if(opts.modal)
		{
				$('body').append('<div id="' + opts.id + '_overlay" class="jqkit_overlay" style="top:0;left:0;width:' + $(document).width() + 'px;height:' + $(document).height() + 'px"></div>');
		}

		$('body').append(html);


//		$('#' + opts.id + '_innerContent').width();

//		$('#' + opts.id).show();

		if(opts.buttons)
		{
				$('#'+ opts.id + '_success').click(
						function()
						{
								if(opts.success)
								{
										if(opts.success())
										{
												windowClose(opts.id);
										}
										else
										{
												$(this).blur();
										}
								}
								else
								{
										windowClose(opts.id);
								}
						}
				).focus();


				$('#' + opts.id + '_cancel').click(
						function()
						{
								windowHide(opts.id);
								if(opts.cancel) opts.cancel();
										windowClose(opts.id);
						}
				).focus();
		}

		if(opts.closeable)
		{

				$('#' + opts.id + '_close').click(
						function()
						{
								windowHide(opts.id);
								if(opts.cancel) opts.cancel();
								windowClose(opts.id);
						}
				);
		}

		if(opts.draggable)
		{
				$('#'+ opts.id).draggable({cursor:'move',handle:'#'+ opts.id + '_handle'});
		}

		$(window).bind('resize.jqkit_window',
		    function()
		    {
		        $('#' + opts.id + '_overlay').css('width',$(document).width() + 'px');
		        $('#' + opts.id + '_overlay').css('height',$(document).height() + 'px');

						if($('#' + opts.id).hasClass('jqkit_anchored'))
						{
								var left = Number($('#' + opts.id).attr('vv')) + (($(window).width() - 977) / 2);
								$('#' + opts.id).css('left',left + 'px');
						}
		    }
		);
}


function windowHide(id)
{
		$('#' + id).hide();
		$('#' + id + '_overlay').hide();
}

function windowClose(id)
{
		$('#' + id).remove();
		$('#' + id + '_overlay').remove();
}


jQuery.fn.jqkit_menu_btn = function()
{
    return this.each(function()
    {
        jQuery(this).hover(
            function()
            {
                var left = jQuery(this).offset().left - 1;
                var top = jQuery(this).offset().top + jQuery(this).outerHeight() - 6;
                jQuery(this).children('div').css({'top':top,'left':left}).slideDown('fast');
            },
            function()
            {
                jQuery(this).children('div').hide();
            }
        );
    });
};

$(function() {


$('.flyable').hover(
		function()
		{
        var left = $(this).outerWidth() + 'px';
				var top = $(this).offset().top - $(this).parent().offset().top;
        $(this).children('div').css({'top':top,'left':left}).slideDown('fast');
		},
		function()
		{
				$(this).children('div').hide();
		}
);

});


jQuery.fn.jqkit_datepicker = function(options)
{
    var opts = jQuery.extend({}, jQuery.fn.jqkit_datepicker.defaults, options);
    var selectedDate = {};
    var displayedDate = {};



    return this.each(function()
    {
    		var $dateField = jQuery(this);

		   	$dateField
		  	.addClass('jqkit_date_field')
		  	.attr('readonly','readonly')
				.click(
					function(event)
					{
							event.stopPropagation();

							$('.jqkit_dp').remove();

							var left = $dateField.position().left;
							var top = $dateField.position().top + $dateField.outerHeight();

							if(top > $(window).height() - 200)
							{
								top = $(window).height() - 200;
							}

							if(left > $(window).width() - 180)
							{
								left = $(window).width() - 180;
							}

							var textString = $dateField.attr('value');
							if(textString.length > 0)
							{
								var selected = new Date(Date.parse(textString));
							}

							if(!(selected && selected.getMonth()))
							{
								var selected = new Date;
							}

							selectedDate.year = selected.getFullYear();
							selectedDate.month = selected.getMonth();
							selectedDate.date = selected.getDate();

							displayedDate.year = selectedDate.year;
							displayedDate.month = selectedDate.month;
							displayedDate.date = selectedDate.date;



							$('body').append('<div class="jqkit_dp"><div class="jqkit_dp_inner_frame">' +
								'<div class="jqkit_dp_topbar" align="center">' +
										'<select id="jqkit_month_picker">' +
											'<option value="0">Jan</option>' +
											'<option value="1">Feb</option>' +
											'<option value="2">Mar</option>' +
											'<option value="3">Apr</option>' +
											'<option value="4">May</option>' +
											'<option value="5">Jun</option>' +
											'<option value="6">Jul</option>' +
											'<option value="7">Aug</option>' +
											'<option value="8">Sep</option>' +
											'<option value="9">Oct</option>' +
											'<option value="10">Nov</option>' +
											'<option value="11">Dec</option>' +
										'</select>' +
										'<select id="jqkit_year_picker">' +
											'<option value="2001">2001</option>' +
											'<option value="2002">2002</option>' +
											'<option value="2003">2003</option>' +
											'<option value="2004">2004</option>' +
											'<option value="2005">2005</option>' +
											'<option value="2006">2006</option>' +
											'<option value="2007">2007</option>' +
											'<option value="2008">2008</option>' +
											'<option value="2009">2009</option>' +
											'<option value="2010">2010</option>' +
											'<option value="2011">2011</option>' +
											'<option value="2012">2012</option>' +
											'<option value="2013">2013</option>' +
											'<option value="2014">2014</option>' +
											'<option value="2015">2015</option>' +
											'<option value="2016">2016</option>' +
											'<option value="2017">2017</option>' +
											'<option value="2018">2018</option>' +
											'<option value="2019">2019</option>' +
											'<option value="2020">2020</option>' +
										'</select>' +

									'<div class="jqkit_btn_left"></div>' +
									'<div class="jqkit_btn_right"></div>' +
								'</div><div class="jqkit_dp_daybar"><div>S</div><div>M</div><div>T</div><div>W</div><div>T</div><div>F</div><div>S</div></div><div class="jqkit_body"></div><div class="jqkit_dp_bottombar" align="center"><button id="jqkit_today">Today</button> &nbsp; <button id="jqkit_cancel">Cancel</button></div></div></div>');

							paintCal({year:selectedDate.year,month:selectedDate.month});

							jQuery('.jqkit_btn_right').click(
								function()
								{
									displayedDate.month++;

									if(displayedDate.month > 11)
									{
										displayedDate.month = 0;
										displayedDate.year++;
									}

									paintCal({year:displayedDate.year,month:displayedDate.month});
									$(this).blur();

								}
							);

							jQuery('.jqkit_btn_left').click(
								function()
								{

									displayedDate.month--;

									if(displayedDate.month < 0)
									{
										displayedDate.month = 11;
										displayedDate.year--;
									}

									paintCal({year:displayedDate.year,month:displayedDate.month});
									$(this).blur();

								}
							);

							$('#jqkit_year_picker').change(
								function()
								{
									displayedDate.year = $(this).val();
									paintCal({year:displayedDate.year,month:displayedDate.month});
									$(this).blur();
								}
							);

							$('#jqkit_month_picker').change(
								function()
								{
									displayedDate.month = $(this).val();
									paintCal({year:displayedDate.year,month:displayedDate.month});
									$(this).blur();
								}
							);

							$('#jqkit_today').click(
								function()
								{
									var d = new Date;
									var month = Number(d.getMonth()) + 1;
									if(month < 10) month = '0' + String(month);

									var date = Number(d.getDate());
									if(date < 10) date = '0' + String(date);

									var year = d.getFullYear();

									$dateField.val(month + '/' + date + '/' + year);

									$('.jqkit_dp').remove();
									$(document).unbind('click.jqkit_datepicker');

								}
							);

							$('#jqkit_cancel').click(
								function()
								{
										$('.jqkit_dp').remove();
										$(document).unbind('click.jqkit_datepicker');
								}
							);

							$(document).bind('click.jqkit_datepicker',
								function()
								{
									$('#jqkit_cancel').trigger('click');
								}
							);

							$('.jqkit_dp_inner_frame').click(
								function(event)
									{
										event.stopPropagation();
									}
								);

							$('.jqkit_dp').css('top',top+'px').css('left',left+'px').show();
					}
				);

		    function paintCal(data)
				{
					var months = new Array(12);
					months[0]  = "January";
					months[1]  = "February";
					months[2]  = "March";
					months[3]  = "April";
					months[4]  = "May";
					months[5]  = "June";
					months[6]  = "July";
					months[7]  = "August";
					months[8]  = "September";
					months[9]  = "October";
					months[10] = "November";
					months[11] = "December";


					var first = new Date(data.year, data.month, 1);
					var dayOffset = first.getDay();

					var monthLength = 32 - new Date(data.year, data.month, 32).getDate();

					var now = new Date;
					var nowYear = now.getFullYear();
					var nowMonth = now.getMonth();
					var nowDate = now.getDate();
					var nowString = String(nowYear);

					if(nowMonth < 10)
						nowString += '0' + String(nowMonth);
					else
						nowString += String(nowMonth);

					if(nowDate < 10)
						nowString += '0' + String(nowDate);
					else
						nowString += String(nowDate);

					var content = '';
					var counter = 1;

					for(var i = 0; i < monthLength + dayOffset; i++)
					{
						if(i >= dayOffset)
						{
							if(data.year == nowYear && data.month == nowMonth && nowDate == counter)
							{
								content += '<div class="jqkit_dp_daybox jqkit_dp_today">' + counter + '</div>';
							}
							else
							{
								if(data.year == selectedDate.year && data.month == selectedDate.month && selectedDate.date == counter)
									content += '<div class="jqkit_dp_daybox jqkit_dp_selected">' + counter + '</div>';
								else
								{
									var thisString = '';
									if(opts.disableFuture || opts.disablePast)
									{
										thisString = String(data.year);

										if(data.month < 10)
											thisString += '0' + String(data.month);
										else
											thisString += String(data.month);

										if(counter < 10)
											thisString += '0' + String(counter);
										else
											thisString += String(counter);
									}


									if(opts.disableFuture && nowString < thisString)
									{
										content += '<div class="jqkit_dp_daybox_disabled">' + counter + '</div>';
									}
									else
									{
										if(opts.disablePast && nowString > thisString)
										{
											content += '<div class="jqkit_dp_daybox_disabled">' + counter + '</div>';
										}
										else
										{
											content += '<div class="jqkit_dp_daybox">' + counter + '</div>';
										}

									}
								}

							}

							counter++;
						}
						else
						{
							content += '<div></div>';
						}

					}

					$('#jqkit_year_picker').val(data.year);
					$('#jqkit_month_picker').val(data.month);

					$('.jqkit_body').empty().append(content);

					$('.jqkit_dp_daybox').click(
						function()
						{
							var month = Number(displayedDate.month) + 1;
							if(month < 10) month = '0' + String(month);

							var date = Number($(this).html());
							if(date < 10) date = '0' + String(date);

							$dateField.val(month + '/' + date + '/' + displayedDate.year);

							$('.jqkit_dp').remove();
						}
					);

				}

    });



};



jQuery.fn.jqkit_datepicker.defaults = {
    disableFuture:false,
    disablePast:false
};


jQuery.fn.jqkit_column_head = function(options)
{
    var opts = jQuery.extend({}, jQuery.fn.jqkit_column_head.defaults, options);

    return this.each(function()
    {
        var $this = jQuery(this);

        switch(opts.initialSort)
        {
            case 'up':
                $this.attr('sort','up');
                $this.append('<img class="jqkit_sort_arrow" src="' + opts.upArrow + '" />');
                $this.removeClass('jqkit_column_head_sortable').addClass('jqkit_column_head_selected');
                break;

            case 'dn':
                $this.attr('sort','dn');
                $this.append('<img class="jqkit_sort_arrow" src="' + opts.downArrow + '" />');
                $this.removeClass('jqkit_column_head_sortable').addClass('jqkit_column_head_selected');
                break;
        }

        if(opts.sortable)
        {
            $this.addClass("jqkit_column_head").addClass("jqkit_column_head_sortable").hover(
                function()
                {
                    if(opts.showSortTip)
                    {
												$('body').append('<div class="jqkit_column_head_tooltip" align="center">Click column heading to sort table</div>');
												var top =  $this.offset().top - $('.jqkit_column_head_tooltip').outerHeight();
												var left =  $this.offset().left;
                        $('.jqkit_column_head_tooltip').css({'top':top,'left':left,'display':'block'});
                        jQuery.fn.jqkit_column_head.timer = setTimeout("$('.jqkit_column_head_tooltip').remove()",2000);
                    }
                },
                function()
                {
                    if(opts.showSortTip)
                    {
                        $('.jqkit_column_head_tooltip').remove();
                        clearTimeout(jQuery.fn.jqkit_column_head.timer);
                    }
                }
            ).click(
                function()
                {
                    $('.jqkit_sort_arrow').remove();
                    $('.jqkit_column_head_selected').removeClass('jqkit_column_head_selected').addClass('jqkit_column_head_sortable');
                    $this.removeClass('jqkit_column_head_sortable').addClass('jqkit_column_head_selected');
                    if($this.attr('sort') == 'dn')
                    {
                        $this.attr('sort','up');
                        $this.append('<img class="jqkit_sort_arrow" src="' + opts.upArrow + '" />');
                    }
                    else
                    {
                        $this.attr('sort','dn');
                        $this.append('<img class="jqkit_sort_arrow" src="' + opts.downArrow + '" />');
                    }
                }
            );

						if(opts.showSortPop)
						{
								$this.append('<img class="jqkit_drop_arrow" src="/jqkit/assets/header/drop_arrow.png" width="15" height="24" border="0" style="float:right" />')
								.append('<div class="jqkt_drop_sort_menu"><div class="jqkt_drop_sort_up_div" align="left"><img src="/jqkit/assets/header/sort_icon_dn.png" width="20" height="20" border="0" style="float:left;padding:3px" />Sort Ascending</div><div class="jqkt_drop_sort_dn_div" align="left"><img src="/jqkit/assets/header/sort_icon_up.png" width="20" height="20" border="0" style="float:left;padding:3px" />Sort Descending</div></div>');

								$this.children('.jqkit_drop_arrow').click(
										function(event)
										{
												$('.jqkt_drop_sort_menu').hide();
												var left = $(this).position().left - 111;
												if($(window).width() - left < 130) left = $(window).width() - 130;
												var top = $(this).offset().top + $(this).outerHeight();
												event.stopPropagation();
												$(this).next().css('left',left).css('top',top).show();
										}
								);

								$this.children('.jqkt_drop_sort_menu').children('.jqkt_drop_sort_up_div').click(
										function()
										{
												$('.jqkt_drop_sort_menu').hide();
												$this.attr('sort','up');
										}
								);

								$this.children('.jqkt_drop_sort_menu').children('.jqkt_drop_sort_dn_div').click(
										function()
										{
												$('.jqkt_drop_sort_menu').hide();
												$this.attr('sort','dn');
										}
								);

								$(document).unbind('click.jqkit_column_head');

								$(document).bind('click.jqkit_column_head',
										function()
										{
												$('.jqkt_drop_sort_menu').hide();
										}
								);
						}
        }
        else
        {
            jQuery(this).addClass("jqkit_column_head");
        }
    });

};

jQuery.fn.jqkit_column_head.timer = 0;

jQuery.fn.jqkit_column_head.defaults = {
    sortable:true,
    initialSort:0,
    showSortTip:false,
		showSortPop:true,
    downArrow:"/jqkit/assets/header/sort_dn.png",
    upArrow:"/jqkit/assets/header/sort_up.png"
};

//
//jQuery.fn.jqkit_autocomplete = function(url,options)
//{
//    var opts = jQuery.extend({}, jQuery.fn.jqkit_autocomplete.defaults, options);
//
//    return this.each(function()
//    {
//        var $this = jQuery(this);
//				$this.attr("autocomplete", "off");
//
//				$this.keyup(
//						function(event)
//						{
//								if($(this).val().length > 1 &&
//									 (event.which == 32 ||
//										event.which == 109 ||
//										event.which == 222 ||
//										event.which == 55 ||
//										event.which == 188 ||
//										event.which == 190 ||
//										(event.which > 64 && event.which < 91) ||
//										(event.which > 95 && event.which < 106)
//									 )
//									 )
//								{
//										fetch_ac($(this));
//								}
//
//								if($(this).val().length < 1)
//								{
//										removeAC();
//								}
//
//								if(event.which == 40 && $('.jqkit_autocomplete_div').length > 0)
//								{
//
//								}
//						}
//				);
//
//				function fetch_ac(t)
//				{
//						if($('.jqkit_autocomplete_div').length == 0)
//						{
//								$('body').append('<div class="jqkit_autocomplete_div"></div>');
//
//								$('.jqkit_autocomplete_div').click(
//										function(event)
//										{
//												event.stopPropagation();
//												removeAC();
//										}
//								);
//
//								$('body').bind('click.jqkit_autocomplete',
//										function()
//										{
//												removeAC();
//										}
//								);
//						}
//
//						$('.jqkit_autocomplete_div')
//								.css('left',t.position().left + 'px')
//								.css('top',(t.position().top + t.outerHeight()) + 'px')
//								.css('width',t.width() + 'px')
//								.load(url,{q:t.val()},
//										function()
//										{
//												$('.jqkit_autocomplete_div div').click(
//													function()
//													{
//														t.val($(this).attr('name'));
//													}
//												);
//										}
//								)
//								.show();
//				}
//
//				function removeAC()
//				{
//						$('.jqkit_autocomplete_div').remove();
//						$('body').unbind('click.jqkit_autocomplete');
//				}
//
//				function selectItem(i)
//				{
//
//				}
//
//    });
//
//};
//
//
//
//jQuery.fn.jqkit_autocomplete.defaults = {
//
//};



/*
 * jQuery Autocomplete plugin 1.1
 *
 * Copyright (c) 2009 JÃ¶rn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 14 2009-08-22 10:29:29Z joern.zaefferer $
 */

;(function($) {

$.fn.extend({
	autocomplete: function(urlOrData, options) {
		var isUrl = typeof urlOrData == "string";
		options = $.extend({}, $.Autocompleter.defaults, {
			url: isUrl ? urlOrData : null,
			data: isUrl ? null : urlOrData,
			delay: isUrl ? $.Autocompleter.defaults.delay : 10,
			max: options && !options.scroll ? 10 : 150
		}, options);

		// if highlight is set to false, replace it with a do-nothing function
		options.highlight = options.highlight || function(value) { return value; };

		// if the formatMatch option is not specified, then use formatItem for backwards compatibility
		options.formatMatch = options.formatMatch || options.formatItem;

		return this.each(function() {
			new $.Autocompleter(this, options);
		});
	},
	result: function(handler) {
		return this.bind("result", handler);
	},
	search: function(handler) {
		return this.trigger("search", [handler]);
	},
	flushCache: function() {
		return this.trigger("flushCache");
	},
	setOptions: function(options){
		return this.trigger("setOptions", [options]);
	},
	unautocomplete: function() {
		return this.trigger("unautocomplete");
	}
});

$.Autocompleter = function(input, options) {

	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	};

	// Create $ object for input element
	var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

	var timeout;
	var previousValue = "";
	var cache = $.Autocompleter.Cache(options);
	var hasFocus = 0;
	var lastKeyPressCode;
	var config = {
		mouseDownOnSelect: false
	};
	var select = $.Autocompleter.Select(options, input, selectCurrent, config);

	var blockSubmit;

	// prevent form submit in opera when selecting with return key
	$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
		if (blockSubmit) {
			blockSubmit = false;
			return false;
		}
	});

	// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
	$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		// a keypress means the input has focus
		// avoids issue where input had focus before the autocomplete was applied
		hasFocus = 1;
		// track last key pressed
		lastKeyPressCode = event.keyCode;
		switch(event.keyCode) {

			case KEY.UP:
				event.preventDefault();
				if ( select.visible() ) {
					select.prev();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.DOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.next();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.PAGEUP:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageUp();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.PAGEDOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageDown();
				} else {
					onChange(0, true);
				}
				break;

			// matches also semicolon
			case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
			case KEY.TAB:
			case KEY.RETURN:
				if( selectCurrent() ) {
					// stop default to prevent a form submit, Opera needs special handling
					event.preventDefault();
					blockSubmit = true;
					return false;
				}
				break;

			case KEY.ESC:
				select.hide();
				break;

			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}).focus(function(){
		// track whether the field has focus, we shouldn't process any
		// results if the field no longer has focus
		hasFocus++;
	}).blur(function() {
		hasFocus = 0;
		if (!config.mouseDownOnSelect) {
			hideResults();
		}
	}).click(function() {
		// show select when clicking in a focused field
		if ( hasFocus++ > 1 && !select.visible() ) {
			onChange(0, true);
		}
	}).bind("search", function() {
		// TODO why not just specifying both arguments?
		var fn = (arguments.length > 1) ? arguments[1] : null;
		function findValueCallback(q, data) {
			var result;
			if( data && data.length ) {
				for (var i=0; i < data.length; i++) {
					if( data[i].result.toLowerCase() == q.toLowerCase() ) {
						result = data[i];
						break;
					}
				}
			}
			if( typeof fn == "function" ) fn(result);
			else $input.trigger("result", result && [result.data, result.value]);
		}
		$.each(trimWords($input.val()), function(i, value) {
			request(value, findValueCallback, findValueCallback);
		});
	}).bind("flushCache", function() {
		cache.flush();
	}).bind("setOptions", function() {
		$.extend(options, arguments[1]);
		// if we've updated the data, repopulate
		if ( "data" in arguments[1] )
			cache.populate();
	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");
	});


	function selectCurrent() {
		var selected = select.selected();
		if( !selected )
			return false;

		var v = selected.result;
		previousValue = v;

		if ( options.multiple ) {
			var words = trimWords($input.val());
			if ( words.length > 1 ) {
				var seperator = options.multipleSeparator.length;
				var cursorAt = $(input).selection().start;
				var wordAt, progress = 0;
				$.each(words, function(i, word) {
					progress += word.length;
					if (cursorAt <= progress) {
						wordAt = i;
						return false;
					}
					progress += seperator;
				});
				words[wordAt] = v;
				// TODO this should set the cursor to the right position, but it gets overriden somewhere
				//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
				v = words.join( options.multipleSeparator );
			}
			v += options.multipleSeparator;
		}

		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;
	}

	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}

		var currentValue = $input.val();

		if ( !skipPrevCheck && currentValue == previousValue )
			return;

		previousValue = currentValue;

		currentValue = lastWord(currentValue);
		if ( currentValue.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			if (!options.matchCase)
				currentValue = currentValue.toLowerCase();
			request(currentValue, receiveData, hideResultsNow);
		} else {
			stopLoading();
			select.hide();
		}
	};

	function trimWords(value) {
		if (!value)
			return [""];
		if (!options.multiple)
			return [$.trim(value)];
		return $.map(value.split(options.multipleSeparator), function(word) {
			return $.trim(value).length ? $.trim(word) : null;
		});
	}

	function lastWord(value) {
		if ( !options.multiple )
			return value;
		var words = trimWords(value);
		if (words.length == 1)
			return words[0];
		var cursorAt = $(input).selection().start;
		if (cursorAt == value.length) {
			words = trimWords(value)
		} else {
			words = trimWords(value.replace(value.substring(cursorAt), ""));
		}
		return words[words.length - 1];
	}

	// fills in the input box w/the first match (assumed to be the best match)
	// q: the term entered
	// sValue: the first matching result
	function autoFill(q, sValue){
		// autofill in the complete box w/the first match as long as the user hasn't entered in more data
		// if the last user key pressed was backspace, don't autofill
		if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
			// select the portion of the value not typed by the user (so the next character will erase)
			$(input).selection(previousValue.length, previousValue.length + sValue.length);
		}
	};

	function hideResults() {
		clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		var wasVisible = select.visible();
		select.hide();
		clearTimeout(timeout);
		stopLoading();
		if (options.mustMatch) {
			// call search and run callback
			$input.search(
				function (result){
					// if no value found, clear the input box
					if( !result ) {
						if (options.multiple) {
							var words = trimWords($input.val()).slice(0, -1);
							$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
						}
						else {
							$input.val( "" );
							$input.trigger("result", null);
						}
					}
				}
			);
		}
	};

	function receiveData(q, data) {
		if ( data && data.length && hasFocus ) {
			stopLoading();
			select.display(data, q);
			autoFill(q, data[0].value);
			select.show();
		} else {
			hideResultsNow();
		}
	};

	function request(term, success, failure) {
		if (!options.matchCase)
			term = term.toLowerCase();
		var data = cache.load(term);
		// recieve the cached data
		if (data && data.length) {
			success(term, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){

			var extraParams = {
				timestamp: +new Date()
			};
			$.each(options.extraParams, function(key, param) {
				extraParams[key] = typeof param == "function" ? param() : param;
			});

			$.ajax({
				// try to leverage ajaxQueue plugin to abort previous requests
				mode: "abort",
				// limit abortion to this input
				port: "autocomplete" + input.name,
				dataType: options.dataType,
				url: options.url,
				data: $.extend({
					q: lastWord(term),
					limit: options.max
				}, extraParams),
				success: function(data) {
					var parsed = options.parse && options.parse(data) || parse(data);
					cache.add(term, parsed);
					success(term, parsed);
				}
			});
		} else {
			// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
			select.emptyList();
			failure(term);
		}
	};

	function parse(data) {
		var parsed = [];
		var rows = data.split("\n");
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				row = row.split("|");
				parsed[parsed.length] = {
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};

	function stopLoading() {
		$input.removeClass(options.loadingClass);
	};

};

$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	minChars: 1,
	delay: 400,
	matchCase: false,
	matchSubset: true,
	matchContains: false,
	cacheLength: 10,
	max: 100,
	mustMatch: false,
	extraParams: {},
	selectFirst: true,
	formatItem: function(row) { return row[0]; },
	formatMatch: null,
	autoFill: false,
	width: 0,
	multiple: false,
	multipleSeparator: ", ",
	highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	},
    scroll: true,
    scrollHeight: 180
};

$.Autocompleter.Cache = function(options) {

	var data = {};
	var length = 0;

	function matchSubset(s, sub) {
		if (!options.matchCase)
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (options.matchContains == "word"){
			i = s.toLowerCase().search("\\b" + sub.toLowerCase());
		}
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){
			length++;
		}
		data[q] = value;
	}

	function populate(){
		if( !options.data ) return false;
		// track the matches
		var stMatchSets = {},
			nullData = 0;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( !options.url ) options.cacheLength = 1;

		// track all options for minChars = 0
		stMatchSets[""] = [];

		// loop through the array and create a lookup structure
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			// if rawValue is a string, make an array otherwise just reference the array
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( value === false )
				continue;

			var firstChar = value.charAt(0).toLowerCase();
			// if no lookup array for this character exists, look it up now
			if( !stMatchSets[firstChar] )
				stMatchSets[firstChar] = [];

			// if the match is a string
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};

			// push the current match into the set list
			stMatchSets[firstChar].push(row);

			// keep track of minChars zero items
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};

		// add the data items to the cache
		$.each(stMatchSets, function(i, value) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			add(i, value);
		});
	}

	// populate any existing data
	setTimeout(populate, 25);

	function flush(){
		data = {};
		length = 0;
	}

	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			/*
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
			if( !options.url && options.matchContains ){
				// track all matches
				var csub = [];
				// loop through all the data grids for matches
				for( var k in data ){
					// don't search through the stMatchSets[""] (minChars: 0) cache
					// this prevents duplicates
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							// if we've got a match, add it to the array
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}
				return csub;
			} else
			// if the exact item exists, use it
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};



$.Autocompleter.Select = function (options, input, select, config) {
	var CLASSES = {
		ACTIVE: "ac_over"
	};

	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

	// Create results
	function init() {
		if (!needsInit)
			return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);

		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	            active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
			    $(target(event)).addClass(CLASSES.ACTIVE);
	        }
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
			input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});

		if( options.width > 0 )
			element.css("width", options.width);

		needsInit = false;
	}

	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}

	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
	};

	function movePosition(step) {
		active += step;
		if (active < 0) {
			active = listItems.size() - 1;
		} else if (active >= listItems.size()) {
			active = 0;
		}
	}

	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}

	function fillList() {
		list.empty();
		var max = limitNumberOfItems(data.length);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			$.data(li, "ac_data", data[i]);
		}
		listItems = list.find("li");
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();
	}

	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE);
			active = -1;
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				left: offset.left
			}).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});

                if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						// IE doesn't recalculate width when scrollbar disappears
						listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
					}
                }

            }
		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ac_data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};

$.fn.selection = function(start, end) {
	if (start !== undefined) {
		return this.each(function() {
			if( this.createTextRange ){
				var selRange = this.createTextRange();
				if (end === undefined || start == end) {
					selRange.move("character", start);
					selRange.select();
				} else {
					selRange.collapse(true);
					selRange.moveStart("character", start);
					selRange.moveEnd("character", end);
					selRange.select();
				}
			} else if( this.setSelectionRange ){
				this.setSelectionRange(start, end);
			} else if( this.selectionStart ){
				this.selectionStart = start;
				this.selectionEnd = end;
			}
		});
	}
	var field = this[0];
	if ( field.createTextRange ) {
		var range = document.selection.createRange(),
			orig = field.value,
			teststring = "<->",
			textLength = range.text.length;
		range.text = teststring;
		var caretAt = field.value.indexOf(teststring);
		field.value = orig;
		this.selection(caretAt, caretAt + textLength);
		return {
			start: caretAt,
			end: caretAt + textLength
		}
	} else if( field.selectionStart !== undefined ){
		return {
			start: field.selectionStart,
			end: field.selectionEnd
		}
	}
};

})(jQuery);
