$(document).ready(function() {
	$('.ac_results').ifixpng();
		
	if ($('.scrollable').length) {	
		$(".main_left .scrollable").scrollable({circular: true, mousewheel: true}).navigator().autoscroll({
			interval: 2000		
		});
		
			var scrollable =   jQuery(".main_left .scrollable").data("scrollable");
	scrollable.onSeek(function(){
			
      var size = 3;

      if (this.getIndex() >= this.getSize() - size) {
	      this.begin();
      }
			
	});
	}
	



		
	$('a[rel*=external]').click( function() {
		window.open(this.href);
		return false;
    });

	$("a.fancybox").fancybox();

    setInterval( "slideSwitch()", 5000 );
	
	//Gomb lekerekítés
	$('.sima_gomb').button_replace();
	
	$('a#top').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow');	
		return false
	});
	
	//Form Tooltip
    $("#some_name").inputTip({
        goodText: "Ez így tökéletesen megfelel!",
        badText: "Valamit azért be is kellene írni...",
        tipText: "Kérjük adja meg a teljes nevét (Pl. Kovács László)",
        validateText: function(inputValue, callback) {
            if (inputValue.length > 0) callback(1);
            else callback(0);
        },
        validateInRealTime: true
    });
    $("#proba_2").inputTip({
        goodText: "Ez így tökéletesen megfelel!",
        badText: "Hibás telefonszám!",
        tipText: "Kérjük adja meg a telefonszámát! (Például: 339-4248)",
        validateText: function(inputValue, callback) {
            var telefonRegexp = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
            if (telefonRegexp.test(inputValue)) callback(1);
            else callback(0);
        },
        validateInRealTime: true
    });


	// Legördülő menü
	var li_elso_width = $('#menu ul li:first').width();
	var li_big_width = li_elso_width+11;
	$('.submenu.big').css('left','-'+li_big_width+'px');

	$('#menu ul li.menu_hover').hover(function() {
		$('.submenu.big').hide();
		$('li.menu_kepviseltcegek a').removeClass('active');
		if ($(this).children('.submenu').is(':hidden')) {
			$(this).children('a.fomenu').addClass('active');
			$(this).children('.submenu').addClass('active');
			if ($.browser.msie && $.browser.version.substr(0,1)<7) {
				$(this).children('.submenu').show();
				$(this).removeClass('active');
			}
			else {
				$(this).children('.submenu').fadeIn(0,function(){
					$(this).removeClass('active');
				});
			}
		}
	},function() {
		if ($(this).children('.submenu').is(':visible')) {
			$(this).children('a.fomenu').removeClass('active');
			if ($.browser.msie && $.browser.version.substr(0,1)<7) {
				$(this).children('.submenu').hide();
			}
			else {
				$(this).children('.submenu').fadeOut(0);
			}
		}
	});
	$('#menu ul li.menu_kepviseltcegek').click(function() {
		$('.submenu.big').show();
	});
	$('#menu ul li.menu_kepviseltcegek a.menulink_kepviseltcegek').click(function() {
		$('a.fomenu').removeClass('active');
		$(this).addClass('active');
		$('.submenu.big').show();
		return false;
	});
	$('.submenu.big').hover(function() {

	},function() {
		$(this).hide();
		$(this).parent().children('a.fomenu').removeClass('active');
	});	// Legördülő menü

	// Kereső
	$("#kereso_input").autocomplete("http://holimex.i-host.hu/ajax_kereso.php", {
		width: 184
	});	
	$("#kereso_input").result(function(event, data, formatted) {
		if (data)
			 location.href = data[1];
	});	
	$("a#kereso_submit").click(function() {
		$("form#ajax_kereso_form").submit();
		return false;
	});		
	
	// Kereső
	
	// Munkatársak
	$('ul#munkatarsak li').hover(function() {
		$('ul#munkatarsak li table').hide();
		$(this).find('table').show();
	},function() {
		$(this).find('table').hide();
	});	
	// Munkatársak

	// Mátrix
    $('table#matrix').tableHover({colClass: 'hover', cellClass: 'hovercell', clickClass: 'click', headRows: true, headCols: true, ignoreCols: [1, 2], ignoreRows: [2]}); 
    var matrix_y = $('table#matrix').offset();
	$(window).scroll(function () { 
	var documentHeight = $(document).height(); 
	var scrollPosition = $(window).scrollTop(); 
    	if (matrix_y.top < scrollPosition) {
    		//$('#table_header').show();
   		}
   		else {
   			//$('#table_header').hide();
   		}
    });
	
	if ( document.location.href.indexOf('gyorskereso#') > -1 ) {
		
		var url = document.location.href.split('#');
		
		
		
		if (document.location.href.indexOf('_') > -1) {
			var count = url[1].split('_');
			$('.'+count[0]+'.v'+count[1]).addClass('click');
			console.log('.'+count[0]+'.v'+count[1]);
		}
		else {
			$('.'+url[1]).addClass('click');
			
			if (url[1]=='asvanyalu') {
				$('.aluminium').addClass('click');
				$('.asvanyfeldolg').addClass('click');
			}
			
			if (url[1]=='gyogyszerbio') {
				$('.gyogyszeripar').addClass('click');
				$('.biotech').addClass('click');
			}
			
		}
		
    }
    
	// Mátrix

	// Spam védelem
	$('a.spam_protect').spam_protect();
	$('.kukac').html('@');
	// Spam védelem
	$("#cegber").hide();
	$('ul#gepek_berendezesek li a').click(function() {
		var items = $('ul#gepek_berendezesek').length;
		var height = $('ul#gepek_berendezesek li').height();
		var submenu_height = $('#submenu_left').height();
		var index = $('ul#gepek_berendezesek li a').index(this)/2;
		var pos_x = (height*index)-submenu_height;
		var margin_top = pos_x+'px';
		var url = $(this).attr('href');
		$('ul#gepek_berendezesek li a').removeClass('hover');
		$(this).addClass('hover');
		$("#cegber").fadeOut(function(){
			if (pos_x < 0) {
				$('#cegber').css('marginTop', '0');
			}
			else {
				$('#cegber').css('marginTop', margin_top);
			}
			$("#cegber").load(url, function(){
 				$("#cegber").fadeIn();
			});			
		});
		return false;
	});
	$('ul.testvercegek li').hover(function() {
		var name = $(this).attr('class');
		$('.terkep div').addClass(name);
	},function() {
		$('.terkep div').attr('class','');
	});
	$('ul.testvercegek li a, a.ne, a.na').click(function() {
		return false;
	});

});
	function slideSwitch() {
	    var $active = $('.slide div.active');
	
	    if ( $active.length == 0 ) $active = $('.slide div:last');
		    var $next =  $active.next().length ? $active.next()
	        : $('.slide div:first');
	
	    $active.addClass('last-active');
	
	    $next.css({opacity: 0.0})
	        .addClass('active')
	        .animate({opacity: 1.0}, 0, function() {
	            $active.removeClass('active last-active');
	        });
	}
