<!--




//////////////////////////////////////////////////////////
//														//
//	APP Engine											//
//														//
//////////////////////////////////////////////////////////

// Construct handler
function construct(){


	//////////////////////////////////////////////////////////
	//	Class variables										//
	//////////////////////////////////////////////////////////
	this.contentLoader = new Array();
	
	
	
	

	//////////////////////////////////////////////////////////
	//	APP content loaders									//
	//////////////////////////////////////////////////////////
	
	// Content loader
	this.skyLoad = function(contentId, contentVar){
		_self = this;
		
		// Create/abort request
		if(this.contentLoader[contentId] != null){ this.contentLoader[contentId].abort(); }else{ this.contentLoader[contentId] = new Sjaks('contentLoad_'+this.contentLoader[contentId]); }
		
		// Define contentVar
		if(contentVar == null){ var contentVar = 'default'; }
		
		// Define contentVar URL
		contentVar = 'content_load_type/'+contentVar+'/';
		
		// Load content
		this.contentLoader[contentId].doGet(core.base_url+'var/page/10001/req/xmlhttp/request/content_load/content_id/'+contentId+'/'+contentVar, this.contentHTML);
	}
	this.contentHTML = function(HTML){
	
		if(HTML != 'fail'){
		
			// Get DOM ID
			HTML = HTML.split('##DOM_ID##');
			var contentHandle = HTML[0];
			HTML = HTML[1];
			
			// Load on empty content
			if(contentHandle != ''){ if(HTML == ''){
				$('#'+contentHandle).css({display: 'none'});
			
			// Load on found content
			}else{
				$('#'+contentHandle).html(HTML); 
				$('#'+contentHandle).css({display: 'block'});
				
				// Execute Javascript if found
				if(typeof contentJSLoad == "function"){ contentJSLoad(); window.contentJSLoad = ''; }
			} }
		}
		
	}
	
	
	
	

	//////////////////////////////////////////////////////////
	//	APP handlers										//
	//////////////////////////////////////////////////////////
	
	// Logout function
	this.logout = function(){
		window.location = core.base_url+'var/logout/1/';
	}
	
	// Loader
	this.load = function(){
		$('#alpha_loader_overall').css({display: 'block'});
		$('#loader_overall').css({display: 'block'});
		pos_screen('alpha_loader_overall');
		pos_screen('loader_overall');
	}
	this.stop_load = function(){
		$('#alpha_loader_overall').css({display: 'none'});
		$('#loader_overall').css({display: 'none'});
	}
	
	// Loader for layover
	this.layover_load = function(LAYER_ID){
		$('#layover_loader_'+LAYER_ID).css({display: 'block'});
	}
	
	this.layover_load_stop = function(LAYER_ID){
		$('#layover_loader_'+LAYER_ID).css({display: 'none'});
	}
	
	
	
	
	
	
	
	
	
	
	

	//////////////////////////////////////////////////////////
	//	ERROR & MESSAGE HANDLING							//
	//////////////////////////////////////////////////////////
	
	// Error display
	this.error = function(ERROR_STR, ERROR_CLOSE){
		msg_title(mt1);
		msg(ERROR_STR, ERROR_CLOSE);
	}
	
	// Message display
	this.msg = function(ERROR_STR, ERROR_CLOSE){
		msg_title(mt2);
		msg(ERROR_STR, ERROR_CLOSE);
	}
	
	
	
	
	
	
	
	

	

	//////////////////////////////////////////////////////////
	//	URL HANDLING										//
	//////////////////////////////////////////////////////////
	
	// Change URL
	this.change_url = function(get_name, get_var, get_url){
		
		// Define URL to use
		var copy_url = core.url;
		
		// Check for URL to use
		if(get_url != null && get_url != ''){ copy_url = get_url }
		
		// Save to return value
		var rebuild_url_var = copy_url;
		
		// Continue on copy url not empty
		if(copy_url != ''){
			
			// Change via loop if get name found
			copy_url_get = copy_url.split('/'+get_name+'/');
			if(copy_url_get.length <= 1){
				rebuild_url_var = copy_url+get_name+'/'+get_var+'/';
			}else{
			
				// Explode on var/ and on /
				copy_url_var = copy_url.split('var/');
				copy_url_var = copy_url_var[1].split('/');
				
				// Define new URL array
				rebuild_url_var = 'var/';
				
				// Loop through variables
				var count_inner = 1;
				for(count_loop = 0; count_loop <= copy_url_var.length-1; count_loop++){ if(copy_url_var[count_loop] != '' && copy_url_var[count_loop] != null){
					
					// On first loop check for get name
					if(count_inner == 1){ var get_mod = false; if(get_name == copy_url_var[count_loop]){ if(get_var != null && get_var != ''){ rebuild_url_var += copy_url_var[count_loop]+'/'; } get_mod = true; }else{ rebuild_url_var += copy_url_var[count_loop]+'/'; } }
					
					// On second loop handle get value
					if(count_inner == 2){ if(get_mod){ if(get_var != null && get_var != ''){ rebuild_url_var += get_var+'/'; } }else{ rebuild_url_var += copy_url_var[count_loop]+'/'; } }
					
					// Handle inner count
					if(count_inner == 2){ count_inner = 1; }else{ count_inner++; }
				} }
			}
		}
		
		// Save rebuilded var to claass
		if(get_url != null && get_url != ''){ return rebuild_url_var; }else{ core.url = rebuild_url_var; }
	}
	
	// Get the current url
	this.url = function(){
		return core.url;
	}
	
	
}

// Create class var
var construct = new construct();









//////////////////////////////////////////////////////////
//														//
//	Images preloading									//
//														//
//////////////////////////////////////////////////////////

var select_load = new Image(); select_load.src = core.image_url+'img/graphics/selectbox_loader.gif';

var slide_control = new Array();
slide_control["left"] = new Image(); slide_control["left"].src = core.image_url+'img/graphics/slide_left.png';
slide_control["right"] = new Image(); slide_control["right"].src = core.image_url+'img/graphics/slide_right.png';
slide_control["item"] = new Image(); slide_control["item"].src = core.image_url+'img/graphics/slide_item.png';
slide_control["itemsel"] = new Image(); slide_control["itemsel"].src = core.image_url+'img/graphics/slide_item_sel.png';

slide_control["left_over"] = new Image(); slide_control["left_over"].src = core.image_url+'img/graphics/slide_left_over.png';
slide_control["right_over"] = new Image(); slide_control["right_over"].src = core.image_url+'img/graphics/slide_right_over.png';
slide_control["item_over"] = new Image(); slide_control["item_over"].src = core.image_url+'img/graphics/slide_item_over.png';
slide_control["itemsel_over"] = new Image(); slide_control["itemsel_over"].src = core.image_url+'img/graphics/slide_item_sel_over.png';

var title_load = new Image(); title_load.src = core.image_url+'img/titles.png';




//////////////////////////////////////////////////////////
//														//
//	Document ready functions							//
//														//
//////////////////////////////////////////////////////////

// Document ready image handler
var sky_slider_interval = '';
var skyslide_time = 2000;
function app_doc_ready_images(){

	// Input bind on document ready
	app_doc_ready_input();
	
	// Button bind on document ready
	app_doc_ready_btn();
	
	// Handle logo
	$('#sky_logo').css({cursor: 'pointer'});
	$('#sky_logo').mouseup(function(event){ window.location = core.base_url; });
	
	// Handle navigation
	$('#sky_nav_'+core.language_id+' li:nth-child(1)').mousemove(function(){ $(this).parents('ul:first').css({backgroundPosition: '0px -5px'}); });
	$('#sky_nav_'+core.language_id+' li:nth-child(2)').mousemove(function(){ $(this).parents('ul:first').css({backgroundPosition: '0px -70px'}); });
	$('#sky_nav_'+core.language_id+' li:nth-child(3)').mousemove(function(){ $(this).parents('ul:first').css({backgroundPosition: '0px -135px'}); });
	$('#sky_nav_'+core.language_id+' li:nth-child(4)').mousemove(function(){ $(this).parents('ul:first').css({backgroundPosition: '0px -200px'}); });
	$('#sky_nav_'+core.language_id+' li:nth-child(5)').mousemove(function(){ $(this).parents('ul:first').css({backgroundPosition: '0px -265px'}); });
	$('#sky_nav_'+core.language_id+' li').mouseout(function(){ $(this).parents('ul:first').css({backgroundPosition: '0px -330px'}); });
	$('#sky_nav_'+core.language_id+' li').mouseup(function(){ window.location = $(this).find('a').attr('href'); });
	$('#sky_nav_'+core.language_id+' li').attr('li_url', $(this).find('a:first').attr('href'));
	$('#sky_nav_'+core.language_id+' li a').html('');
	$('#sky_nav_'+core.language_id+' li a').click(function(event){ event.preventDefault(); });
	
	// Execute switch
	if(typeof skybot_time != 'undefined'){ setInterval("skybot_switch();", skybot_time); }
	
	// Replace titles
	sky_titles();
	
	// Replace buttons
	sky_buttons();
	
	// Replace hyperlinks
	sky_links();
}