(function($){

	$.fn.spam_protect = function(options) {
		return this.each(function() {
			obj = $(this);
			href = obj.attr('href');
			href_replaced_1 = href.replace("|", "@");
			href_replaced_2 = href_replaced_1.replace(":", ".");
			obj.attr({ 
				href: 'mailto:'+href_replaced_2,
				title: 'E-mail cím: '+href_replaced_2
          	});
			obj.html(href_replaced_2);
		});
	};

	$.fn.button_replace = function(options) {
		return this.each(function() {
			obj = $(this);
			val = obj.val();
			if (obj.hasClass('clear')) {
				button = '<a href="" class="button"><span>'+val+'</span></a><div class="clear"></div>';
			}
			else {
				button = '<a href="" class="button"><span>'+val+'</span></a>';
			}
			obj.after(button);
			obj.hide();
		});
	};

	$.fn.form = function(options) {

		var defaults = {
			message_required: 'Ezt a mezőt kötelező kitölteni!',
			message_email: 'Valós e-mail címet adjon meg!',
			moreText: "more",
			lessText: "less",
			ellipsisText: "..."
		};
		var options = $.extend(defaults, options);		

		return this.each(function() {
			obj = $(this);
			
			/*Küldés*/
			obj.find('p.submit a').live('click', function() {
				obj.submit();
				return false;
			});
			/*Küldés*/
			
			/*Tooltip*/
			tooltip = obj.find('input.tooltip');
			tooltip.focus(function() {
				tooltip_this = $(this);
				title = tooltip_this.attr('title');
				id = tooltip_this.attr('id')
				tooltip_id = 'tooltip_'+id;
				pos = tooltip_this.offset();
				tooltip_html = '<div class="tooltip_holder" id="'+tooltip_id+'"><div class="box notice"><div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div><div class="icon"></div><div class="content"><p>'+title+'</p></div></div></div>';				
				$('.tooltip_holder').remove();
				tooltip_this.after(tooltip_html);
				$('#'+tooltip_id).css({left:'380px',top:'20px'}).fadeIn();
			});
			tooltip.blur(function() {				
				$('.tooltip_holder').fadeOut(function(){
					$(this).remove();
				});
			});
			/*Tooltip*/
		});
	};	
})(jQuery);



jQuery.fn.inputTip = function(options) {

    var defaults = {
        tipId: "inputTipContainer",
        tipSelectedClass: "selected",
        goodText: "Ok",
        badText: "Bad",
        tipText: "Tip",
        checkingText: "Checking...",
        validateText: null,
        validateInRealTime: true
    };
    var options = $.extend(defaults, options);

    var inputTipContainer = $('<div class="' + defaults.tipId + '"><div class="box notice"><div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div><div class="icon"></div><div class="content"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p></div></div></div>');

    var currentHelper = new jQuery.inputTipHelper(defaults, inputTipContainer);

    $("body").append(inputTipContainer);
    return this.each(function() {
        $(this).focus(function() {
            $(this).addClass("selected").addClass("straightRightCorner");
            var thisRef = $(this);
            var thisOffset = $(this).offset();
            inputTipContainer.show().css("left", (thisOffset.left + thisRef.outerWidth()) + "px").css("top", (thisOffset.top) + "px");
            currentHelper.SetTipContainerText(2);
        }).blur(function() {
            $(this).removeClass("selected");
            defaults.validateText($(this).val(), function(status, response) {
                currentHelper.SetTipContainerText(status, response);
            });
        });
        if (defaults.validateInRealTime) {
            $(this).keyup(function() {
                if (defaults.validateInRealTime) {
                    defaults.validateText($(this).val(), function(status, response) {
                        currentHelper.SetTipContainerText(status, response);
                    });
                }
            });
        }
    });
}
jQuery.inputTipHelper = function(Settings, TipContainer) {
    this.init(Settings, TipContainer);
}
jQuery.inputTipHelper.prototype = {
    Settings: null,
    TipContainer: null,

    init: function(Settings, TipContainer) {
        this.TipContainer = TipContainer;
        this.Settings = Settings;
    },

    SetTipContainerText: function(type, newForcedText) {
        this.TipContainer.removeClass("error")
        this.TipContainer.removeClass("success");
        this.TipContainer.find('.box').removeClass("error")
        this.TipContainer.find('.box').removeClass("success");
        var newText;
        switch (type) {
            // Bad                            
            case 0:
                {
                    this.TipContainer.addClass("error");
                    this.TipContainer.find('.box').addClass("error");
                    newText = this.Settings.badText;
                }
                break;
            // Good                            
            case 1:
                {
                    this.TipContainer.addClass("success");
                    this.TipContainer.find('.box').addClass("success");
                    newText = this.Settings.goodText;
                }
                break;
            // Tip                            
            case 2:
                {
                    newText = this.Settings.tipText;
                }
                break;
        }
        if (newForcedText) newText = newForcedText;
        this.TipContainer.find('p').html(newText);
    }
}