// Slider init
var skyslide = 1;
var skyslide_loop = 1;
var cs_top = -190;
var cs_left = 600;
function sky_slider_init(){

	// Add elements
	$('#sky_slider').append('<div id="sky_slide_control"></div>');
	
	// Build control elements
	if(skyslide > 1){
	
		// Append left button
		//$('#sky_slide_control').append('<img src="'+slide_control["left"].src+'" alt="" id="sky_slide_navl" />');
		
		// Append first icon
		$('#sky_slide_control').append('<img src="'+slide_control["itemsel"].src+'" alt="" class="sky_slide_item_sel" id="sky_slide_icon_1" />');
		
		// Append icons
		for(cs = 2; cs <= skyslide; cs++){ $('#sky_slide_control').append('<img src="'+slide_control["item"].src+'" alt="" class="sky_slide_item" id="sky_slide_icon_'+cs+'" />'); }
	
		// Append right button
		//$('#sky_slide_control').append('<img src="'+slide_control["right"].src+'" alt="" id="sky_slide_navr" />');
		
		// Handle binds
		sky_slider_control();
		
	}
	
	// Bind mouseup for slides
	$('#sky_slide ul li').each(function(){
		$(this).attr('lili', $(this).find('a:first').attr('href'));
		$(this).css({cursor: 'pointer'});
	});
	$('#sky_slide ul li').mouseup(function(){ window.location = $(this).attr('lili'); });
	
	// Handle buttons
	 sky_buttons();
	
	// Execute slider
	sky_slider_interval = setInterval("sky_slider();", skyslide_time);
}




// Slider control bind
function sky_slider_control(){
	$('#sky_slide_navl').unbind();
	$('#sky_slide_navr').unbind();
	
	if(skyslide_loop != 1){ $('#sky_slide_navl').css({cursor: 'pointer'}); }else{ $('#sky_slide_navl').css({cursor: 'default'}); }
	if(skyslide_loop != skyslide){ $('#sky_slide_navr').css({cursor: 'pointer'}); }else{ $('#sky_slide_navr').css({cursor: 'default'}); }
	
	if(skyslide_loop != 1){ $('#sky_slide_navl').mousemove(function(){ $(this).attr('src', slide_control["left_over"].src); }); }
	if(skyslide_loop != skyslide){ $('#sky_slide_navr').mousemove(function(){ $(this).attr('src', slide_control["right_over"].src); }); }
	
	if(skyslide_loop != 1){ $('#sky_slide_navl').mouseout(function(){ $(this).attr('src', slide_control["left"].src); }); }
	if(skyslide_loop != skyslide){ $('#sky_slide_navr').mouseout(function(){ $(this).attr('src', slide_control["right"].src); }); }
	
	
	$('#sky_slide_item_sel').unbind();
	$('#sky_slide_item').unbind();
	
	//$('.sky_slide_item_sel').mousemove(function(){ $(this).attr('src', slide_control["itemsel_over"].src); });
	//$('.sky_slide_item').mousemove(function(){ $(this).attr('src', slide_control["item_over"].src); });
	
	//$('.sky_slide_item_sel').mouseout(function(){ $(this).attr('src', slide_control["itemsel"].src); });
	//$('.sky_slide_item').mouseout(function(){ $(this).attr('src', slide_control["item"].src); });
}





// Slider
function sky_slider(){
	
	// Set vars to use
	var skyslide_loop1 = skyslide_loop;
	var skyslide_loop2 = skyslide_loop+1;

	// Reset element
	if(skyslide_loop >= skyslide){ skyslide_loop2 = 1; skyslide_loop = 0; }
	
	// Position upcoming element
	$('#sky_slide ul li:nth-child('+(skyslide_loop2)+')').css({left: '600px'});
	
	// Slide & fade <li>
	$('#sky_slide ul li:nth-child('+skyslide_loop1+')').animate({mozOpacity: '0', filter: 'alpha(opacity=0)', opacity: '0', left: '-600px'}, 750);
	$('#sky_slide ul li:nth-child('+(skyslide_loop2)+')').animate({mozOpacity: '.99', filter: 'alpha(opacity=99)', opacity: '.99', left: '0px'}, 750, function(){
	
		// Set to full z-index
		$('#sky_slide ul li:nth-child('+skyslide_loop1+')').css({zIndex: '4'});
		$('#sky_slide ul li:nth-child('+skyslide_loop2+')').css({zIndex: '5'});
	
		// Demark icon
		$('#sky_slide_icon_'+skyslide_loop1).attr('src', slide_control["item"].src);
		$('#sky_slide_icon_'+skyslide_loop1).attr('class', 'sky_slide_item');
		
		// Mark icon
		$('#sky_slide_icon_'+skyslide_loop2).attr('src', slide_control["itemsel"].src);
		$('#sky_slide_icon_'+skyslide_loop2).attr('class', 'sky_slide_item_sel');
		
		// Rebind controls
		sky_slider_control();
		
	});
	
	// Add to slide count
	skyslide_loop++;
}




// Skybot switch
var skybot_switch_id = 1;
function skybot_switch(){
	$('#sky_bot img:nth-child('+skybot_switch_id+')').fadeOut('fast', function(){
		if(skybot_switch_id >= skybot_images.length-1){ skybot_switch_id = 0; }
		$('#sky_bot img:nth-child('+(skybot_switch_id+1)+')').fadeIn('fast');
		skybot_switch_id++;
	});
}




// Replace titles
function sky_titles(){

	// h2
	$('h2.replace').each(function(){
		var rep_h2 = $(this).attr('class').split(' '); rep_h2 = rep_h2[1];
		$(this).parent().html('<div style="background-position:0px -'+rep_h2+'px;" class="sky_title_'+core.language_id+'"></div>');
	});
}



// Replace hyperlinks
function sky_links(){
	$('a.link_replace').each(function(){
		var bg_pos = $(this).attr('class').split(' ');
		bg_width = bg_pos[2];
		bg_pos = bg_pos[1];
		$(this).parent().html('<div onmouseup="window.location = \''+$(this).attr('href')+'\';" link_url="'+$(this).attr('href')+'" class="sky_link" style="background-position:-5px -'+bg_pos+'px;width:'+bg_width+'px;"></div>');
	});
	$('.sky_link').unbind();
	$('.sky_link').mousemove(function(){ $(this).attr('class', 'sky_link_alpha'); });
	$('.sky_link').mouseout(function(){ $(this).attr('class', 'sky_link'); });
}



// Replace buttons
function sky_buttons(){
	$('.btn_replaced').find('a:first').css({display: 'none'});
	$('.btn_replaced').unbind();
	$('.btn_replaced').mousemove(function(){ $(this).css({backgroundPosition: '0px -45px'}); });
	$('.btn_replaced').mouseout(function(){ $(this).css({backgroundPosition: '0px 0px'}); });
	$('.btn_replaced').mouseup(function(){
		var rp_link = $(this).find('a:first').attr('href').split('javascript: ');
		if(rp_link.length == 2){ eval(rp_link[1]); }else{ window.location = $(this).find('a:first').attr('href'); }
	});
	$('.btn_replacedm_'+core.language_id).find('a:first').css({display: 'none'});
	$('.btn_replacedm_'+core.language_id).unbind();
	$('.btn_replacedm_'+core.language_id).mousemove(function(){ $(this).css({backgroundPosition: '0px -45px'}); });
	$('.btn_replacedm_'+core.language_id).mouseout(function(){ $(this).css({backgroundPosition: '0px 0px'}); });
	$('.btn_replacedm_'+core.language_id).mouseup(function(){
		var rp_link = $(this).find('a:first').attr('href').split('javascript: ');
		if(rp_link.length == 2){ eval(rp_link[1]); }else{ window.location = $(this).find('a:first').attr('href'); }
	});
	$('.btn_replacedmo_'+core.language_id).find('a:first').css({display: 'none'});
	$('.btn_replacedmo_'+core.language_id).unbind();
	$('.btn_replacedmo_'+core.language_id).mousemove(function(){ $(this).css({backgroundPosition: '0px -45px'}); });
	$('.btn_replacedmo_'+core.language_id).mouseout(function(){ $(this).css({backgroundPosition: '0px 0px'}); });
	$('.btn_replacedmo_'+core.language_id).mouseup(function(){
		var rp_link = $(this).find('a:first').attr('href').split('javascript: ');
		if(rp_link.length == 2){ eval(rp_link[1]); }else{ window.location = $(this).find('a:first').attr('href'); }
	});
}



// Document ready image static handler
function app_doc_ready_images_static(){

	// Add loader
	$('body').append('<div id="alpha_loader_overall"></div>');
	$('body').append('<img src="'+core.image_url+'img/graphics/loader_overall.gif" alt="" id="loader_overall" />');
	
	
}







//////////////////////////////////////////////////////////
//														//
//	APP Graphics										//
//														//
//////////////////////////////////////////////////////////




//////////////////////////////////////////////////////////
//	Buttons												//
//////////////////////////////////////////////////////////
	
// Bind function for document ready buttons
function app_doc_ready_btn(){

	// Unbind functions
	$('.btn').unbind();
	$('.btn_sel').unbind();
	$('.btn_dea').unbind();
	$('.small_btn').unbind();
	$('.small_btn_sel').unbind();
	$('.small_btn_dea').unbind();
	$('.btn_q').unbind();
	$('.layover_close').unbind();

	// Bind function for mouseover
	$('.btn').mousemove(function(event){ btn_over(this); });
	$('.btn_sel').mousemove(function(event){ btn_over(this); });
	$('.btn_dea').mousemove(function(event){ btn_over(this); });
	$('.small_btn').mousemove(function(event){ small_btn_over(this); });
	$('.small_btn_sel').mousemove(function(event){ small_btn_over(this); });
	$('.small_btn_dea').mousemove(function(event){ small_btn_over(this); });
	$('.btn_q').mousemove(function(event){ btn_q_over(event, this.id); });
	$('.layover_close').mousemove(function(event){ $(this).css({backgroundPosition: '-245px -285px'}); });

	// Bind function for mouseout
	$('.btn').mouseout(function(event){ btn_out(this); });
	$('.btn_sel').mouseout(function(event){ btn_out(this); });
	$('.btn_dea').mouseout(function(event){ btn_out(this); });
	$('.small_btn').mouseout(function(event){ small_btn_out(this); });
	$('.small_btn_sel').mouseout(function(event){ small_btn_out(this); });
	$('.small_btn_dea').mouseout(function(event){ small_btn_out(this); });
	$('.btn_q').mouseout(function(event){ btn_q_out(this.id); });
	$('.layover_close').mouseout(function(event){ $(this).css({backgroundPosition: '-200px -285px'}); });
	
	
}	

	
// Handle button over
function btn_over(LOAD_TAG_ID){
	$('table#'+LOAD_TAG_ID.id+' td.btn_left').attr('class', 'btn_left_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_left_join').attr('class', 'btn_left_join_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_center').attr('class', 'btn_center_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_right').attr('class', 'btn_right_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_right_join').attr('class', 'btn_right_join_over');
	$('table#'+LOAD_TAG_ID.id+' span.color_btn').attr('class', 'color_btn_over');
	
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_left').attr('class', 'btn_sel_left_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_left_join').attr('class', 'btn_sel_left_join_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_center').attr('class', 'btn_sel_center_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_right').attr('class', 'btn_sel_right_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_right_join').attr('class', 'btn_sel_right_join_over');
	$('table#'+LOAD_TAG_ID.id+' span.color_btn_sel').attr('class', 'color_btn_sel_over');
	
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_left').attr('class', 'btn_de_left_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_left_join').attr('class', 'btn_de_left_join_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_center').attr('class', 'btn_de_center_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_right').attr('class', 'btn_de_right_over');
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_right_join').attr('class', 'btn_de_right_join_over');
	$('table#'+LOAD_TAG_ID.id+' span.color_btn_de').attr('class', 'color_btn_de_over');
}
	
// Handle button out
function btn_out(LOAD_TAG_ID){
	$('table#'+LOAD_TAG_ID.id+' td.btn_left_over').attr('class', 'btn_left');
	$('table#'+LOAD_TAG_ID.id+' td.btn_left_join_over').attr('class', 'btn_left_join');
	$('table#'+LOAD_TAG_ID.id+' td.btn_center_over').attr('class', 'btn_center');
	$('table#'+LOAD_TAG_ID.id+' td.btn_right_over').attr('class', 'btn_right');
	$('table#'+LOAD_TAG_ID.id+' td.btn_right_join_over').attr('class', 'btn_right_join');
	$('table#'+LOAD_TAG_ID.id+' span.color_btn_over').attr('class', 'color_btn');
	
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_left_over').attr('class', 'btn_sel_left');
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_left_join_over').attr('class', 'btn_sel_left_join');
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_center_over').attr('class', 'btn_sel_center');
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_right_over').attr('class', 'btn_sel_right');
	$('table#'+LOAD_TAG_ID.id+' td.btn_sel_right_join_over').attr('class', 'btn_sel_right_join');
	$('table#'+LOAD_TAG_ID.id+' span.color_btn_sel_over').attr('class', 'color_btn_sel');
	
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_left_over').attr('class', 'btn_de_left');
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_left_join_over').attr('class', 'btn_de_left_join');
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_center_over').attr('class', 'btn_de_center');
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_right_over').attr('class', 'btn_de_right');
	$('table#'+LOAD_TAG_ID.id+' td.btn_de_right_join_over').attr('class', 'btn_de_right_join');
	$('table#'+LOAD_TAG_ID.id+' span.color_btn_de_over').attr('class', 'color_btn_de');
}
	
	
// Handle small button over
function small_btn_over(LOAD_TAG_ID){
	var checko = $(LOAD_TAG_ID).attr('class').split('_over');
	if(checko.length <= 1){ $(LOAD_TAG_ID).attr('class', $(LOAD_TAG_ID).attr('class')+'_over'); }
	$('div#'+LOAD_TAG_ID.id+' span.color_btn').attr('class', 'color_btn_over');
	$('div#'+LOAD_TAG_ID.id+' span.color_btn_sel').attr('class', 'color_btn_sel_over');
	$('div#'+LOAD_TAG_ID.id+' span.color_btn_dea').attr('class', 'color_btn_dea_over');
}
	
// Handle small button out
function small_btn_out(LOAD_TAG_ID){
	var checko = $(LOAD_TAG_ID).attr('class').split('_over');
	if(checko.length > 1){ $(LOAD_TAG_ID).attr('class', checko[0]); }
	$('div#'+LOAD_TAG_ID.id+' span.color_btn_over').attr('class', 'color_btn');
	$('div#'+LOAD_TAG_ID.id+' span.color_btn_sel_over').attr('class', 'color_btn_sel');
	$('div#'+LOAD_TAG_ID.id+' span.color_btn_dea_over').attr('class', 'color_btn_dea');
}


// Function for handling questionmark button over
function btn_q_over(event, LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	var btn_msg = $('#btn_q_msg_'+tag_id).val();
	mouse_msg(event, '_'+btn_msg);
	$('#'+LOAD_TAG_ID).css({backgroundPosition: '-5px -315px'});
}


// Function for handling questionmark button out
function btn_q_out(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	mouse_msg_hide();
	$('#'+LOAD_TAG_ID).css({backgroundPosition: '-5px -285px'});
}





//////////////////////////////////////////////////////////
//	Inputs												//
//////////////////////////////////////////////////////////