/*
 * 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 15 2009-08-22 10:30:27Z 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 ? 100 : 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: 100
				}, 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-5
			}).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);

/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
 
 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */
 
(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set 
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */
	 
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);

/*
 * jQuery tableHover plugin
 * Version: 0.1.4
 *
 * Copyright (c) 2007 Roman Weich
 * http://p.sohei.org
 *
 * Dual licensed under the MIT and GPL licenses 
 * (This means that you can choose the license that best suits your project, and use it accordingly):
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Changelog: 
 * v 0.1.4 - 2007-12-17
 *	- fix: clicking on a link or child element inside a cell did not set the clickClass on the rows/columns.
 * v 0.1.3 - 2007-09-04
 *	- fix: highlight did not work when the hovered table cell had child elements inside
 * v 0.1.2 - 2007-08-13
 *	- fix/change: changed event binding routine, as is got really slow with jquery 1.1.3.1
 *	-change: added new option "ignoreCols", through which columns can be excluded from the highlighting process
 * v 0.1.1 - 2007-06-05
 *	- fix: errors when using the plugin on a table not having a theader or tfoot
 * v 0.1.0 - 2007-05-31
 */

(function($)
{
	/**
	 * Calculates the actual cellIndex value of all cells in the table and stores it in the realCell property of each cell.
	 * Thats done because the cellIndex value isn't correct when colspans or rowspans are used.
	 * Originally created by Matt Kruse for his table library - Big Thanks! (see http://www.javascripttoolbox.com/)
	 * @param {element} table	The table element.
	 */
	var fixCellIndexes = function(table) 
	{
		var rows = table.rows;
		var len = rows.length;
		var matrix = [];
		for ( var i = 0; i < len; i++ )
		{
			var cells = rows[i].cells;
			var clen = cells.length;
			for ( var j = 0; j < clen; j++ )
			{
				var c = cells[j];
				var rowSpan = c.rowSpan || 1;
				var colSpan = c.colSpan || 1;
				var firstAvailCol = -1;
				if ( !matrix[i] )
				{ 
					matrix[i] = []; 
				}
				var m = matrix[i];
				// Find first available column in the first row
				while ( m[++firstAvailCol] ) {}
				c.realIndex = firstAvailCol;
				for ( var k = i; k < i + rowSpan; k++ )
				{
					if ( !matrix[k] )
					{ 
						matrix[k] = []; 
					}
					var matrixrow = matrix[k];
					for ( var l = firstAvailCol; l < firstAvailCol + colSpan; l++ )
					{
						matrixrow[l] = 1;
					}
				}
			}
		}
	};

	/**
	 * Sets the rowIndex of each row in the table. 
	 * Opera seems to get that wrong using document order instead of logical order on the tfoot-tbody part.
	 * @param {element} table	The table element.
	 */
	var fixRowIndexes = function(tbl) 
	{
		var v = 0, i, k, r = ( tbl.tHead ) ? tbl.tHead.rows : 0;
		if ( r )
		{
			for ( i = 0; i < r.length; i++ )
			{
				r[i].realRIndex = v++;
			}
		}
		for ( k = 0; k < tbl.tBodies.length; k++ )
		{
			r = tbl.tBodies[k].rows;
			if ( r )
			{
				for ( i = 0; i < r.length; i++ )
				{
					r[i].realRIndex = v++;
				}
			}
		}
		r = ( tbl.tFoot ) ? tbl.tFoot.rows : 0;
		if ( r )
		{
			for ( i = 0; i < r.length; i++ )
			{
				r[i].realRIndex = v++;
			}
		}
	};

	/**
	 * Highlights table rows and/or columns on mouse over.
	 * Fixes the highlight of the currently highlighted rows/columns on click.
	 * Works on tables with rowspans and colspans.
	 *
	 * @param {map} options			An object for optional settings (options described below).
	 *
	 * @option {boolean} allowHead		Allow highlighting when hovering over the table header.
	 *							Default value: true
	 * @option {boolean} allowBody		Allow highlighting when hovering over the table body.
	 *							Default value: true
	 * @option {boolean} allowFoot		Allow highlighting when hovering over the table footer.
	 *							Default value: true
	 *
	 * @option {boolean} headRows		If true the rows in the table header will be highlighted when hovering over them.
	 *							Default value: false
	 * @option {boolean} bodyRows		If true the rows in the table body will be highlighted when hovering over them.
	 *							Default value: true
	 * @option {boolean} footRows		If true the rows in the table footer will be highlighted when hovering over them.
	 *							Default value: false
	 * @option {boolean} spanRows		When hovering over a cell spanning over more than one row, highlight all spanned rows.
	 *							Default value: true
	 *
	 * @option {boolean} headCols		If true the cells in the table header (matching the currently hovered column) will be highlighted.
	 *							Default value: false
	 * @option {boolean} bodyCols		If true the cells in the table body (matching the currently hovered column) will be highlighted.
	 *							Default value: true
	 * @option {boolean} footCols		If true the cells in the table footer (matching the currently hovered column) will be highlighted.
	 *							Default value: false
	 * @option {boolean} spanCols		When hovering over a cell spanning over more than one column, highlight all spanned columns.
	 *							Default value: true
	 * @option {array} ignoreCols		An array of numbers. Each column with the matching column index won't be included in the highlighting process.
	 *							Index starting at 1!
	 *							Default value: [] (empty array)
	 *
	 * @option {boolean} headCells		Set a special highlight class to the cell the mouse pointer is currently pointing at (inside the table header only).
	 *							Default value: false
	 * @option {boolean} bodyCells		Set a special highlight class to the cell the mouse pointer is currently pointing at (inside the table body only).
	 *							Default value: true
	 * @option {boolean} footCells		Set a special highlight class to the cell the mouse pointer is currently pointing at (inside the table footer only).
	 *							Default value: false
	 *
	 * @option {string} rowClass			The css class set to the currently highlighted row.
	 *							Default value: 'hover'
	 * @option {string} colClass			The css class set to the currently highlighted column.
	 *							Default value: '' (empty string)
	 * @option {string} cellClass			The css class set to the currently highlighted cell.
	 *							Default value: '' (empty string)
	 * @option {string} clickClass		The css class set to the currently highlighted row and column on mouse click.
	 *							Default value: '' (empty string)
	 *
	 * @example $('#table').tableHover({});
	 * @desc Add simple row highlighting to #table with default settings.
	 *
	 * @example $('#table').tableHover({rowClass: "someclass", colClass: "someotherclass"});
	 * @desc Add row and columnhighlighting to #table and set the specified css classes to the highlighted cells.
	 *
	 * @example $('#table').tableHover({clickClass: "someclickclass"});
	 * @desc Add simple row highlighting to #table and set the specified css class on the cells when clicked.
	 *
	 * @example $('#table').tableHover({allowBody: false, allowFoot: false, allowHead: true, colClass: "someclass"});
	 * @desc Add column highlighting on #table only highlighting the cells when hovering over the table header.
	 *
	 * @example $('#table').tableHover({bodyCols: false, footCols: false, headCols: true, colClass: "someclass"});
	 * @desc Add column highlighting on #table only for the cells in the header.
	 *
	 * @type jQuery
	 *
	 * @name tableHover
	 * @cat Plugins/tableHover
	 * @author Roman Weich (http://p.sohei.org)
	 */
	$.fn.tableHover = function(options)
	{
		var settings = $.extend({
				allowHead : true,
				allowBody : true,
				allowFoot : true,

				headRows : false,
				bodyRows : true,
				footRows : false,
				spanRows : true,

				headCols : false,
				bodyCols : true,
				footCols : false,
				spanCols : true,
				ignoreCols : [],

				headCells : false,
				bodyCells : true,
				footCells : false,
				//css classes,,
				rowClass : 'hover',
				colClass : '',
				cellClass : '',
				clickClass : ''
			}, options);

		return this.each(function() 
        {
			var colIndex = [], rowIndex = [], tbl = this, r, rCnt = 0, lastClick = [-1, -1];

			if ( !tbl.tBodies || !tbl.tBodies.length )
			{
				return;
			}

			/**
			 * Adds all rows and each of their cells to the row and column indexes.
			 * @param {array} rows		An array of table row elements to add.
			 * @param {string} nodeName	Defines whether the rows are in the header, body or footer of the table.
			 */
			var addToIndex = function(rows, nodeName)
			{
				var c, row, rowI, cI, rI, s;
				//loop through the rows
				for ( rowI = 0; rowI < rows.length; rowI++, rCnt++ )
				{
					row = rows[rowI];
					//each cell
					for ( cI = 0; cI < row.cells.length; cI++ )
					{
						c = row.cells[cI];
						//add to rowindex
						if ( (nodeName == 'TBODY' && settings.bodyRows) 
							|| (nodeName == 'TFOOT' && settings.footRows) 
							|| (nodeName == 'THEAD' && settings.headRows) )
						{
							s = c.rowSpan;
							while ( --s >= 0 )
							{
								rowIndex[rCnt + s].push(c);
							}
						}
						//add do colindex
						if ( (nodeName == 'TBODY' && settings.bodyCols)
								|| (nodeName == 'THEAD' && settings.headCols) 
								|| (nodeName == 'TFOOT' && settings.footCols) )
						{
							s = c.colSpan;
							while ( --s >= 0 )
							{
								rI = c.realIndex + s;
								if ( $.inArray(rI + 1, settings.ignoreCols) > -1 )
								{
									break;//dont highlight the columns in the ignoreCols array
								}
								if ( !colIndex[rI] )
								{
									colIndex[rI] = [];
								}
								colIndex[rI].push(c);
							}
						}
						//allow hover for the cell?
						if ( (nodeName == 'TBODY' && settings.allowBody) 
								|| (nodeName == 'THEAD' && settings.allowHead) 
								|| (nodeName == 'TFOOT' && settings.allowFoot) )
						{
							c.thover = true;
						}
					}
				}
			};

			/**
			 * Mouseover event handling. Set the highlight to the rows/cells.
			 */
			var over = function(e)
			{
				var p = e.target;
				while ( p != this && p.thover !== true )
				{
					p = p.parentNode;
				}
				if ( p.thover === true )
				{
					highlight(p, true);
				}
			};

			/**
			 * Mouseout event handling. Remove the highlight from the rows/cells.
			 */
			var out = function(e)
			{
				var p = e.target;
				while ( p != this && p.thover !== true )
				{
					p = p.parentNode;
				}
				if ( p.thover === true )
				{
					highlight(p, false);
				}
			};
			
			/**
			 * Mousedown event handling. Sets or removes the clickClass css style to the currently highlighted rows/cells.
			 */
			var click = function(e)
			{
				var t = e.target;
				while ( t && t != tbl && !t.thover ) //search the real target
					t = t.parentNode;
				if ( t.thover && settings.clickClass != '' )
				{
					var x = t.realIndex, y = t.parentNode.realRIndex, s = '';
					//unclick
					$('td.' + settings.clickClass + ', th.' + settings.clickClass, tbl).removeClass(settings.clickClass);
					if ( x != lastClick[0] || y != lastClick[1] )
					{
						//click..
						if ( settings.rowClass != '' )
						{
							s += ',.' + settings.rowClass;
						}
						if ( settings.colClass != '' )
						{
							s += ',.' + settings.colClass;
						}
						if ( settings.cellClass != '' )
						{
							s += ',.' + settings.cellClass;
						}
						if ( s != '' )
						{
							$('td, th', tbl).filter(s.substring(1)).addClass(settings.clickClass);
						}
						lastClick = [x, y];
					}
					else
					{
						lastClick = [-1, -1];
					}
				}
			};
			
			/**
			 * Adds or removes the highlight to/from the columns and rows.
			 * @param {element} cell	The cell with the mouseover/mouseout event.
			 * @param {boolean} on		Defines whether the style will be set or removed.
			 */
			var highlight = function(cell, on)
			{
				if ( on ) //create dummy funcs - dont want to test for on==true all the time
				{
					$.fn.tableHoverHover = $.fn.addClass;
				}
				else
				{
					$.fn.tableHoverHover = $.fn.removeClass;
				}
				//highlight columns
				var h = colIndex[cell.realIndex] || [], rH = [], i = 0, rI, nn;
				if ( settings.colClass != '' )
				{
					while ( settings.spanCols && ++i < cell.colSpan && colIndex[cell.realIndex + i] )
					{
						h = h.concat(colIndex[cell.realIndex + i]);
					}
					$(h).tableHoverHover(settings.colClass);
				}
				//highlight rows
				if ( settings.rowClass != '' )
				{
					rI = cell.parentNode.realRIndex;
					if ( rowIndex[rI] )
					{
						rH = rH.concat(rowIndex[rI]);
					}
					i = 0;
					while ( settings.spanRows && ++i < cell.rowSpan )
					{
						if ( rowIndex[rI + i] )
						{
							rH = rH.concat(rowIndex[rI + i]);
						}
					}
					$(rH).tableHoverHover(settings.rowClass);
				}
				//highlight cell
				if ( settings.cellClass != '' )
				{
					nn = cell.parentNode.parentNode.nodeName.toUpperCase();
					if ( (nn == 'TBODY' && settings.bodyCells)
							|| (nn == 'THEAD' && settings.headCells)
							|| (nn == 'TFOOT' && settings.footCells) )
					{
						$(cell).tableHoverHover(settings.cellClass);
					}
				}
			};

			fixCellIndexes(tbl);
			fixRowIndexes(tbl);

			//init rowIndex
			for ( r = 0; r < tbl.rows.length; r++ )
			{
				rowIndex[r] = [];
			}
			//add header cells to index
			if ( tbl.tHead )
			{
				addToIndex(tbl.tHead.rows, 'THEAD');
			}
			//create index - loop through the bodies
			for ( r = 0; r < tbl.tBodies.length; r++ )
			{
				addToIndex(tbl.tBodies[r].rows, 'TBODY');
			}
			//add footer cells to index
			if ( tbl.tFoot )
			{
				addToIndex(tbl.tFoot.rows, 'TFOOT');
			}
			$(this).bind('mouseover', over).bind('mouseout', out).click(click);
		});
	};
})(jQuery); 