// Bind function for document ready inputs
function app_doc_ready_input(){

	// Handle questionmark for text inputs
	$('.app_input_left_q1').unbind();
	$('.app_input_left_q1').mousemove(function(event){ input_q_over(this); mouse_msg(event, this.id); });
	$('.app_input_left_q1').mouseout(function(event){ input_q_out(this); mouse_msg_hide(); });
	
	// Handle focus click for text inputs
	$('.app_input').unbind();
	$('.app_input').mouseup(function(event){ focus_input(this); });
	
	// Handle focus click for textarea
	$('.app_textarea').unbind();
	$('.app_textarea').mouseup(function(event){ focus_textarea(this); });

	// Handle questionmark for select inputs
	$('.app_select_left_q1').unbind();
	$('.app_select_left_q1').mousemove(function(event){ input_q_over(this); mouse_msg(event, this.id); });
	$('.app_select_left_q1').mouseout(function(event){ input_q_out(this); mouse_msg_hide(); });
	
	// Handle mouseover/mouseout/click for selectbox
	$('.app_select').unbind();
	$('.app_select').mousemove(function(event){ select_over(this.id); });
	$('.app_select').mouseout(function(event){ select_out(this.id); });
	$('.app_select').mouseup(function(event){ select_click(this.id); });

	// Handle questionmark for select inputs
	$('.app_drop_left_q1').unbind();
	$('.app_drop_left_q1').mousemove(function(event){ input_q_over(this); mouse_msg(event, this.id); });
	$('.app_drop_left_q1').mouseout(function(event){ input_q_out(this); mouse_msg_hide(); });
	
	// Handle mouseover/mouseout/click for selectbox
	$('.app_drop').unbind();
	$('.app_drop').mousemove(function(event){ drop_over(this.id); });
	$('.app_drop').mouseout(function(event){ drop_out(this.id); });
	$('.app_drop').mouseup(function(event){ drop_click(this.id); });
	
	// Handle click for checkbox inputs
	$('.app_box').unbind();
	$('.app_box').mouseup(function(event){ box_click(this.id); });
	$('.app_box').mouseover(function(event){ box_over(this.id); });
	$('.app_box').mouseout(function(event){ box_out(this.id); });
	
	// Handle click for checkbox input labels
	$('.app_box_label').unbind();
	$('.app_box_label').mouseup(function(event){ var tag_id = get_id_tag(this.id); box_click('app_box_'+tag_id); });
	$('.app_box_label').mouseover(function(event){ var tag_id = get_id_tag(this.id); box_over('app_box_'+tag_id); });
	$('.app_box_label').mouseout(function(event){ var tag_id = get_id_tag(this.id); box_out('app_box_'+tag_id); });
	
}


// Function for focussing on an input when clicking on the surrounding images
function focus_input(LOAD_TAG_ID){
	$('table#'+LOAD_TAG_ID.id+' input').focus();
}
function focus_textarea(LOAD_TAG_ID){
	$('table#'+LOAD_TAG_ID.id+' textarea').focus();
}

// Function for mouseover questionmark
function input_q_over(LOAD_TAG_ID){
	var checko = $(LOAD_TAG_ID).attr('class').split('_over');
	if(checko.length <= 1){ $(LOAD_TAG_ID).attr('class', $(LOAD_TAG_ID).attr('class')+'_over'); }
}

// Function for mouseout questionmark
function input_q_out(LOAD_TAG_ID){
	var checko = $(LOAD_TAG_ID).attr('class').split('_over');
	if(checko.length > 1){ $(LOAD_TAG_ID).attr('class', checko[0]); }
}


// Function for select mouseover
var select_timer = '';
function select_over(LOAD_TAG_ID){
	clearTimeout(select_timer);
	var tag_id = get_id_tag(LOAD_TAG_ID);
	if(current_select_load != LOAD_TAG_ID){ $('#app_select_load').remove(); select_reset(); current_select_load = ''; }
	if(!current_select_loading){ $('#app_select_right_'+tag_id).css({backgroundPosition: '-85px -135px'}); }
}

// Function for select mouseout
function select_out(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	if(!current_select_loading){ $('#app_select_right_'+tag_id).css({backgroundPosition: '-5px -135px'}); }
	clearTimeout(select_timer);
	select_timer = setTimeout("select_hide();", 100);
}
function select_hide(){
	if(current_select_load != ''){
		var tag_id = get_id_tag(current_select_load);
		$('#app_select_right_'+tag_id).css({backgroundPosition: '-5px -135px'});
		$('#app_select_right_'+tag_id).html('');
		request_select_url.abort();
	}
	clearTimeout(select_timer);
	$('#app_select_load').remove();
	current_select_load = '';
}

// Function for clicking on checkbox
var current_select_load = '';
var request_select_url = new Sjaks('request_select_url');
var current_select_loading = false;
function select_click(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	clearTimeout(select_timer);
	$('#app_select_load').remove();
	if(current_select_load == LOAD_TAG_ID){ current_select_load = ''; }else{
		current_select_load = LOAD_TAG_ID;
		var select_url = $('#app_select_hid_url_'+tag_id).val();
		if(select_url != '' && select_url != 'build'){
			$('#app_select_right_'+tag_id).css({backgroundPosition: '-45px -135px'});
			$('#app_select_right_'+tag_id).html('<img src="'+select_load.src+'" alt="" id="app_select_loader" />');
			$('#app_select_loader').mouseover(function(event){ select_over(current_select_load); });
			$('#app_select_loader').mousemove(function(event){ select_over(current_select_load); });
			request_select_url.abort();
			current_select_loading = true;
			request_select_url.doGet(select_url, select_show);
		}else if(select_url == 'build'){
			var li_count = $('#app_select_ul_'+tag_id).attr('class').split(' '); li_count = li_count[1];
			var li_string = '';
			if(is_numeric(li_count)){ for(count_li = 1; count_li <= li_count; count_li++){
				var li_value = $('#app_select_li_'+tag_id+'_'+count_li).html();
				var li_id = $('#app_select_li_'+tag_id+'_'+count_li).attr('class').split(' '); li_id = li_id[1];
				var bottom_css = ''; if(count_li == li_count){ bottom_css = '_bottom'; }
				li_string += '<tr><td class="select_sub_left'+bottom_css+'" id="app_subselect_left_'+count_li+'"></td><td valign="top" class="select_sub_inline'+bottom_css+'" id="app_subselect_'+count_li+'"><div class="select_sub_pos'+bottom_css+'" id="select_sub_pos_'+count_li+'">'+li_value+'<input type="hidden" id="select_sub_hid_'+count_li+'" name="select_sub_hid_'+count_li+'" value="'+li_id+'" /></div></td><td class="select_sub_right'+bottom_css+'" id="app_subselect_right_'+count_li+'"></td></tr>';
			} }
			if(li_string != ''){ select_show(li_string); }
		}
	}
}

// Function for resetting
function select_reset(SELECT_OVER){
	if(current_select_load != ''){
		current_select_loading = false;
		request_select_url.abort();
		var tag_id = get_id_tag(current_select_load);
		$('#app_select_right_'+tag_id).html('');
		if(SELECT_OVER != null){ $('#app_select_right_'+tag_id).css({backgroundPosition: '-85px -135px'}); }else{ $('#app_select_right_'+tag_id).css({backgroundPosition: '-5px -135px'}); }
	}
}

// Function for showing select layer after xmlhttp request
function select_show(HTML){
	current_select_loading = false;
	if(current_select_load != '' && HTML != 'fail' && HTML != ''){
		select_reset(true);
		var select_width = $('#'+current_select_load).width();
		var select_pos = $('#'+current_select_load).offset();
		if(is_numeric(select_width) && select_width > 0){

			// Append the select layer
			$('body').append('<table id="app_select_load" border="0" cellspacing="0" cellpadding="0">'+HTML+'</table>');
			$('#app_select_load').css({width: (select_width+2)+'px'});
			$('#app_select_load').css({left: select_pos.left+'px'});
			$('#app_select_load').css({top: (select_pos.top+35)+'px'});
			
			// Bind the mouseover/out functions to outer table
			$('#app_select_load').mousemove(function(event){ select_over(current_select_load); });
			$('#app_select_load').mouseout(function(event){ select_out(current_select_load); });
			
			// Bind the mouseover/out functions to list
			$('.select_sub_inline').mouseover(function(event){ select_sub_over(this.id); });
			$('.select_sub_inline').mouseout(function(event){ select_sub_out(this.id); });
			$('.select_sub_inline').mouseup(function(event){ select_sub_click(this.id); });
			$('.select_sub_left').mouseover(function(event){ select_sub_over(this.id); });
			$('.select_sub_left').mouseout(function(event){ select_sub_out(this.id); });
			$('.select_sub_left').mouseup(function(event){ select_sub_click(this.id); });
			$('.select_sub_right').mouseover(function(event){ select_sub_over(this.id); });
			$('.select_sub_right').mouseout(function(event){ select_sub_out(this.id); });
			$('.select_sub_right').mouseup(function(event){ select_sub_click(this.id); });
			$('.select_sub_inline_bottom').mouseover(function(event){ select_sub_over(this.id); });
			$('.select_sub_inline_bottom').mouseout(function(event){ select_sub_out(this.id); });
			$('.select_sub_inline_bottom').mouseup(function(event){ select_sub_click(this.id); });
			$('.select_sub_left_bottom').mouseover(function(event){ select_sub_over(this.id); });
			$('.select_sub_left_bottom').mouseout(function(event){ select_sub_out(this.id); });
			$('.select_sub_left_bottom').mouseup(function(event){ select_sub_click(this.id); });
			$('.select_sub_right_bottom').mouseover(function(event){ select_sub_over(this.id); });
			$('.select_sub_right_bottom').mouseout(function(event){ select_sub_out(this.id); });
			$('.select_sub_right_bottom').mouseup(function(event){ select_sub_click(this.id); });
		}
	}
}

// Function for sub list click
function select_sub_click(LOAD_TAG_ID){
	if(current_select_load != ''){
		var select_tag_id = get_id_tag(current_select_load);
		var tag_id = get_id_tag(LOAD_TAG_ID);
		var hid_val = $('#select_sub_hid_'+tag_id).val();
		var input_id = $('#app_select_hid_'+select_tag_id).val();
		$('#'+input_id).val(hid_val);
		$('#app_select_text_'+select_tag_id).html($('#select_sub_pos_'+tag_id).html());
		$('#app_select_load').remove();
		select_reset();
		current_select_load = '';
		var click_function = $('#app_select_hid_click_'+select_tag_id).val();
		eval(click_function);
	}
}
	

// Function for sub list mouseover
function select_sub_over(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	
	// Check for class type
	var nav_sub_bottom = $('#app_subselect_'+tag_id).attr("class").split('bottom');
	
	// Handle submenu over
	if(nav_sub_bottom.length > 1){
		$('#app_subselect_left_'+tag_id).css({backgroundPosition: '-19px -370px'});
		$('#app_subselect_'+tag_id).css({backgroundPosition: '0px -14px'});
		$('#app_subselect_right_'+tag_id).css({backgroundPosition: '-160px -370px'});
	}else{
		$('#app_subselect_left_'+tag_id).css({backgroundPosition: '-19px -310px'});
		$('#app_subselect_'+tag_id).css({backgroundPosition: '0px 0px'});
		$('#app_subselect_right_'+tag_id).css({backgroundPosition: '-160px -310px'});
	}
}

// Function for sub list mouseout
function select_sub_out(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	
	// Check for class type
	var nav_sub_bottom = $('#app_subselect_'+tag_id).attr("class").split('bottom');
	
	// Handle submenu over
	if(nav_sub_bottom.length > 1){
		$('#app_subselect_left_'+tag_id).css({backgroundPosition: '-19px -235px'});
		$('#app_subselect_'+tag_id).css({backgroundPosition: '0px -97px'});
		$('#app_subselect_right_'+tag_id).css({backgroundPosition: '-160px -235px'});
	}else{
		$('#app_subselect_left_'+tag_id).css({backgroundPosition: '-19px -175px'});
		$('#app_subselect_'+tag_id).css({backgroundPosition: '0px -75px'});
		$('#app_subselect_right_'+tag_id).css({backgroundPosition: '-160px -175px'});
	}
}





// Function for dropbox mouseover
var current_drop_load = '';
var current_drop_loading = '';
function drop_over(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	if(current_drop_loading != LOAD_TAG_ID){ $('#app_drop_right_'+tag_id).css({backgroundPosition: '-85px -135px'}); }
}

// Function for dropbox mouseout
function drop_out(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	if(current_drop_loading != LOAD_TAG_ID){ $('#app_drop_right_'+tag_id).css({backgroundPosition: '-5px -135px'}); }
}

// Function for clicking on drop box
var request_drop_url = new Sjaks('request_drop_url');
var mgm_dropbox_id = '';
function drop_click(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	current_drop_load = LOAD_TAG_ID;
	current_drop_loading = LOAD_TAG_ID;
	var drop_url = $('#app_drop_hid_url_'+tag_id).val();
	$('#app_drop_right_'+tag_id).css({backgroundPosition: '-45px -135px'});
	$('#app_drop_right_'+tag_id).html('<img src="'+select_load.src+'" alt="" id="app_drop_loader" />');
	$('#app_drop_loader').mouseover(function(event){ drop_over(LOAD_TAG_ID); });
	$('#app_drop_loader').mousemove(function(event){ drop_over(LOAD_TAG_ID); });
	request_drop_url.abort();
	request_drop_url.doGet(drop_url, drop_click_html);
}
function drop_click_html(HTML){
	if(current_drop_load != ''){
		current_drop_loading = '';
		var tag_id = get_id_tag(current_drop_load);
		$('#app_drop_right_'+tag_id).css({backgroundPosition: '-5px -135px'});
		$('#app_drop_right_'+tag_id).html('');
		if(mgm_dropbox_id != ''){
			window.parent.layover(mgm_dropbox_id, true, HTML);
			if(typeof drop_click_after == "function"){ drop_click_after(); }
		}
	}
}






// Function for handling checkbox click
function box_click(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	
	// Get added object name
	var obj_name = LOAD_TAG_ID.split('app_box_');
	obj_name = obj_name[1].split('_');
	obj_name = obj_name[0];
	if(obj_name != '' && !is_numeric(obj_name)){ tag_id = obj_name+'_'+tag_id; }
	
	// Get status from hidden checkbox input
	var box_status = $('#'+$('#app_box_hid_'+tag_id).val()).attr("checked");

	// Load normal image
	if(box_status == 'checked' || box_status == true){
		$('#'+$('#app_box_hid_'+tag_id).val()).attr("checked", "");
		$('#'+$('#app_box_hid_'+tag_id).val()).attr("value", "");
		$('#'+LOAD_TAG_ID).css({backgroundPosition: '-45px -175px'});
	}else{
		$('#'+$('#app_box_hid_'+tag_id).val()).attr("checked", "checked");
		$('#'+$('#app_box_hid_'+tag_id).val()).attr("value", $('#app_box_val_'+tag_id).val());
		$('#'+LOAD_TAG_ID).css({backgroundPosition: '-65px -175px'});
	}
}

// Function for handling checkbox click out
function box_click_out(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	
	// Get added object name
	var obj_name = LOAD_TAG_ID.split('app_box_');
	obj_name = obj_name[1].split('_');
	obj_name = obj_name[0];
	if(obj_name != '' && !is_numeric(obj_name)){ tag_id = obj_name+'_'+tag_id; }

	// Load normal image
	$('#'+$('#app_box_hid_'+tag_id).val()).attr("checked", "");
	$('#'+$('#app_box_hid_'+tag_id).val()).attr("value", "");
	$('#'+LOAD_TAG_ID).css({backgroundPosition: '-5px -175px'});
}

// Function for handling checkbox click in without mouseover
function box_click_in(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	
	// Get added object name
	var obj_name = LOAD_TAG_ID.split('app_box_');
	obj_name = obj_name[1].split('_');
	obj_name = obj_name[0];
	if(obj_name != '' && !is_numeric(obj_name)){ tag_id = obj_name+'_'+tag_id; }
	
	// Get status from hidden checkbox input
	var box_status = $('#'+$('#app_box_hid_'+tag_id).val()).attr("checked");

	// Load normal image
	$('#'+$('#app_box_hid_'+tag_id).val()).attr("checked", "checked");
	$('#'+$('#app_box_hid_'+tag_id).val()).attr("value", $('#app_box_val_'+tag_id).val());
	$('#'+LOAD_TAG_ID).css({backgroundPosition: '-25px -175px'});
}