/*
 * jQuery Nivo Slider v2.6
 * http://nivo.dev7studios.com
 *
 * Copyright 2011, Gilbert Pellegrom
 * Free to use and abuse under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * March 2010
 */

(function($){var NivoSlider=function(element,options){var settings=$.extend({},$.fn.nivoSlider.defaults,options);var vars={currentSlide:0,currentImage:'',totalSlides:0,randAnim:'',running:false,paused:false,stop:false};var slider=$(element);slider.data('nivo:vars',vars);slider.css('position','relative');slider.addClass('nivoSlider');var kids=slider.children();kids.each(function(){var child=$(this);var link='';if(!child.is('img')){if(child.is('a')){child.addClass('nivo-imageLink');link=child;}
child=child.find('img:first');}
var childWidth=child.width();if(childWidth==0)childWidth=child.attr('width');var childHeight=child.height();if(childHeight==0)childHeight=child.attr('height');if(childWidth>slider.width()){slider.width(childWidth);}
if(childHeight>slider.height()){slider.height(childHeight);}
if(link!=''){link.css('display','none');}
child.css('display','none');vars.totalSlides++;});if(settings.startSlide>0){if(settings.startSlide>=vars.totalSlides)settings.startSlide=vars.totalSlides-1;vars.currentSlide=settings.startSlide;}
if($(kids[vars.currentSlide]).is('img')){vars.currentImage=$(kids[vars.currentSlide]);}else{vars.currentImage=$(kids[vars.currentSlide]).find('img:first');}
if($(kids[vars.currentSlide]).is('a')){$(kids[vars.currentSlide]).css('display','block');}
slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');slider.append($('<div class="nivo-caption"><p></p></div>').css({display:'none',opacity:settings.captionOpacity}));var processCaption=function(settings){var nivoCaption=$('.nivo-caption',slider);if(vars.currentImage.attr('title')!=''&&vars.currentImage.attr('title')!=undefined){var title=vars.currentImage.attr('title');if(title.substr(0,1)=='#')title=$(title).html();if(nivoCaption.css('display')=='block'){nivoCaption.find('p').fadeOut(settings.animSpeed,function(){$(this).html(title);$(this).fadeIn(settings.animSpeed);});}else{nivoCaption.find('p').html(title);}
nivoCaption.fadeIn(settings.animSpeed);}else{nivoCaption.fadeOut(settings.animSpeed);}}
processCaption(settings);var timer=0;if(!settings.manualAdvance&&kids.length>1){timer=setInterval(function(){nivoRun(slider,kids,settings,false);},settings.pauseTime);}
if(settings.directionNav){slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+settings.prevText+'</a><a class="nivo-nextNav">'+settings.nextText+'</a></div>');if(settings.directionNavHide){$('.nivo-directionNav',slider).hide();slider.hover(function(){$('.nivo-directionNav',slider).show();},function(){$('.nivo-directionNav',slider).hide();});}
$('a.nivo-prevNav',slider).live('click',function(){if(vars.running)return false;clearInterval(timer);timer='';vars.currentSlide-=2;nivoRun(slider,kids,settings,'prev');});$('a.nivo-nextNav',slider).live('click',function(){if(vars.running)return false;clearInterval(timer);timer='';nivoRun(slider,kids,settings,'next');});}
if(settings.controlNav){var nivoControl=$('<div class="nivo-controlNav"></div>');slider.append(nivoControl);for(var i=0;i<kids.length;i++){if(settings.controlNavThumbs){var child=kids.eq(i);if(!child.is('img')){child=child.find('img:first');}
if(settings.controlNavThumbsFromRel){nivoControl.append('<a class="nivo-control" rel="'+i+'"><img src="'+child.attr('rel')+'" alt="" /></a>');}else{nivoControl.append('<a class="nivo-control" rel="'+i+'"><img src="'+child.attr('src').replace(settings.controlNavThumbsSearch,settings.controlNavThumbsReplace)+'" alt="" /></a>');}}else{nivoControl.append('<a class="nivo-control" rel="'+i+'">'+(i+1)+'</a>');}}
$('.nivo-controlNav a:eq('+vars.currentSlide+')',slider).addClass('active');$('.nivo-controlNav a',slider).live('click',function(){if(vars.running)return false;if($(this).hasClass('active'))return false;clearInterval(timer);timer='';slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');vars.currentSlide=$(this).attr('rel')-1;nivoRun(slider,kids,settings,'control');});}
if(settings.keyboardNav){$(window).keypress(function(event){if(event.keyCode=='37'){if(vars.running)return false;clearInterval(timer);timer='';vars.currentSlide-=2;nivoRun(slider,kids,settings,'prev');}
if(event.keyCode=='39'){if(vars.running)return false;clearInterval(timer);timer='';nivoRun(slider,kids,settings,'next');}});}
if(settings.pauseOnHover){slider.hover(function(){vars.paused=true;clearInterval(timer);timer='';},function(){vars.paused=false;if(timer==''&&!settings.manualAdvance){timer=setInterval(function(){nivoRun(slider,kids,settings,false);},settings.pauseTime);}});}
slider.bind('nivo:animFinished',function(){vars.running=false;$(kids).each(function(){if($(this).is('a')){$(this).css('display','none');}});if($(kids[vars.currentSlide]).is('a')){$(kids[vars.currentSlide]).css('display','block');}
if(timer==''&&!vars.paused&&!settings.manualAdvance){timer=setInterval(function(){nivoRun(slider,kids,settings,false);},settings.pauseTime);}
settings.afterChange.call(this);});var createSlices=function(slider,settings,vars){for(var i=0;i<settings.slices;i++){var sliceWidth=Math.round(slider.width()/settings.slices);if(i==settings.slices-1){slider.append($('<div class="nivo-slice"></div>').css({left:(sliceWidth*i)+'px',width:(slider.width()-(sliceWidth*i))+'px',height:'0px',opacity:'0',background:'url("'+vars.currentImage.attr('src')+'") no-repeat -'+((sliceWidth+(i*sliceWidth))-sliceWidth)+'px 0%'}));}else{slider.append($('<div class="nivo-slice"></div>').css({left:(sliceWidth*i)+'px',width:sliceWidth+'px',height:'0px',opacity:'0',background:'url("'+vars.currentImage.attr('src')+'") no-repeat -'+((sliceWidth+(i*sliceWidth))-sliceWidth)+'px 0%'}));}}}
var createBoxes=function(slider,settings,vars){var boxWidth=Math.round(slider.width()/settings.boxCols);var boxHeight=Math.round(slider.height()/settings.boxRows);for(var rows=0;rows<settings.boxRows;rows++){for(var cols=0;cols<settings.boxCols;cols++){if(cols==settings.boxCols-1){slider.append($('<div class="nivo-box"></div>').css({opacity:0,left:(boxWidth*cols)+'px',top:(boxHeight*rows)+'px',width:(slider.width()-(boxWidth*cols))+'px',height:boxHeight+'px',background:'url("'+vars.currentImage.attr('src')+'") no-repeat -'+((boxWidth+(cols*boxWidth))-boxWidth)+'px -'+((boxHeight+(rows*boxHeight))-boxHeight)+'px'}));}else{slider.append($('<div class="nivo-box"></div>').css({opacity:0,left:(boxWidth*cols)+'px',top:(boxHeight*rows)+'px',width:boxWidth+'px',height:boxHeight+'px',background:'url("'+vars.currentImage.attr('src')+'") no-repeat -'+((boxWidth+(cols*boxWidth))-boxWidth)+'px -'+((boxHeight+(rows*boxHeight))-boxHeight)+'px'}));}}}}
var nivoRun=function(slider,kids,settings,nudge){var vars=slider.data('nivo:vars');if(vars&&(vars.currentSlide==vars.totalSlides-1)){settings.lastSlide.call(this);}
if((!vars||vars.stop)&&!nudge)return false;settings.beforeChange.call(this);if(!nudge){slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');}else{if(nudge=='prev'){slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');}
if(nudge=='next'){slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');}}
vars.currentSlide++;if(vars.currentSlide==vars.totalSlides){vars.currentSlide=0;settings.slideshowEnd.call(this);}
if(vars.currentSlide<0)vars.currentSlide=(vars.totalSlides-1);if($(kids[vars.currentSlide]).is('img')){vars.currentImage=$(kids[vars.currentSlide]);}else{vars.currentImage=$(kids[vars.currentSlide]).find('img:first');}
if(settings.controlNav){$('.nivo-controlNav a',slider).removeClass('active');$('.nivo-controlNav a:eq('+vars.currentSlide+')',slider).addClass('active');}
processCaption(settings);$('.nivo-slice',slider).remove();$('.nivo-box',slider).remove();if(settings.effect=='random'){var anims=new Array('sliceDownRight','sliceDownLeft','sliceUpRight','sliceUpLeft','sliceUpDown','sliceUpDownLeft','fold','fade','boxRandom','boxRain','boxRainReverse','boxRainGrow','boxRainGrowReverse');vars.randAnim=anims[Math.floor(Math.random()*(anims.length+1))];if(vars.randAnim==undefined)vars.randAnim='fade';}
if(settings.effect.indexOf(',')!=-1){var anims=settings.effect.split(',');vars.randAnim=anims[Math.floor(Math.random()*(anims.length))];if(vars.randAnim==undefined)vars.randAnim='fade';}
vars.running=true;if(settings.effect=='sliceDown'||settings.effect=='sliceDownRight'||vars.randAnim=='sliceDownRight'||settings.effect=='sliceDownLeft'||vars.randAnim=='sliceDownLeft'){createSlices(slider,settings,vars);var timeBuff=0;var i=0;var slices=$('.nivo-slice',slider);if(settings.effect=='sliceDownLeft'||vars.randAnim=='sliceDownLeft')slices=$('.nivo-slice',slider)._reverse();slices.each(function(){var slice=$(this);slice.css({'top':'0px'});if(i==settings.slices-1){setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=50;i++;});}
else if(settings.effect=='sliceUp'||settings.effect=='sliceUpRight'||vars.randAnim=='sliceUpRight'||settings.effect=='sliceUpLeft'||vars.randAnim=='sliceUpLeft'){createSlices(slider,settings,vars);var timeBuff=0;var i=0;var slices=$('.nivo-slice',slider);if(settings.effect=='sliceUpLeft'||vars.randAnim=='sliceUpLeft')slices=$('.nivo-slice',slider)._reverse();slices.each(function(){var slice=$(this);slice.css({'bottom':'0px'});if(i==settings.slices-1){setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=50;i++;});}
else if(settings.effect=='sliceUpDown'||settings.effect=='sliceUpDownRight'||vars.randAnim=='sliceUpDown'||settings.effect=='sliceUpDownLeft'||vars.randAnim=='sliceUpDownLeft'){createSlices(slider,settings,vars);var timeBuff=0;var i=0;var v=0;var slices=$('.nivo-slice',slider);if(settings.effect=='sliceUpDownLeft'||vars.randAnim=='sliceUpDownLeft')slices=$('.nivo-slice',slider)._reverse();slices.each(function(){var slice=$(this);if(i==0){slice.css('top','0px');i++;}else{slice.css('bottom','0px');i=0;}
if(v==settings.slices-1){setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=50;v++;});}
else if(settings.effect=='fold'||vars.randAnim=='fold'){createSlices(slider,settings,vars);var timeBuff=0;var i=0;$('.nivo-slice',slider).each(function(){var slice=$(this);var origWidth=slice.width();slice.css({top:'0px',height:'100%',width:'0px'});if(i==settings.slices-1){setTimeout(function(){slice.animate({width:origWidth,opacity:'1.0'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){slice.animate({width:origWidth,opacity:'1.0'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=50;i++;});}
else if(settings.effect=='fade'||vars.randAnim=='fade'){createSlices(slider,settings,vars);var firstSlice=$('.nivo-slice:first',slider);firstSlice.css({'height':'100%','width':slider.width()+'px'});firstSlice.animate({opacity:'1.0'},(settings.animSpeed*2),'',function(){slider.trigger('nivo:animFinished');});}
else if(settings.effect=='slideInRight'||vars.randAnim=='slideInRight'){createSlices(slider,settings,vars);var firstSlice=$('.nivo-slice:first',slider);firstSlice.css({'height':'100%','width':'0px','opacity':'1'});firstSlice.animate({width:slider.width()+'px'},(settings.animSpeed*2),'',function(){slider.trigger('nivo:animFinished');});}
else if(settings.effect=='slideInLeft'||vars.randAnim=='slideInLeft'){createSlices(slider,settings,vars);var firstSlice=$('.nivo-slice:first',slider);firstSlice.css({'height':'100%','width':'0px','opacity':'1','left':'','right':'0px'});firstSlice.animate({width:slider.width()+'px'},(settings.animSpeed*2),'',function(){firstSlice.css({'left':'0px','right':''});slider.trigger('nivo:animFinished');});}
else if(settings.effect=='boxRandom'||vars.randAnim=='boxRandom'){createBoxes(slider,settings,vars);var totalBoxes=settings.boxCols*settings.boxRows;var i=0;var timeBuff=0;var boxes=shuffle($('.nivo-box',slider));boxes.each(function(){var box=$(this);if(i==totalBoxes-1){setTimeout(function(){box.animate({opacity:'1'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){box.animate({opacity:'1'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=20;i++;});}
else if(settings.effect=='boxRain'||vars.randAnim=='boxRain'||settings.effect=='boxRainReverse'||vars.randAnim=='boxRainReverse'||settings.effect=='boxRainGrow'||vars.randAnim=='boxRainGrow'||settings.effect=='boxRainGrowReverse'||vars.randAnim=='boxRainGrowReverse'){createBoxes(slider,settings,vars);var totalBoxes=settings.boxCols*settings.boxRows;var i=0;var timeBuff=0;var rowIndex=0;var colIndex=0;var box2Darr=new Array();box2Darr[rowIndex]=new Array();var boxes=$('.nivo-box',slider);if(settings.effect=='boxRainReverse'||vars.randAnim=='boxRainReverse'||settings.effect=='boxRainGrowReverse'||vars.randAnim=='boxRainGrowReverse'){boxes=$('.nivo-box',slider)._reverse();}
boxes.each(function(){box2Darr[rowIndex][colIndex]=$(this);colIndex++;if(colIndex==settings.boxCols){rowIndex++;colIndex=0;box2Darr[rowIndex]=new Array();}});for(var cols=0;cols<(settings.boxCols*2);cols++){var prevCol=cols;for(var rows=0;rows<settings.boxRows;rows++){if(prevCol>=0&&prevCol<settings.boxCols){(function(row,col,time,i,totalBoxes){var box=$(box2Darr[row][col]);var w=box.width();var h=box.height();if(settings.effect=='boxRainGrow'||vars.randAnim=='boxRainGrow'||settings.effect=='boxRainGrowReverse'||vars.randAnim=='boxRainGrowReverse'){box.width(0).height(0);}
if(i==totalBoxes-1){setTimeout(function(){box.animate({opacity:'1',width:w,height:h},settings.animSpeed/1.3,'',function(){slider.trigger('nivo:animFinished');});},(100+time));}else{setTimeout(function(){box.animate({opacity:'1',width:w,height:h},settings.animSpeed/1.3);},(100+time));}})(rows,prevCol,timeBuff,i,totalBoxes);i++;}
prevCol--;}
timeBuff+=100;}}}
var shuffle=function(arr){for(var j,x,i=arr.length;i;j=parseInt(Math.random()*i),x=arr[--i],arr[i]=arr[j],arr[j]=x);return arr;}
var trace=function(msg){if(this.console&&typeof console.log!="undefined")
console.log(msg);}
this.stop=function(){if(!$(element).data('nivo:vars').stop){$(element).data('nivo:vars').stop=true;trace('Stop Slider');}}
this.start=function(){if($(element).data('nivo:vars').stop){$(element).data('nivo:vars').stop=false;trace('Start Slider');}}
settings.afterLoad.call(this);return this;};$.fn.nivoSlider=function(options){return this.each(function(key,value){var element=$(this);if(element.data('nivoslider'))return element.data('nivoslider');var nivoslider=new NivoSlider(this,options);element.data('nivoslider',nivoslider);});};$.fn.nivoSlider.defaults={effect:'random',slices:15,boxCols:8,boxRows:4,animSpeed:500,pauseTime:3000,startSlide:0,directionNav:true,directionNavHide:true,controlNav:true,controlNavThumbs:false,controlNavThumbsFromRel:false,controlNavThumbsSearch:'.jpg',controlNavThumbsReplace:'_thumb.jpg',keyboardNav:true,pauseOnHover:true,manualAdvance:false,captionOpacity:0.8,prevText:'Prev',nextText:'Next',beforeChange:function(){},afterChange:function(){},slideshowEnd:function(){},lastSlide:function(){},afterLoad:function(){}};$.fn._reverse=[].reverse;})(jQuery);

$(window).load(function() {
	$('#slider2').nivoSlider({
		directionNav:false,
		controlNav:false
	});
});