// Function for checking box selected status
function box_check(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	
	// Get added object name
	var obj_name = LOAD_TAG_ID.split('app_box_');
	obj_name = obj_name[1].split('_');
	obj_name = obj_name[0];
	if(obj_name != '' && !is_numeric(obj_name)){ tag_id = obj_name+'_'+tag_id; }
	
	// Get status from hidden checkbox input
	var box_status = $('#'+$('#app_box_hid_'+tag_id).val()).attr("checked");

	// Load normal image
	if(box_status == 'checked' || box_status == true){
		return true;
	}else{
		return false;
	}
}

// Function for handling checkbox mouseover
function box_over(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	
	// Get added object name
	var obj_name = LOAD_TAG_ID.split('app_box_');
	obj_name = obj_name[1].split('_');
	obj_name = obj_name[0];
	if(obj_name != '' && !is_numeric(obj_name)){ tag_id = obj_name+'_'+tag_id; }
	
	// Get status from hidden checkbox input
	var box_status = $('#'+$('#app_box_hid_'+tag_id).val()).attr("checked");
	
	// Load normal image
	if(box_status == 'checked' || box_status == true){
		$('#'+LOAD_TAG_ID).css({backgroundPosition: '-65px -175px'});
	}else{
		$('#'+LOAD_TAG_ID).css({backgroundPosition: '-45px -175px'});
	}
}

// Function for handling checkbox mouseout
function box_out(LOAD_TAG_ID){
	var tag_id = get_id_tag(LOAD_TAG_ID);
	
	// Get added object name
	var obj_name = LOAD_TAG_ID.split('app_box_');
	obj_name = obj_name[1].split('_');
	obj_name = obj_name[0];
	if(obj_name != '' && !is_numeric(obj_name)){ tag_id = obj_name+'_'+tag_id; }
	
	// Get status from hidden checkbox input
	var box_status = $('#'+$('#app_box_hid_'+tag_id).val()).attr("checked");
	
	// Load normal image
	if(box_status == 'checked' || box_status == true){
		$('#'+LOAD_TAG_ID).css({backgroundPosition: '-25px -175px'});
	}else{
		$('#'+LOAD_TAG_ID).css({backgroundPosition: '-5px -175px'});
	}
}













//////////////////////////////////////////////////////////
//														//
//	jQuery plugins										//
//														//
//////////////////////////////////////////////////////////



// Copyright (c) 2009 - 2010 Erik van den Berg (http://www.planitworks.nl/jeegoocontext)
// Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
// and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
//
// Contributors:
// Denis Evteev
// Roman Imankulov (www.netangels.ru)
//
// Version: 1.3
// Requires jQuery 1.3.2+
(function($){
    var _global;
    var _menus;

    // Detect overflow.
    var _overflow = function(x, y){
        return {
            width : x - $(window).width() - $(window).scrollLeft(),
            height : y - $(window).height() - $(window).scrollTop()
        };
    };
    
    // Keyboard up/down
    var _onKeyUpDown = function(down){
        if(_menus[_global.activeId].currentHover)
        {
            // Hover the first visible menu-item from the next or previous siblings and skip any separator items.
            var prevNext = down ? 
            _menus[_global.activeId].currentHover.nextAll(':not(.' + _menus[_global.activeId].separatorClass + '):visible:first') :
            _menus[_global.activeId].currentHover.prevAll(':not(.' + _menus[_global.activeId].separatorClass + '):visible:first');
            // If nothing is found, hover the first or last visible sibling.
            if(prevNext.length == 0)
            {
                prevNext = _menus[_global.activeId].currentHover.parent().find('> li:visible');
                prevNext = (down ? $(prevNext[0]) : $(prevNext[prevNext.length - 1]));
            }
            prevNext.mouseover();
        }
        else
        {
            // Current hover is null, select the last visible submenu.
            var visibleMenus = $('#' + _global.activeId + ', #' + _global.activeId + ' ul').filter(function(){
                return ($(this).is(':visible') && $(this).parents(':hidden').length == 0);
            });
            if(visibleMenus.length > 0)
            {
                // Find all visible menu-items for this menu and hover the first or last visible sibling.
                var visibleItems = $(visibleMenus[visibleMenus.length - 1]).find('> li:visible');
                $(visibleItems[(down ? 0 : (visibleItems.length - 1))]).mouseover();
            }
        }
    };
    
    // Clear all active context.
    var _clearActive = function(){
        for(cm in _menus)
        {
            $(_menus[cm].allContext).removeClass(_global.activeClass);
        } 
    };
    
    // Reset menu.
    var _resetMenu = function(){
        // Hide active menu and it's submenus.
        if(_global.activeId)$('#' + _global.activeId).add('#' + _global.activeId + ' ul').hide(); 
        // Stop key up/down interval.
        clearInterval(_global.keyUpDown);
        _global.keyUpDownStop = false;
        // Clear current hover.
        if(_menus[_global.activeId])_menus[_global.activeId].currentHover = null;
        // Clear active menu.
        _global.activeId = null;               
		// Unbind click and mouseover functions bound to the document
		$(document).unbind('.jeegoocontext');  
		// Unbind resize event bound to the window.
		$(window).unbind('resize.jeegoocontext');           
    };
    
    var _globalHide = function(e){
        // Invoke onHide callback if set, 'this' refers to the menu.    
		// Discontinue default behavior if callback returns false.       
		if(_global.activeId && _menus[_global.activeId].onHide)
		{
			if(_menus[_global.activeId].onHide.apply($('#' + _global.activeId), [e, _menus[_global.activeId].context]) == false)
			{
				return false;
			}
		}

		// Default behavior.
		// =================================================== // 

		// Clear active context.
		_clearActive();  
		// Hide active menu.
		_resetMenu();
    };
	
	$.fn.jeegoocontext = function(id, options){
        
        if(!_global) _global = {};
        if(!_menus) _menus = {};
        
        // Always override _global.menuClass if value is provided by options.
        if(options && options.menuClass)_global.menuClass = options.menuClass;
        // Only set _global.menuClass if not set.
        if(!_global.menuClass)_global.menuClass = 'jeegoocontext';
        // Always override _global.activeClass if value is provided by options.
        if(options && options.activeClass)_global.activeClass = options.activeClass;
        // Only set _global.activeClass if not set.
        if(!_global.activeClass)_global.activeClass = 'active';
		
		// Default undefined:
		// livequery, bool
	    // event, string
		// openBelowContext, bool
		// ignoreWidthOverflow, bool
		// ignoreHeightOverflow, bool
		// autoHide, bool
		// onShow, function
		// onHover, function
		// onSelect, function
		// onHide, function
		_menus[id] = $.extend({
            hoverClass: 'hover',
            submenuClass: 'submenu',
            separatorClass: 'separator',
            operaEvent: 'ctrl+click',
            fadeIn: 200,
            delay: 300,
            keyDelay: 100,
            widthOverflowOffset: 0,
            heightOverflowOffset: 0,
            submenuLeftOffset: 0,
            submenuTopOffset: 0,
            autoAddSubmenuArrows: true,
            startLeftOffset: 0,
            startTopOffset: 0,
            keyboard: true
        }, options || {});
             
        // All context bound to this menu.
        _menus[id].allContext = this.selector;
        
        // Add mouseover and click handlers to the menu's items.
        $('#' + id).find('li')[_menus[id].livequery ? 'expire' : 'unbind']('.jeegoocontext')[_menus[id].livequery ? 'livequery' : 'bind']('mouseover.jeegoocontext', function(e){  

            var $this = _menus[id].currentHover = $(this);
    
            // Clear hide and show timeouts.
            clearTimeout(_menus[id].show);
            clearTimeout(_menus[id].hide);
            
            // Clear all hover state.
            $('#' + id).find('*').removeClass(_menus[id].hoverClass);
            
            // Set hover state on self, direct children, ancestors and ancestor direct children.
            var $parents = $this.parents('li');
            $this.add($this.find('> *')).add($parents).add($parents.find('> *')).addClass(_menus[id].hoverClass);
            
            // Invoke onHover callback if set, 'this' refers to the hovered list-item.
            // Discontinue default behavior if callback returns false.  
            var continueDefault = true;                 
            if(_menus[id].onHover)
            {
                if(_menus[id].onHover.apply(this, [e, _menus[id].context]) == false)continueDefault = false;
            }      
            
            // Continue after timeout(timeout is reset on every mouseover).
            if(!_menus[id].proceed)
            {
                _menus[id].show = setTimeout(function(){
                    _menus[id].proceed = true;
                    $this.mouseover(); 
                }, _menus[id].delay);
                               
                return false;
            }            
            _menus[id].proceed = false;

            // Hide all sibling submenu's and deeper level submenu's.
            $this.parent().find('ul').not($this.find('> ul')).hide();
            
            if(!continueDefault)
            {
                e.preventDefault();
                return false;
            }
            
            // Default behavior.
            // =================================================== //       
                
            // Position and fade-in submenu's.
            var $submenu = $this.find('> ul');
            if($submenu.length != 0)
            {
                var offSet = $this.offset();
                	 
                var overflow = _overflow(
                    (offSet.left + $this.parent().width() + _menus[id].submenuLeftOffset + $submenu.width() + _menus[id].widthOverflowOffset), 
                    (offSet.top + _menus[id].submenuTopOffset + $submenu.height() + _menus[id].heightOverflowOffset)
                );
				var parentWidth = $submenu.parent().parent().width();
				var y = offSet.top - $this.parent().offset().top;
                $submenu.css(
                    {
                        'left': (overflow.width > 0 && !_menus[id].ignoreWidthOverflow) ? (-parentWidth - _menus[id].submenuLeftOffset + 'px') : (parentWidth + _menus[id].submenuLeftOffset + 'px'),
                        'top': (overflow.height > 0 && !_menus[id].ignoreHeightOverflow) ? (y - overflow.height + _menus[id].submenuTopOffset) + 'px' : y + _menus[id].submenuTopOffset + 'px'
                    }
                );     
                     	            
                $submenu.fadeIn(_menus[id].fadeIn);   
            }
            e.stopPropagation(); 
        })[_menus[id].livequery ? 'livequery' : 'bind']('click.jeegoocontext', function(e){
        
            // Invoke onSelect callback if set, 'this' refers to the selected listitem.
            // Discontinue default behavior if callback returns false.
            if(_menus[id].onSelect)
            {            
                if(_menus[id].onSelect.apply(this, [e, _menus[id].context]) == false)
                {
                    return false;
                }
            }
            
            // Default behavior.
            //====================================================//
            
            // Reset menu
            _resetMenu();
                
            // Clear active state from this context.
            $(_menus[id].context).removeClass(_global.activeClass);
            
            e.stopPropagation();
        });
        
        // Determine the event type used to invoke the menu.
        // Event type is a namespaced event so it can be easily unbound later.
        var div = document.createElement('div');
        div.setAttribute('oncontextmenu', '');
        var eventType = _menus[id].event;
        if(!eventType)
        {
            eventType = (typeof div.oncontextmenu != 'undefined') ? 'contextmenu.jeegoocontext' : _menus[id].operaEvent + '.jeegoocontext';
        }
        else
        {
            eventType += '.jeegoocontext';
        }
        
        // Searching for the modifier in the event type
        // (e.g. ctrl+click, shift+contextmenu)
        if (eventType.indexOf('+') != -1) 
        {
            var chunks = eventType.split('+', 2);
            _menus[id].modifier = chunks[0] + 'Key';
            eventType = chunks[1];
        }
        
        // Add menu invocation handler to the context.
        return this[_menus[id].livequery ? 'livequery' : 'bind'](eventType, function(e){
            // Check for the modifier if any.
			if (typeof _menus[id].modifier == 'string' && !e[_menus[id].modifier]) return;
            
			// Save context(i.e. the current area to which the menu belongs).
            _menus[id].context = this;
            var $menu = $('#' + id);

            // Determine start position.
            var startLeft, startTop;
            if(_menus[id].openBelowContext)
            {
                var contextOffset = $(this).offset();
                startLeft = contextOffset.left;
                startTop = contextOffset.top + $(this).outerHeight();
            }
            else
            {
                startLeft = e.pageX;
                startTop = e.pageY;
            }
            startLeft += _menus[id].startLeftOffset;
            startTop += _menus[id].startTopOffset;

            // Check for overflow and correct menu-position accordingly.         
            var overflow = _overflow((startLeft + $menu.width() + _menus[id].widthOverflowOffset), (startTop + $menu.height() + _menus[id].heightOverflowOffset));         
            if(!_menus[id].ignoreWidthOverflow && overflow.width > 0) startLeft -= overflow.width;
            // Ignore y-overflow if openBelowContext or if _menus[id].ignoreHeightOverflow
            if(!_menus[id].openBelowContext && !_menus[id].ignoreHeightOverflow && overflow.height > 0) 
            {
                startTop -= overflow.height;
            }
			
            // Invoke onShow callback if set, 'this' refers to the menu.
            // Discontinue default behavior if callback returns false.         
            if(_menus[id].onShow)
            {
                if(_menus[id].onShow.apply($menu, [e, _menus[id].context, startLeft, startTop]) == false)
                {
                    return false;
                }
            }

            // Default behavior.
            // =================================================== //

            // Reset last active menu.
            _resetMenu();

            // Set this id as active menu id.
            _global.activeId = id;
            
            // Hide current menu and all submenus, on first page load this is neccesary for proper keyboard support.
            $('#' + _global.activeId).add('#' + _global.activeId + ' ul').hide();  

            // Clear all active context on page.
            _clearActive();   
                   
            // Make this context active.
            $(_menus[id].context).addClass(_global.activeClass); 
                                   
            // Clear all hover state.
            $menu.find('li, li > *').removeClass(_menus[id].hoverClass);
               
            // Auto add/delete submenu arrows(spans) if set by options.
            if(_menus[id].autoAddSubmenuArrows)
            {
                $menu.find('li:has(ul)').not(':has(span.' + _menus[id].submenuClass + ')').prepend('<span class="' + _menus[id].submenuClass + '"></span>'); 
                $menu.find('li').not(':has(ul)').find('> span.' + _menus[id].submenuClass).remove();     
            }
            
            // Fade-in menu at clicked-position.		
			if(browser == 'ie'){ startTop-=262; }
            $menu.css({
                'left': startLeft + 'px',
                'top':  startTop + 'px'
            }).fadeIn(_menus[id].fadeIn);
			
			// If openBelowContext, maintain contextmenu left position on window resize event.
            if(_menus[id].openBelowContext)
            {
                $(window).bind('resize.jeegoocontext', function(){
                    $('#' + id).css('left', $(_menus[id].context).offset().left + _menus[id].startLeftOffset + 'px');
                });
            }
        
			// Bind mouseover, keyup/keydown and click events to the document.
			$(document).bind('mouseover.jeegoocontext', function(e){ 
				// Remove hovers from last-opened submenu and hide any open relatedTarget submenu's after timeout.
				if($(e.relatedTarget).parents('#' + id).length > 0)
				{
					// Clear show submenu timeout.
					clearTimeout(_menus[id].show);
								   
					var $li = $(e.relatedTarget).parent().find('li');               
					$li.add($li.find('> *')).removeClass(_menus[id].hoverClass);
					
					// Clear last hovered menu-item.
					_menus[_global.activeId].currentHover = null;
	
					// Set hide submenu timeout.
					_menus[id].hide = setTimeout(function(){				    
						$li.find('ul').hide();
						if(_menus[id].autoHide)_globalHide(e);
					}, _menus[id].delay);                             
				}
			}).bind('click.jeegoocontext', _globalHide);
			
			if(_menus[id].keyboard)
			{
			    $(document).bind('keydown.jeegoocontext', function(e){
			        switch(e.which)
			        {
			            case 38: //keyup
			            if(_global.keyUpDownStop)return false;
			            _onKeyUpDown();
			            _global.keyUpDown = setInterval(_onKeyUpDown, _menus[_global.activeId].keyDelay);
			            _global.keyUpDownStop = true;
			            return false;
			            case 39: //keyright
			            if(_menus[_global.activeId].currentHover)
			            {
                            _menus[_global.activeId].currentHover.find('ul:visible:first li:visible:first').mouseover(); 
			            }
			            else
			            {
			                var visibleMenus = $('#' + _global.activeId + ', #' + _global.activeId + ' ul:visible');
			                if(visibleMenus.length > 0)
			                {
			                    $(visibleMenus[visibleMenus.length - 1]).find(':visible:first').mouseover();
			                }
			            }
			            return false;
			            case 40: //keydown
			            if(_global.keyUpDownStop)return false;
			            _onKeyUpDown(true);
			            _global.keyUpDown = setInterval(function(){
			                _onKeyUpDown(true);
			            }, _menus[_global.activeId].keyDelay);
			            _global.keyUpDownStop = true;
			            return false;
			            case 37: //keyleft
			            if(_menus[_global.activeId].currentHover)
			            {
			                $(_menus[_global.activeId].currentHover.parents('li')[0]).mouseover();
			            }
                        else
                        {
                            var hoveredLi = $('#' + _global.activeId + ' li.' + _menus[_global.activeId].hoverClass);
                            if(hoveredLi.length > 0)$(hoveredLi[hoveredLi.length - 1]).mouseover();
                        }
                        return false;
			            case 13: //enter
			            if(_menus[_global.activeId].currentHover)
			            {
			                _menus[_global.activeId].currentHover.click();
			            }
			            else
			            {
			                _globalHide(e);
			            }
			            break;
			            case 27: //escape
			            _globalHide(e);
			            break;
			            default:
			            break;
			        }
			    }).bind('keyup.jeegoocontext', function(e){
			        clearInterval(_global.keyUpDown);
			        _global.keyUpDownStop = false;
			    });
			}

            return false;
        });      
    }; 
	
	// Unbind context from context menu.
    $.fn.nojeegoocontext = function(){ 
        this.unbind('.jeegoocontext');
    };
       	   
})(jQuery);

/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-22 01:45:56 +0200 (Son, 22 Jul 2007) $
 * $Rev: 2447 $
 *
 * Version 2.1.1
 */
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);


/*
 * 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?10:150},options);options.highlight=options.highlight||function(value){return value;};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};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;$.browser.opera&&$(input.form).bind("submit.autocomplete",function(){if(blockSubmit){blockSubmit=false;return false;}});$input.bind(($.browser.opera?"keypress":"keydown")+".autocomplete",function(event){hasFocus=1;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;case options.multiple&&$.trim(options.multipleSeparator)==","&&KEY.COMMA:case KEY.TAB:case KEY.RETURN:if(selectCurrent()){event.preventDefault();blockSubmit=true;return false;}break;case KEY.ESC:select.hide();break;default:clearTimeout(timeout);timeout=setTimeout(onChange,options.delay);break;}}).focus(function(){hasFocus++;}).blur(function(){hasFocus=0;if(!config.mouseDownOnSelect){hideResults();}}).click(function(){if(hasFocus++>1&&!select.visible()){onChange(0,true);}}).bind("search",function(){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("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;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];}function autoFill(q,sValue){if(options.autoFill&&(lastWord($input.val()).toLowerCase()==q.toLowerCase())&&lastKeyPressCode!=KEY.BACKSPACE){$input.val($input.val()+sValue.substring(lastWord(previousValue).length));$(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){$input.search(function(result){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);if(data&&data.length){success(term,data);}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({mode:"abort",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{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;var stMatchSets={},nullData=0;if(!options.url)options.cacheLength=1;stMatchSets[""]=[];for(var i=0,ol=options.data.length;i<ol;i++){var rawValue=options.data[i];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(!stMatchSets[firstChar])stMatchSets[firstChar]=[];var row={value:value,data:rawValue,result:options.formatResult&&options.formatResult(rawValue)||value};stMatchSets[firstChar].push(row);if(nullData++<options.max){stMatchSets[""].push(row);}};$.each(stMatchSets,function(i,value){options.cacheLength++;add(i,value);});}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(!options.url&&options.matchContains){var csub=[];for(var k in data){if(k.length>0){var c=data[k];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub.push(x);}});}}return csub;}else
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;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();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;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;}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){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);





/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-20 09:02:08 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4265 $
 *
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+
 */

(function($) {

$.event.special.mousewheel = {
	setup: function() {
		var handler = $.event.special.mousewheel.handler;
		
		// Fix pageX, pageY, clientX and clientY for mozilla
		if ( $.browser.mozilla )
			$(this).bind('mousemove.mousewheel', function(event) {
				$.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});
	
		if ( this.addEventListener )
			this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		var handler = $.event.special.mousewheel.handler;
		
		$(this).unbind('mousemove.mousewheel');
		
		if ( this.removeEventListener )
			this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = function(){};
		
		$.removeData(this, 'mwcursorposdata');
	},
	
	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );
		
		event = $.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		$.extend( event, $.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;
		
		if ( event.wheelDelta ) delta = event.wheelDelta/120;
		if ( event.detail     ) delta = -event.detail/3;
//		if ( $.browser.opera  ) delta = -event.wheelDelta;
		
		event.data  = event.data || {};
		event.type  = "mousewheel";
		
		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return $.event.handle.apply(this, args);
	}
};

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

})(jQuery);





/* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 93 2010-06-01 08:17:28Z kelvin.luck $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								tabIndex		-	The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *								enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *								animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
 *								topCapHeight	-	The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
 *								bottomCapHeight	-	The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
 *								observeHash		-	Whether jScrollPane should attempt to automagically scroll to the correct place when an anchor inside the scrollpane is linked to (default true)
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			var paneEle = this;
			var currentScrollPosition = 0;
			var paneWidth;
			var paneHeight;
			var trackHeight;
			var trackOffset = settings.topCapHeight;
			var $container;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				$container = $(this).parent();
				currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				paneWidth = $c.innerWidth();
				paneHeight = $c.outerHeight();
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', $c).remove();
				$this.css({'top':0});
			} else {
				$this.data('originalStyleTag', $this.attr('style'));
				// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
				$this.css('overflow', 'hidden');
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				paneWidth = $this.innerWidth();
				paneHeight = $this.innerHeight();
				$container = $('<div></div>')
					.attr({'className':'jScrollPaneContainer'})
					.css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					);
				if (settings.enableKeyboardNavigation) {
					$container.attr(
						'tabindex', 
						settings.tabIndex
					);
				}
				$this.wrap($container);
				$container = $this.parent();
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);
				
			}
			trackHeight = paneHeight;
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load readystatechange', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
								$this.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;
			
			var isScrollable = percentInView < .99;
			$container[isScrollable ? 'addClass' : 'removeClass']('jScrollPaneScrollable');

			if (isScrollable) {
				$container.append(
					$('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div><table border="0" cellspacing="0" cellpadding="0" height="100%" width="100%"><tr><td class="jScrollPaneDragCenter"></td></tr></table></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					),
					$('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					$container.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowUp', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'top':settings.topCapHeight + 'px'
									}
								)
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowDown', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'bottom':settings.bottomCapHeight + 'px'
									}
								)
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
				}
				
				if (settings.arrowSize) {
					trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
					trackOffset += settings.arrowSize;
				} else if ($upArrow) {
					var topArrowHeight = $upArrow.height();
					settings.arrowSize = topArrowHeight;
					trackHeight = paneHeight - topArrowHeight - $downArrow.height();
					trackOffset += topArrowHeight;
				}
				trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
				$track.css({'height': trackHeight+'px', top:trackOffset+'px'})
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll).bind('mouseleave', onStopDrag)
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					$container.scrollTop(0);
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						// Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
						// errors from the lookup...
						try {
							$e = $(pos, $this);
						} catch (err) {
							return;
						}
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					$this.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						$container.scrollTop(0);
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						var preventInfiniteLoop = 100;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
							if (!preventInfiniteLoop--) {
								return;
							}
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (settings.observeHash) {
					if (location.hash && location.hash.length > 1) {
						setTimeout(function(){
							scrollTo(location.hash);
						}, $.browser.safari ? 100 : 0);
					}
					
					// use event delegation to listen for all clicks on links and hijack them if they are links to
					// anchors within our content...
					$(document).bind('click', function(e){
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h && h.substr(0, 1) == '#' && h.length > 1) {
								setTimeout(function(){
									scrollTo(h, !settings.animateToInternalLinks);
								}, $.browser.safari ? 100 : 0);
							}
						}
					});
				}
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
				  
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					$this[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = $this.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				   $(document)
					  .unbind('mousemove.jScrollPaneDragging')
					  .unbind('mouseup.jScrollPaneDragging');
				   clearTextSelectionInterval();
				}

				$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				$this[0].scrollTo = $this[0].scrollBy = function() {};
				// clean up listeners
				$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
		$this = $(this);
		var $c = $this.parent();
		if ($c.is('.jScrollPaneContainer')) {
			$this.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			$this.attr('style', $this.data('originalStyleTag'));
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false,
	topCapHeight: 0,
	bottomCapHeight: 0,
	observeHash: true
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);
//-->
