// Outer HTML
$.fn.outerHTML = function() {
	return $('<div>').append( this.eq(0).clone() ).html();
};

/******************************* RTE *********************************/
/*
 * Lightweight RTE - jQuery Plugin, version 1.2
 * Copyright (c) 2009 Andrey Gayvoronsky - http://www.gayvoronsky.com
 */
jQuery.fn.rte = function(options, editors) {
	if(!editors || editors.constructor != Array)
		editors = new Array();
		
	$(this).each(function(i) {
		var id = (this.id) ? this.id : editors.length;
		editors[id] = new lwRTE (this, options || {});
	});
	
	return editors;
}

var lwRTE_resizer = function(textarea) {
	this.drag = false;
	this.rte_zone = $(textarea).parents('.rte-zone');
}

lwRTE_resizer.mousedown = function(resizer, e) {
	resizer.drag = true;
	resizer.event = (typeof(e) == "undefined") ? window.event : e;
	resizer.rte_obj = $(".rte-resizer", resizer.rte_zone).prev().eq(0);
	$('body', document).css('cursor', 'se-resize');
	return false;
}

lwRTE_resizer.mouseup = function(resizer, e) {
	resizer.drag = false;
	$('body', document).css('cursor', 'auto');
	return false;
}

lwRTE_resizer.mousemove = function(resizer, e) {
	if(resizer.drag) {
		e = (typeof(e) == "undefined") ? window.event : e;
		var w = Math.max(1, resizer.rte_zone.width() + e.screenX - resizer.event.screenX);
		var h = Math.max(1, resizer.rte_obj.height() + e.screenY - resizer.event.screenY);
		resizer.rte_zone.width(w);
		resizer.rte_obj.height(h);
		resizer.event = e;
	}
	return false;
}

var lwRTE = function (textarea, options) {
	this.css		= [];
	this.css_class	= options.frame_class || 'rte-iframe';
	this.base_url	= options.base_url || '';
	this.width		= options.width || $(textarea).width() || '100%';
	this.height		= options.height || $(textarea).height() || 350;
	this.iframe		= null;
	this.iframe_doc	= null;
	this.textarea	= null;
	this.event		= null;
	this.range		= null;
	this.toolbars	= {rte: '', html : ''};
	this.controls	= {rte: {disable: {hint: 'Source editor'}}, html: {enable: {hint: 'Visual editor'}}};

	$.extend(this.controls.rte, options.controls_rte || {});
	$.extend(this.controls.html, options.controls_html || {});
	$.extend(this.css, options.css || {});

	if(document.designMode || document.contentEditable) {
		$(textarea).wrap($('<div></div>').addClass('rte-zone').width(this.width));		
		$('<div class="rte-resizer"><a href="#"></a></div>').insertAfter(textarea);

		var resizer = new lwRTE_resizer(textarea);
		
		$(".rte-resizer a", $(textarea).parents('.rte-zone')).mousedown(function(e) {
			$(document).mousemove(function(e) {
				return lwRTE_resizer.mousemove(resizer, e);
			});

			$(document).mouseup(function(e) {
				return lwRTE_resizer.mouseup(resizer, e)
			});

			return lwRTE_resizer.mousedown(resizer, e);
		});

		this.textarea	= textarea;
		this.enable_design_mode();
	}
}

lwRTE.prototype.editor_cmd = function(command, args) {
	this.iframe.contentWindow.focus();
	try {
		this.iframe_doc.execCommand(command, false, args);
	} catch(e) {
	}
	this.iframe.contentWindow.focus();
}

lwRTE.prototype.get_toolbar = function() {
	var editor = (this.iframe) ? $(this.iframe) : $(this.textarea);
	return (editor.prev().hasClass('rte-toolbar')) ? editor.prev() : null;
}

lwRTE.prototype.activate_toolbar = function(editor, tb) {
	var old_tb = this.get_toolbar();

	if(old_tb)
		old_tb.remove();

	$(editor).before($(tb).clone(true));
}
	
lwRTE.prototype.enable_design_mode = function() {
	var self = this;

	// need to be created this way
	self.iframe	= document.createElement("iframe");
	self.iframe.frameBorder = 0;
	self.iframe.frameMargin = 0;
	self.iframe.framePadding = 0;
	self.iframe.width = '100%';
	self.iframe.height = self.height || '100%';
	self.iframe.src	= "javascript:void(0);";

	// Custom - Add ID if none
	var id = $(self.textarea).attr('id');
	if(!id) {
		var id = "lwrte_"+Math.floor(Math.random() * 999999);
		$(self.textarea).attr('id',id);
	}
	// End Custom

	if($(self.textarea).attr('class'))
		self.iframe.className = $(self.textarea).attr('class');

	if($(self.textarea).attr('id'))
		self.iframe.id = $(self.textarea).attr('id');

	if($(self.textarea).attr('name'))
		self.iframe.title = $(self.textarea).attr('name');

	var content	= $(self.textarea).val();

	$(self.textarea).hide().after(self.iframe)/*.remove()*/; // Custom (keep hidden textarea for storing live text in)
	//self.textarea	= null; // Custom (keep hidden textarea for storing live text in)
	
	var css = '';
	
	for(var i in self.css) css += "<link type='text/css' rel='stylesheet' href='" + self.css[i] + "' />";

	var base = (self.base_url) ? "<base href='" + self.base_url + "' />" : '';
	var style = (self.css_class) ? "class='" + self.css_class + "'" : '';

	// Mozilla need this to display caret
	/*if($.trim(content) == '')
		content	= '<br>';*/

	var doc = "<html><head>" + base + css + "</head><body " + style + " style='padding:5px'>" + content + "</body></html>";

	self.iframe_doc	= self.iframe.contentWindow.document;

	try {
		self.iframe_doc.designMode = 'on';
	} catch ( e ) {
		// Will fail on Gecko if the editor is placed in an hidden container element
		// The design mode will be set ones the editor is focused
		$(self.iframe_doc).focus(function() { self.iframe_doc.designMode(); } );
	}

	self.iframe_doc.open();
	self.iframe_doc.write(doc);
	self.iframe_doc.close();

	if(!self.toolbars.rte)
		self.toolbars.rte	= self.create_toolbar(self.controls.rte);

	self.activate_toolbar(self.iframe, self.toolbars.rte);

	$(self.iframe).parents('form').submit(function() {
		lwrte_save(self); // Custom - Save Text								   
		//self.disable_design_mode(true); // Custom Removed - this screws up everything on validation attempt
	});
	
	// Custom - Save Text
	lwrte_save(self);
	
	// Custom - Context menu
	if(ADMIN == true) {
		$(self.iframe_doc).bind("contextmenu",function(e){
			var html = self.get_selected_html();
			// Image
			if(html.indexOf('<img') > -1) {
				self.lwrte_menu(e,'img');
				return false;
			}
		});
	}

	// Custom - Keyboard Shortcuts
	$(self.iframe_doc).bind('keydown', 'Ctrl+l',function (evt){ /*alert('l'); lwrte_link_basic(); return false;*/ });
	$(self.iframe_doc).bind('keydown', 'Ctrl+b',function (evt){ self.editor_cmd("bold"); return false; });
	$(self.iframe_doc).bind('keydown', 'Ctrl+i',function (evt){ self.editor_cmd("italic"); return false; });
	$(self.iframe_doc).bind('keydown', 'Ctrl+u',function (evt){ self.editor_cmd("underline"); return false; });
	
	// Custom - Paste
	$(self.iframe_doc).bind('paste', function(e){
		// Cleanup Text
		if(texteditor_cleanup_paste == 1) setTimeout('lwrte_cleanup("'+self.iframe.id+'")',30);
	});

	$(self.iframe_doc).mouseup(function(event) {
		if(self.iframe_doc.selection) self.range = self.iframe_doc.selection.createRange();  //store to restore later(IE fix)
		self.set_selected_controls( (event.target) ? event.target : event.srcElement, self.controls.rte); 
	});

	// Custom - Leaving Iframe (specifically, need to save image positions)
	$(self.iframe).blur(function(event) {
		lwrte_save(self);						 
	});

	$(self.iframe_doc).blur(function(event){ 
		lwrte_save(self); // Custom (add text to hidden textarea)
		if(self.iframe_doc.selection) self.range = self.iframe_doc.selection.createRange(); // same fix for IE as above
	});

	$(self.iframe_doc).keyup(function(event) {
		lwrte_save(self); // Custom (add text to hidden textarea)
		self.set_selected_controls( self.get_selected_element(), self.controls.rte); 
	});

	// Mozilla CSS styling off
	if(!$.browser.msie)
		self.editor_cmd('styleWithCSS', false);
}
    
// Custom - Saves Text to hidden Input for AJAX Saving
function lwrte_save(self) {
	var html = $("body",self.iframe_doc).html();
	$(self.textarea).val(html);
	if(self.iframe.title == "post_text") $('#preview_text').html(html);
}

// Custom - Context Menu
var lwrte_timer;
lwRTE.prototype.lwrte_menu = function(e,type) {
	var self = this;
	var menu = "";
	var id = "";
	var iframe_position = $(self.iframe).offset();
	var top = iframe_position.top + e.pageY - 10;
	var left = iframe_position.left + e.pageX - 10;
	
	// Image Align
	if(type == "img") {
		menu += "<span onclick=\"alert('clicked left');lwrte_menu_command('align-left','"+id+"');\">Align Left</span>";
		menu += "<span onclick=\"alert('clicked right');lwrte_menu_command('align-right','"+id+"');\">Align Right</span>";
	}
	menu = "<div class='rte-menu' style='top:"+top+"px;left:"+left+"px;'>"+menu+"</div>";
	//alert(menu);
	
	// Add Menu
	$("body").append(menu);
	
	// Remove on Mouseout
	$("div.rte-menu").mouseout(function() {
		if(lwrte_timer) clearTimeout(lwrte_timer);
		lwrte_timer = setTimeout('lwrte_menu_remove();',250);
	});
	$("div.rte-menu").mouseover(function() {
		if(lwrte_timer) clearTimeout(lwrte_timer);
	});
}

// Custom - Remove Menu (after timeout)
function lwrte_menu_remove() {
	//$('div.rte-toolbar').next('iframe').contents().find('.rte-menu').remove();
	$('div.rte-menu').remove();
}

// Custom - Context Menu Commands
function lwrte_menu_command(command,id) {
	alert(command+','+id);
	// Get IFrame
	/*var iframe = $('div.rte-toolbar').next('iframe').contents();
	
	var self = $('textarea.texteditor');
	var html = self.get_selected_html();
	alert(html);
	
	//if(command == "align-left" || command == "align-right") {
		
			
	// Align Left
	if(command == "align-left") $('#temp_'+id,iframe).attr('align','left');
	// Align Right
	if(command == "align-right") $('#temp_'+id,iframe).attr('align','right');
	
	// Remove Temp ID
	$('#temp_'+id).removeAttr('id');*/
}

// Custom - Get Attribute from HTML
function lwrte_parse(html,attribute) {
	var value = '';
	var regex = new RegExp(attribute+"=[\"|'](.*?)[\"|']","g");
	if(html.indexOf(attribute) > -1) {
		var matches = regex.exec(html);
		if(matches[1]) value = matches[1];
	}
	
	return value;
}

// Custom - Cleanup on Paste
function lwrte_cleanup(id) {
	//var iframe = $('iframe#'+id);
	var w = $('iframe').each(function() {
		var iframe_doc	= this.contentDocument;
		var html = $("body",iframe_doc).html();
		$.ajax({
			type: 'POST',
			url: DOMAIN,
			data: 'ajaxRequest=cleanIt&text='+encodeURIComponent(html),
			success: function(html){
				$("body",iframe_doc).html(html);
			}
		});
	});
}
	
lwRTE.prototype.disable_design_mode = function(submit) {
	var self = this;

	self.textarea = (submit) ? $('<input type="hidden" />').get(0) : $('<textarea></textarea>').width('100%').height(self.height).get(0);

	if(self.iframe.className)
		self.textarea.className = self.iframe.className;

	if(self.iframe.id)
		self.textarea.id = self.iframe.id;
		
	if(self.iframe.title)
		self.textarea.name = self.iframe.title;
	
	$(self.textarea).val($('body', self.iframe_doc).html());
	//$(self.iframe).before(self.textarea); // Custom (though not sure why I did this)

	if(!self.toolbars.html)
		self.toolbars.html	= self.create_toolbar(self.controls.html);

	if(submit != true) {
		$(self.iframe_doc).remove(); //fix 'permission denied' bug in IE7 (jquery cache)
		$(self.iframe).remove();
		self.iframe = self.iframe_doc = null;
		self.activate_toolbar(self.textarea, self.toolbars.html);
	}
	
	// Custom - Save Text
	lwrte_save(self);
}
    
lwRTE.prototype.toolbar_click = function(obj, control) {
	//alert('toolbar click');
	var fn = control.exec;
	var args = control.args || [];
	var is_select = (obj.tagName.toUpperCase() == 'SELECT');
	//alert(fn);
	$('.rte-panel', this.get_toolbar()).remove();

	if(fn) {
		if(is_select)
			args.push(obj);

		try {
			fn.apply(this, args);
		} catch(e) {

		}
	} else if(this.iframe && control.command) {
		if(is_select) {
			args = obj.options[obj.selectedIndex].value;

			if(args.length <= 0)
				return;
		}

		this.editor_cmd(control.command, args);
	}
	
	lwrte_save(this);
}
	
lwRTE.prototype.create_toolbar = function(controls) {
	var self = this;
	var tb = $("<div></div>").addClass('rte-toolbar').width('100%').append($("<ul></ul>")).append($("<div></div>").addClass('clear'));
	var obj, li;
	
	for (var key in controls){
		if(controls[key].separator) {
			li = $("<li></li>").addClass('separator');
		} else {
			if(controls[key].init) {
				try {
					controls[key].init.apply(controls[key], [this]);
				} catch(e) {
				}
			}
			
			if(controls[key].select) {
				obj = $(controls[key].select)
					.change( function(e) {
						self.event = e;
						self.toolbar_click(this, controls[this.className]); 
						return false;
					});
			} else {
				obj = $("<a href='#'></a>")
					.attr('title', (controls[key].hint) ? controls[key].hint : key)
					.attr('rel', key)
					.click( function(e) {
						self.event = e;
						self.toolbar_click(this, controls[this.rel]); 
						return false;
					})
			}

			li = $("<li></li>").append(obj.addClass(key));
		}

		// Custom - Settings Defined Options
		if(key == "suggestions" && texteditor_links_suggestions != 1) {}
		else $("ul",tb).append(li);
	}

	$('.enable', tb).click(function() {
		self.enable_design_mode();
		return false; 
	});

	$('.disable', tb).click(function() {
		self.disable_design_mode();
		return false; 
	});

	return tb.get(0);
}

lwRTE.prototype.create_panel = function(title, width) {
	var self = this;
	var tb = self.get_toolbar();

	if(!tb)
		return false;

	$('.rte-panel', tb).remove();
	var drag, event;
	var left = self.event.pageX;
	var top = self.event.pageY;
	
	var panel	= $('<div></div>').hide().addClass('rte-panel');
	if($.browser.msie && $.browser.version=="6.0") panel.css({left: left, top: top});// Custom (made this css ie6 only)
	$('<div></div>')
		.addClass('rte-panel-title')
		.html(title)
		.append($("<a class='close' href='#'>X</a>")
		.click( function() { panel.remove(); return false; }))
		.mousedown( function() { drag = true; return false; })
		.mouseup( function() { drag = false; return false; })
		.mousemove( 
			function(e) {
				if(drag && event) {
					left -= event.pageX - e.pageX;
					top -=  event.pageY - e.pageY;
					//panel.css( {left: left, top: top} );  // Custom, positioning it myself
				}

				event = e;
				return false;
			} 
		)
		.appendTo(panel);

	if(width)
		panel.width(width);

	tb.append(panel);
	return panel;
}

lwRTE.prototype.get_content = function() {
	return (this.iframe) ? $('body', this.iframe_doc).html() : $(this.textarea).val();
}

lwRTE.prototype.set_content = function(content) {
	(this.iframe) ? $('body', this.iframe_doc).html(content) : $(this.textarea).val(content);
}

lwRTE.prototype.set_selected_controls = function(node, controls) {
	var toolbar = this.get_toolbar();

	if(!toolbar)
		return false;
		
	var key, i_node, obj, control, tag, i, value;

	try {
		for (key in controls) {
			control = controls[key];
			obj = $('.' + key, toolbar);

			obj.removeClass('active');

			if(!control.tags)
				continue;

			i_node = node;
			do {
				if(i_node.nodeType != 1)
					continue;

				tag	= i_node.nodeName.toLowerCase();
				if($.inArray(tag, control.tags) < 0 )
					continue;

				if(control.select) {
					obj = obj.get(0);
					if(obj.tagName.toUpperCase() == 'SELECT') {
						obj.selectedIndex = 0;

						for(i = 0; i < obj.options.length; i++) {
							value = obj.options[i].value;
							if(value && ((control.tag_cmp && control.tag_cmp(i_node, value)) || tag == value)) {
								obj.selectedIndex = i;
								break;
							}
						}
					}
				} else
					obj.addClass('active');
			}  while(i_node = i_node.parentNode)
		}
	} catch(e) {
	}
	
	return true;
}

lwRTE.prototype.get_selected_element = function () {
	var node, selection, range;
	var iframe_win	= this.iframe.contentWindow;
	
	if (iframe_win.getSelection) {
		try {
			selection = iframe_win.getSelection();
			range = selection.getRangeAt(0);
			node = range.commonAncestorContainer;
		} catch(e){
			return false;
		}
	} else {
		try {
			selection = iframe_win.document.selection;
			range = selection.createRange();
			node = range.parentElement();
		} catch (e) {
			return false;
		}
	}

	return node;
}

lwRTE.prototype.get_selection_range = function() {
	var rng	= null;
	var iframe_window = this.iframe.contentWindow;
	this.iframe.focus();
	
	if(iframe_window.getSelection) {
		rng = iframe_window.getSelection().getRangeAt(0);
		if($.browser.opera) { //v9.63 tested only
			var s = rng.startContainer;
			if(s.nodeType === Node.TEXT_NODE)
				rng.setStartBefore(s.parentNode);
		}
	} else {
		if(this.range) {
			this.range.select(); // Restore selection, if IE lost focus.
			rng = this.iframe_doc.selection.createRange();
		}
	}

	return rng;
}

lwRTE.prototype.get_selected_text = function() {
	var iframe_win = this.iframe.contentWindow;

	if(iframe_win.getSelection)	
		return iframe_win.getSelection().toString();

	this.range.select(); //Restore selection, if IE lost focus.
	return iframe_win.document.selection.createRange().text;
};

lwRTE.prototype.get_selected_html = function() {
	var html = null;
	var iframe_window = this.iframe.contentWindow;
	var rng	= this.get_selection_range();
	
	if(rng && iframe_window) {
		if(iframe_window.getSelection) {
			var e = document.createElement('div');
			e.appendChild(rng.cloneContents());
			html = e.innerHTML;		
		} else {
			// New Code (gets html OR selected image)
			if(rng.htmlText) html = rng.htmlText;
			else {
				elm = rng.item ? rng.item(0) : rng.parentElement();
				var html = elm.outerHTML;
			}
			// Original Code (didn't get selected image)
			//html = rng.htmlText;
		}
	}

	return html;
};

lwRTE.prototype.selection_replace_with = function(html) {
	var rng	= this.get_selection_range();
	var iframe_window = this.iframe.contentWindow;

	if(!rng) return;
	
	this.editor_cmd('removeFormat'); // we must remove formating or we will get empty format tags!

	if(iframe_window.getSelection) {
		rng.deleteContents();
		rng.insertNode(rng.createContextualFragment(html));
		this.editor_cmd('delete');
	} else {
		// New Code (gets html OR selected image)
		if(rng.htmlText) {
			this.editor_cmd('delete');
			rng.pasteHTML(html);
		}
		else {
			elm = rng.item ? rng.item(0) : rng.parentElement();
			var e = $(elm);
			$(e).replaceWith(html);
		}
		// Original (doesn't work with selected image)
		/*this.editor_cmd('delete');
		rng.pasteHTML(html);*/
	}
}

var rte_tag		= '-rte-tmp-tag-';

/****** Default Toolbar *******/
var full_toolbar={
	bold:{command:"bold",tags:["b","strong"]},
	italic:{command:"italic",tags:["i","em"]},
	strikeThrough:{command:"strikethrough",tags:["s","strike"]},
	underline:{command:"underline",tags:["u"]},
	s2:{separator:true},
	justifyLeft:{command:"justifyleft"},
	justifyCenter:{command:"justifycenter"},
	justifyRight:{command:"justifyright"},
	justifyFull:{command:"justifyfull"},
	s3:{separator:true},
	indent:{command:"indent"},
	outdent:{command:"outdent"},
	s4:{separator:true},
	subscript:{command:"subscript",tags:["sub"]},
	superscript:{command:"superscript",tags:["sup"]},
	s5:{separator:true},
	orderedList:{command:"insertorderedlist",tags:["ol"]},
	unorderedList:{command:"insertunorderedlist",tags:["ul"]},
	s6:{separator:true},
	color:{exec:lwrte_color},
	image:{exec:lwrte_image,tags:["img"]},
	link:{exec:lwrte_link,tags:["a"]},
	unlink:{command:"unlink"},
	suggestions:{exec:lwrte_link_suggestions},
	s8:{separator:true},
	/*removeFormat:{exec:lwrte_unformat},
	word:{exec:lwrte_cleanup_word},
	clear:{exec:lwrte_clear},
	s8:{separator:true},
	block:{command:"formatblock",select:'<select>	<option value="">- format -</option>	<option value="<p>">Paragraph</option>	<option value="<h1>">Header 1</option>	<option value="<h2>">Header 2</options>	<option value="<h3>">Header 3</option>	<option value="<h4>">Header 4</options>	<option value="<h5>">Header 5</option>	<option value="<h6>">Header 6</options></select>	',tag_cmp:lwrte_block_compare,tags:["p","h1","h2","h3","h4","h5","h6"]},*/
	font:{command:"fontname",select:'<select>	<option value="">- font -</option>	<option value="arial">Arial</option>	<option value="comic sans ms">Comic Sans</option>	<option value="courier new">Courier New</options>	<option value="georgia">Georgia</option>	<option value="helvetica">Helvetica</options>	<option value="impact">Impact</option>	<option value="times new roman">Times</options>	<option value="trebuchet ms">Trebuchet</options>	<option value="verdana">Verdana</options></select>	',tags:["span"]},
	size:{command:"fontsize",select:'<select>	<option value="">-</option>	<option value="1">1 (8pt)</option>	<option value="2">2 (10pt)</option>	<option value="3">3 (12pt)</options>	<option value="4">4 (14pt)</option>	<option value="5">5 (16pt)</options>	<option value="6">6 (18pt)</option>	<option value="7">7 (20pt)</options></select>	',tags:["span"]}/*,
	style:{exec:lwrte_style,init:lwrte_style_init}*/
};
var html_toolbar={
	s1:{separator:true}/*,
	word:{exec:lwrte_cleanup_word},
	clear:{exec:lwrte_clear}*/
};
/*** Public Toolbar ***/
var default_toolbar={
	bold:{command:"bold",tags:["b","strong"]},
	italic:{command:"italic",tags:["i","em"]},
	underline:{command:"underline",tags:["u"]},
	s2:{separator:true},
	indent:{command:"indent"},
	outdent:{command:"outdent"},
	unorderedList:{command:"insertunorderedlist",tags:["ul"]},
	s6:{separator:true},
	image:{exec:lwrte_image,tags:["img"]},
	link:{exec:lwrte_link_basic,tags:["a"]},
	unlink:{command:"unlink"},
	suggestions:{exec:lwrte_link_suggestions},
	s8:{separator:true}
	//style:{exec:lwrte_style,init:lwrte_style_init}
};

/*** Basic Toolbar ***/
var basic_toolbar={
	bold:{command:"bold",tags:["b","strong"]},
	italic:{command:"italic",tags:["i","em"]},
	underline:{command:"underline",tags:["u"]},
	s2:{separator:true},
	indent:{command:"indent"},
	outdent:{command:"outdent"},
	unorderedList:{command:"insertunorderedlist",tags:["ul"]}
};

/*** tag compare callbacks ***/
function lwrte_block_compare(node, tag) {
	tag = tag.replace(/<([^>]*)>/, '$1');
	return (tag.toLowerCase() == node.nodeName.toLowerCase());
}

/*** init callbacks ***/
function lwrte_style_init(rte) {
	var self = this;
	self.select = '<select><option value="">- no css -</option></select>';

	// load CSS info. javascript only issue is not working correctly, that's why ajax-php :(
	if(rte.css.length) {	
		$.ajax({
			url: "styles.php", 
			type: "POST",
			data: { css: rte.css[rte.css.length - 1] }, 
			async: false,
			success: function(data) {
				var list = data.split(',');
				var select = "";

				for(var name in list)
					select += '<option value="' + list[name] + '">' + list[name] + '</option>';
	
				self.select = '<select><option value="">- css -</option>' + select + '</select>';
			}});
	}
}

/*** exec callbacks ***/
/*function lwrte_style(args) {
	if(args) {
		try {
			var css = args.options[args.selectedIndex].value
			var self = this;
			var html = self.get_selected_text();
			html = '<span class="' + css + '">' + html + '</span>';
			self.selection_replace_with(html);
			args.selectedIndex = 0;
		} catch(e) {
		}
	}
}*/

function lwrte_color(){
	var self = this;
	var panel = self.create_panel('Set color for text', 385);
	var mouse_down = false;
	var mouse_over = false;
	panel.append('\
<div class="colorpicker1"><div class="rgb" id="rgb"></div></div>\
<div class="colorpicker1"><div class="gray" id="gray"></div></div>\
<div class="colorpicker2">\
	<div class="palette" id="palette"></div>\
	<div class="preview" id="preview"></div>\
	<div class="color" id="color"></div>\
</div>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Cancel</button></p>'
).show();

	var preview = $('#preview', panel);
	var color = $("#color", panel);
	var palette = $("#palette", panel);
	var colors = [
		'#660000', '#990000', '#cc0000', '#ff0000', '#333333',
		'#006600', '#009900', '#00cc00', '#00ff00', '#666666',
		'#000066', '#000099', '#0000cc', '#0000ff', '#999999',
		'#909000', '#900090', '#009090', '#ffffff', '#cccccc',
		'#ffff00', '#ff00ff', '#00ffff', '#000000', '#eeeeee'
	];
			
	for(var i = 0; i < colors.length; i++)
		$("<div></div>").addClass("item").css('background', colors[i]).appendTo(palette);
			
	var height = $('#rgb').height();
	var part_width = $('#rgb').width() / 6;

	$('#rgb,#gray,#palette', panel)
		.mousedown( function(e) {mouse_down = true; return false; } )
		.mouseup( function(e) {mouse_down = false; return false; } )
		.mouseout( function(e) {mouse_over = false; return false; } )
		.mouseover( function(e) {mouse_over = true; return false; } );

	$('#rgb').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, true, false, false, e); return false;} );
	$('#gray').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, false, true, false, e); return false;} );
	$('#palette').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, false, false, true, e); return false;} );
	$('#rgb').click( function(e) { compute_color(this, true, false, false, e); return false;} );
	$('#gray').click( function(e) { compute_color(this, false, true, false, e); return false;} );
	$('#palette').click( function(e) { compute_color(this, false, false, true, e); return false;} );

	$('#cancel', panel).click( function() { panel.remove(); return false; } );
	$('#ok', panel).click( 
		function() {
			var value = color.html();

			if(value.length > 0 && value.charAt(0) =='#') {
				if(self.iframe_doc.selection) //IE fix for lost focus
					self.range.select();

				self.editor_cmd('foreColor', value);
			}
					
			panel.remove(); 
			return false;
		}
	);

	function to_hex(n) {
		var s = "0123456789abcdef";
		return s.charAt(Math.floor(n / 16)) + s.charAt(n % 16);
	}			

	function get_abs_pos(element) {
		var r = { x: element.offsetLeft, y: element.offsetTop };

		if (element.offsetParent) {
			var tmp = get_abs_pos(element.offsetParent);
			r.x += tmp.x;
			r.y += tmp.y;
		}

		return r;
	};
			
	function get_xy(obj, event) {
		var x, y, top;
		event = event || window.event;
		var el = event.target || event.srcElement;

		// use absolute coordinates
		var pos = get_abs_pos(obj);
		
		// scroll position (if panel is 'fixed')
		if($('div.rte-panel').css('position') == "fixed") top = $(window).scrollTop();

		// subtract distance to middle
		x = event.pageX  - pos.x;
		y = event.pageY - pos.y - top;

		return { x: x, y: y };
	}
			
	function compute_color(obj, is_rgb, is_gray, is_palette, e) {
		var r, g, b, c;

		var mouse = get_xy(obj, e);
		var x = mouse.x;
		var y = mouse.y;

		if(is_rgb) {
			r = (x >= 0)*(x < part_width)*255 + (x >= part_width)*(x < 2*part_width)*(2*255 - x * 255 / part_width) + (x >= 4*part_width)*(x < 5*part_width)*(-4*255 + x * 255 / part_width) + (x >= 5*part_width)*(x < 6*part_width)*255;
			g = (x >= 0)*(x < part_width)*(x * 255 / part_width) + (x >= part_width)*(x < 3*part_width)*255	+ (x >= 3*part_width)*(x < 4*part_width)*(4*255 - x * 255 / part_width);
			b = (x >= 2*part_width)*(x < 3*part_width)*(-2*255 + x * 255 / part_width) + (x >= 3*part_width)*(x < 5*part_width)*255 + (x >= 5*part_width)*(x < 6*part_width)*(6*255 - x * 255 / part_width);

			var k = (height - y) / height;

			r = 128 + (r - 128) * k;
			g = 128 + (g - 128) * k;
			b = 128 + (b - 128) * k;
		} else if (is_gray) {
			r = g = b = (height - y) * 1.7;
		} else if(is_palette) {
			x = Math.floor(x / 10);
			y = Math.floor(y / 10);
			c = colors[x + y * 5];
		}

		if(!is_palette)
			c = '#' + to_hex(r) + to_hex(g) + to_hex(b);

		preview.css('background', c);
		color.html(c);
	}
}
// Images
function lwrte_image() {
	var self = this;
	
	// Custom - Exists?
	var img_url = '';
	var img_align = '';
	var img_style = '';
	var html = self.get_selected_html();
	if(html) {
		if($(html).attr('src')) img_url = $(html).attr('src');
		if($(html).attr('align')) img_align = $(html).attr('align');
		if($(html).attr('style')) img_style = $(html).attr('style');
	}
	
	var panel_text = '\
<p><label>Image</label><input type="text" id="url" size="30" value="'+img_url+'" /><button id="view">View</button></p>';
	panel_text = panel_text + '\
<p><label>Upload</label><input type="file" name="lwrte_file" id="lwrte_file" size="22" /></p>';
	panel_text = panel_text + '\
<div class="clear"></div>\
<p><label>Align</label><select id="align"><option value="left"';
	if(img_align == "left") panel_text += ' selected="selected"';
	panel_text += '>Left</option><option value="right"';
	if(img_align == "right") panel_text += ' selected="selected"';
	panel_text += '>Right</option></select></p>\
<div class="clear"></div>\
<div id="preview" style="margin-left:25px;"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Cancel</button></p>';
	
	var panel = self.create_panel('Insert image', 385);
	panel.append(panel_text).show();

	var url = $('#url', panel);
	$('#lwrte_file', panel).change(function(){
		// Loader
		loader("preview",'Uploading..');
		
		$.ajaxFileUpload({
			url:DOMAIN+'?ajaxRequest=upload_rte',
			secureuri:false,
			fileElementId:'lwrte_file',
			dataType: 'json',
			success: function (data, status) {
				// Place Filename
				$("#url", panel).val(data.file);
				// Clear File Input and Preview
				$('#lwrte_file', panel).val("");
				$("#preview", panel).html('');
				// Hide Failure Messages
				$("#red", panel).animate({opacity: 1.0}, 1500).slideUp(500, function() {$(this).remove();});
			}/*,
			error: function (data, status, e) {
				alert(e);
			}*/
		});														
	});

	$('#view', panel).click( function() {
			(url.val().length >0 ) ? window.open(url.val()) : alert("Enter URL of image to view");
			return false;
		}
	);
			
	$('#cancel', panel).click( function() { panel.remove(); return false;} );
	$('#ok', panel).click( 
		function() {
			var file = url.val();
			
			// Original (wasn't placing image at cursor, didn't handle align, etc.)
			//self.editor_cmd('insertImage', file);
			// New (custom)
			var align = $('#align', panel).val();
			var h = "<img src='"+file+"' alt=''";
			if(align) h += " align='"+align+"'";
			h += " />";
			self.selection_replace_with(h); 
			//self.editor_cmd("insertHTML", h); // doesn't work in IE and changes domain to relative path in Firefox which we don't want
			
			panel.remove(); 
			lwrte_save(self); // Custom - Save Text
			return false;
		}
	)
}

function lwrte_unformat() {
	this.editor_cmd('removeFormat');
	this.editor_cmd('unlink');
}

function lwrte_clear() {
	if(confirm('Clear Document?')) 
		this.set_content('');
}

function lwrte_link() {
	var self = this;
	var panel = self.create_panel("Create link / Attach file", 385);

	panel.append('\
<p><label>URL</label><input type="text" id="url" size="30" value=""><button id="file">Attach File</button><button id="view">View</button></p>\
<div class="clear"></div>\
<p><label>Title</label><input type="text" id="title" size="30" value=""><label>Target</label><select id="target"><option value="">default</option><option value="_blank">new</option></select></p>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Cancel</button></p>'
).show();

	$('#cancel', panel).click( function() { panel.remove(); return false; } );

	var url = $('#url', panel);
	var upload = $('#file', panel).upload( {
		autoSubmit: true,
		action: 'uploader.php',
		onComplete: function(response) { 
			if(response.length <= 0)
				return;

			response	= eval("(" + response + ")");

			if(response.error && response.error.length > 0)
				alert(response.error);
			else
				url.val((response.file && response.file.length > 0) ? response.file : '');
		}
	});

	$('#view', panel).click( function() {
		(url.val().length >0 ) ? window.open(url.val()) : alert("Enter URL to view");
		return false;
	}
	);

	$('#ok', panel).click( 
		function() {
			var url = $('#url', panel).val();
			var target = $('#target', panel).val();
			var title = $('#title', panel).val();

			if(self.get_selected_text().length <= 0) {
				alert('Select the text you wish to link!');
				return false;
			}

			panel.remove(); 

			if(url.length <= 0)
				return false;

			self.editor_cmd('unlink');

			// we wanna well-formed linkage (<p>,<h1> and other block types can't be inside of link due to WC3)
			self.editor_cmd('createLink', rte_tag);
			var tmp = $('<span></span>').append(self.get_selected_html());
	
			if(target.length > 0) $('a[href*="' + rte_tag + '"]', tmp).attr('target', target);
			if(title.length > 0) $('a[href*="' + rte_tag + '"]', tmp).attr('title', title);
			$('a[href*="' + rte_tag + '"]', tmp).attr('href', url);
					
			self.selection_replace_with(tmp.html());
			lwrte_save(self); // Custom - Save Text
			
			return false;
		}
	)
}

// Links (basic)
function lwrte_link_basic(){
	var self=this;
	
	// Text ?
	var text = self.get_selected_text();
	if(text.length<=0){alert("Please select the text which you'd like to link.");return false}
	
	var panel=self.create_panel("Add a Link",385);
	panel.append('<p><label>URL</label><input type="text" id="url" size="30" value=""><button id="view">View</button></p><div class="clear"></div><p><label>Title</label><input type="text" id="title" size="30" value=""></p><div class="clear"></div><p class="submit"><button id="ok">Ok</button><button id="cancel">Cancel</button></p>').show();
	$("#cancel",panel).click(function(){panel.remove();return false});
	var url=$("#url",panel);
	$("#view",panel).click(function(){(url.val().length>0)?window.open(url.val()):alert("Enter URL to view");return false});
	$("#ok",panel).click(function(){
		var url = $("#url",panel).val();
		var title = $("#title",panel).val();
		var target = $("#target",panel).val();
		
		if(self.get_selected_text().length <= 0){alert("Select the text you wish to link!");return false}
		panel.remove();
		if(url.length<=0){return false}
		self.editor_cmd("unlink");
		
		// Simplest Method (but doesn't use title/target attributes)
		if($.browser.msie) self.editor_cmd('createLink', url);
		// Basic Method (good, but doesn't work with IE 6/7 [no support for insertHTML])
		else {
			var h = '<a href="' + url + '"';
			if(target) h += ' target="'+target+'"';
			if(title) h += ' title="'+title+'"';
			h += '>' + self.get_selected_html() + '</a>';
			self.editor_cmd("insertHTML", h);
		}
		
		// Custom - Save Text
		lwrte_save(self); 
		
		return false;
	})
};

// Links (suggestions)
function lwrte_link_suggestions(text){
	var self = this;
	// Text ?
	var text = self.get_selected_text();
	var html = self.get_selected_text();
	if(text.length<=0){alert("Please select the text which you'd like to link.");return false}
	
	// Panel
	var panel=self.create_panel("Add a Link",450);
	panel.append("<div id='rte_link_suggestions'><br /><br /><center><img src='"+DOMAIN+"images/ajax-loader.gif' alt='Loading..' /></center></div><p class='submit'><button id='ok'>Ok</button><button id='cancel'>Cancel</button></p>").show();
	$("#cancel",panel).click(function(){panel.remove();return false});
	$.ajax({
		type: 'POST',
		url: DOMAIN,
		data: 'ajaxRequest=suggestIt&type=link&text='+encodeURIComponent(text),
		success: function(html){
			$('#rte_link_suggestions').html(html);
			thickbox();
			
			$("tr.suggestion",panel).click(function(){
				$("tr.selected",panel).removeClass('selected');
				$(this).addClass('selected');
			});
		}
	});
	
	$("#ok",panel).click(function(){
		/*var url = $("tr.selected input[name=url]",panel).val();
		var title = $("tr.selected input[name=title]",panel).val();
		var target = $("tr.selected input[name=target]",panel).val();

		if(self.get_selected_text().length <= 0) {
			alert('Select the text you wish to link!');
			return false;
		}

		panel.remove(); 

		if(url.length <= 0)
			return false;

		self.editor_cmd('unlink');

		// we wanna well-formed linkage (<p>,<h1> and other block types can't be inside of link due to WC3)
		self.editor_cmd('createLink', rte_tag);
		var tmp = $('<span></span>').append(self.get_selected_html());

		if(target.length > 0)
			$('a[href*="' + rte_tag + '"]', tmp).attr('target', target);

		if(title.length > 0)
			$('a[href*="' + rte_tag + '"]', tmp).attr('title', title);

		$('a[href*="' + rte_tag + '"]', tmp).attr('href', url);
			
		self.selection_replace_with(tmp.html());
		return false;*/
		
		var url = $("tr.selected input[name=url]",panel).val();
		var title = $("tr.selected input[name=title]",panel).val();
		var target = $("tr.selected input[name=target]",panel).val();
		if(url.length <= 0) {alert("Please select a suggested link");return false}
		if(self.get_selected_text().length<=0){alert("Please select the text in the texteditor which you'd like to link.");return false}
		
		panel.remove();
		self.editor_cmd("unlink");
		
		// Some Early Mixed Method
		// we wanna well-formed linkage (<p>,<h1> and other block types can't be inside of link due to WC3)
		/*if ($.browser.safari) {
			var h = '<a href="' + url + '"';
			if(target) h += ' target="'+target+'"';
			if(title)  h += ' title="'+title+'"';
			h += '>' + self.get_selected_text() + '</a>';
			self.editor_cmd("insertHTML", h)
		}
		else {
			self.editor_cmd('createLink', rte_tag);
			var tmp = $('<span></span>').append(self.get_selected_html());

			if(target) $('a[href*="' + rte_tag + '"]', tmp).attr('target', target);
			if(title) $('a[href*="' + rte_tag + '"]', tmp).attr('title', title);
			$('a[href*="' + rte_tag + '"]', tmp).attr('href', url);
				
			self.selection_replace_with(tmp.html());
		}
		self.set_content($.trim(self.get_content()));*/
		
		// Simplest Method (but doesn't use title/target attributes)
		if($.browser.msie) self.editor_cmd('createLink', url);
		// Basic Method (good, but doesn't work with IE 6/7 [no support for insertHTML])
		else {
			var h = '<a href="' + url + '"';
			if(target) h += ' target="'+target+'"';
			if(title) h += ' title="'+title+'"';
			h += '>' + self.get_selected_html() + '</a>';
			self.editor_cmd("insertHTML", h);
		}
		
		// My Tweaked Method (lots of issues with breaks, bullets, etc.)
		/*if ($.browser.safari) {
			var h = '<a href="' + url + '"';
			if(target) h += ' target="'+target+'"';
			if(title) h += ' title="'+title+'"';
			h += '>' + self.get_selected_text() + '</a>';
			self.selection_replace_with(h);
		}
		else {
			self.editor_cmd('createLink', rte_tag);
			var tmp = $('<span></span>').append(self.get_selected_html());
			if(title) $('a[href*="' + rte_tag + '"]', tmp).attr('title', title);
			if(target) $('a[href*="' + rte_tag + '"]', tmp).attr('target', target);
			$('a[href*="' + rte_tag + '"]', tmp).attr('href', url);
			self.selection_replace_with(tmp.html());
		}*/
		
		// Original
		// we wanna well-formed linkage (<p>,<h1> and other block types can't be inside of link due to WC3)
		/*self.editor_cmd('createLink', rte_tag);
		var tmp = $('<span></span>').append(self.get_selected_html());
		if(target.length > 0) $('a[href*="' + rte_tag + '"]', tmp).attr('target', target);
		if(title.length > 0) $('a[href*="' + rte_tag + '"]', tmp).attr('title', title);
		$('a[href*="' + rte_tag + '"]', tmp).attr('href', url);
		self.selection_replace_with(tmp.html());*/
		
		// Custom - Save Text
		lwrte_save(self); 
		
		return false;
	})
};

/*************************** Interface (for nestable) **********************/
/** iutil **/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('9.J={1C:6(e){4 x=0;4 y=0;4 7=e.Y;4 12=1H;c(9(e).8(\'A\')==\'T\'){4 N=7.B;4 Q=7.z;12=1f;7.B=\'1r\';7.A=\'1q\';7.z=\'1d\'}4 3=e;R(3){x+=3.1h+(3.O&&!9.1m.1i?d(3.O.17)||0:0);y+=3.1n+(3.O&&!9.1m.1i?d(3.O.18)||0:0);3=3.1t}3=e;R(3&&3.1e&&3.1e.16()!=\'f\'){x-=3.u||0;y-=3.F||0;3=3.1D}c(12==1f){7.A=\'T\';7.z=Q;7.B=N}a{x:x,y:y}},1B:6(3){4 x=0,y=0;R(3){x+=3.1h||0;y+=3.1n||0;3=3.1t}a{x:x,y:y}},1s:6(e){4 w=9.8(e,\'1E\');4 h=9.8(e,\'1G\');4 o=0;4 q=0;4 7=e.Y;c(9(e).8(\'A\')!=\'T\'){o=e.V;q=e.U}p{4 N=7.B;4 Q=7.z;7.B=\'1r\';7.A=\'1q\';7.z=\'1d\';o=e.V;q=e.U;7.A=\'T\';7.z=Q;7.B=N}a{w:w,h:h,o:o,q:q}},1F:6(3){a{o:3.V||0,q:3.U||0}},1I:6(e){4 h,w,C;c(e){w=e.I;h=e.G}p{C=5.j;w=1c.14||P.14||(C&&C.I)||5.f.I;h=1c.10||P.10||(C&&C.G)||5.f.G}a{w:w,h:h}},1p:6(e){4 t=0,l=0,w=0,h=0,s=0,E=0;c(e&&e.1u.16()!=\'f\'){t=e.F;l=e.u;w=e.15;h=e.W;s=0;E=0}p{c(5.j){t=5.j.F;l=5.j.u;w=5.j.15;h=5.j.W}p c(5.f){t=5.f.F;l=5.f.u;w=5.f.15;h=5.f.W}s=P.14||5.j.I||5.f.I||0;E=P.10||5.j.G||5.f.G||0}a{t:t,l:l,w:w,h:h,s:s,E:E}},1v:6(e,D){4 3=9(e);4 t=3.8(\'1w\')||\'\';4 r=3.8(\'1x\')||\'\';4 b=3.8(\'1A\')||\'\';4 l=3.8(\'1z\')||\'\';c(D)a{t:d(t)||0,r:d(r)||0,b:d(b)||0,l:d(l)};p a{t:t,r:r,b:b,l:l}},1y:6(e,D){4 3=9(e);4 t=3.8(\'1J\')||\'\';4 r=3.8(\'1M\')||\'\';4 b=3.8(\'27\')||\'\';4 l=3.8(\'28\')||\'\';c(D)a{t:d(t)||0,r:d(r)||0,b:d(b)||0,l:d(l)};p a{t:t,r:r,b:b,l:l}},26:6(e,D){4 3=9(e);4 t=3.8(\'18\')||\'\';4 r=3.8(\'22\')||\'\';4 b=3.8(\'23\')||\'\';4 l=3.8(\'17\')||\'\';c(D)a{t:d(t)||0,r:d(r)||0,b:d(b)||0,l:d(l)||0};p a{t:t,r:r,b:b,l:l}},2e:6(L){4 x=L.2d||(L.2b+(5.j.u||5.f.u))||0;4 y=L.2c||(L.29+(5.j.F||5.f.F))||0;a{x:x,y:y}},X:6(g,13){13(g);g=g.1O;R(g){9.J.X(g,13);g=g.1L}},1N:6(g){9.J.X(g,6(3){19(4 Z 1T 3){c(1Z 3[Z]===\'6\'){3[Z]=1a}}})},1X:6(3,H){4 k=9.J.1p();4 11=9.J.1s(3);c(!H||H==\'1W\')9(3).8({1U:k.t+((1g.1o(k.h,k.E)-k.t-11.q)/2)+\'1j\'});c(!H||H==\'20\')9(3).8({1Y:k.l+((1g.1o(k.w,k.s)-k.l-11.o)/2)+\'1j\'})},2f:6(3,1l){4 1k=9(\'25[@M*="S"]\',3||5),S;1k.24(6(){S=K.M;K.M=1l;K.Y.2a="21:1R.1P.1V(M=\'"+S+"\')"})}};[].1b||(1S.1Q.1b=6(v,n){n=(n==1a)?0:n;4 m=K.1K;19(4 i=n;i<m;i++)c(K[i]==v)a i;a-1});',62,140,'|||el|var|document|function|es|css|jQuery|return||if|parseInt||body|nodeEl|||documentElement|clientScroll||||wb|else|hb||iw||scrollLeft|||||position|display|visibility|de|toInteger|ih|scrollTop|clientHeight|axis|clientWidth|iUtil|this|event|src|oldVisibility|currentStyle|self|oldPosition|while|png|none|offsetHeight|offsetWidth|scrollHeight|traverseDOM|style|attr|innerHeight|windowSize|restoreStyles|func|innerWidth|scrollWidth|toLowerCase|borderLeftWidth|borderTopWidth|for|null|indexOf|window|absolute|tagName|true|Math|offsetLeft|opera|px|images|emptyGIF|browser|offsetTop|max|getScroll|block|hidden|getSize|offsetParent|nodeName|getMargins|marginTop|marginRight|getPadding|marginLeft|marginBottom|getPositionLite|getPosition|parentNode|width|getSizeLite|height|false|getClient|paddingTop|length|nextSibling|paddingRight|purgeEvents|firstChild|Microsoft|prototype|DXImageTransform|Array|in|top|AlphaImageLoader|vertically|centerEl|left|typeof|horizontally|progid|borderRightWidth|borderBottomWidth|each|img|getBorder|paddingBottom|paddingLeft|clientY|filter|clientX|pageY|pageX|getPointer|fixPNG'.split('|'),0,{}))
/** idrag **/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('8.c={m:W,7:W,2g:z(){B a.1x(z(){9(a.1v){a.5.P.27(\'2L\',8.c.1X);a.5=W;a.1v=d;9(8.13.1o){a.1U="3o"}H{a.v.3n=\'\';a.v.2V=\'\';a.v.2G=\'\'}}})},1X:z(e){9(8.c.7!=W){8.c.1H(e);B d}k 6=a.1z;8(1c).24(\'2u\',8.c.20).24(\'2r\',8.c.1H);6.5.C=8.E.2U(e);6.5.10=6.5.C;6.5.1E=d;6.5.3g=a!=a.1z;8.c.7=6;9(6.5.12&&a!=a.1z){21=8.E.26(6.1p);22=8.E.1K(6);25={x:u(8.q(6,\'K\'))||0,y:u(8.q(6,\'J\'))||0};j=6.5.10.x-21.x-22.1h/2-25.x;g=6.5.10.y-21.y-22.Y/2-25.y;8.1Y.3y(6,[j,g])}B 8.3f||d},2I:z(e){k 6=8.c.7;6.5.1E=G;k 1G=6.v;6.5.1B=8.q(6,\'T\');6.5.1q=8.q(6,\'1N\');9(!6.5.2p)6.5.2p=6.5.1q;6.5.n={x:u(8.q(6,\'K\'))||0,y:u(8.q(6,\'J\'))||0};6.5.1L=0;6.5.1J=0;9(8.13.1o){k 1V=8.E.2f(6,G);6.5.1L=1V.l||0;6.5.1J=1V.t||0}6.5.f=8.1A(8.E.26(6),8.E.1K(6));9(6.5.1q!=\'2A\'&&6.5.1q!=\'2W\'){1G.1N=\'2A\'}8.c.m.2h();k V=6.34(G);8(V).q({T:\'2x\',K:\'16\',J:\'16\'});V.v.2w=\'0\';V.v.2v=\'0\';V.v.2t=\'0\';V.v.2s=\'0\';8.c.m.1y(V);k F=8.c.m.Z(0).v;9(6.5.1Z){F.2d=\'2B\';F.2c=\'2B\'}H{F.2c=6.5.f.Y+\'O\';F.2d=6.5.f.1h+\'O\'}F.T=\'2x\';F.2w=\'16\';F.2v=\'16\';F.2t=\'16\';F.2s=\'16\';8.1A(6.5.f,8.E.1K(V));9(6.5.A){9(6.5.A.K){6.5.n.x+=6.5.C.x-6.5.f.x-6.5.A.K;6.5.f.x=6.5.C.x-6.5.A.K}9(6.5.A.J){6.5.n.y+=6.5.C.y-6.5.f.y-6.5.A.J;6.5.f.y=6.5.C.y-6.5.A.J}9(6.5.A.2b){6.5.n.x+=6.5.C.x-6.5.f.x-6.5.f.Y+6.5.A.2b;6.5.f.x=6.5.C.x-6.5.f.1h+6.5.A.2b}9(6.5.A.28){6.5.n.y+=6.5.C.y-6.5.f.y-6.5.f.Y+6.5.A.28;6.5.f.y=6.5.C.y-6.5.f.Y+6.5.A.28}}6.5.1I=6.5.n.x;6.5.1M=6.5.n.y;9(6.5.1u||6.5.p==\'1w\'){1r=8.E.2f(6.1p,G);6.5.f.x=6.37+(8.13.1o?0:8.13.2n?-1r.l:1r.l);6.5.f.y=6.38+(8.13.1o?0:8.13.2n?-1r.t:1r.t);8(6.1p).1y(8.c.m.Z(0))}9(6.5.p){8.c.2q(6);6.5.S.p=8.c.2j}9(6.5.12){8.1Y.31(6)}F.K=6.5.f.x-6.5.1L+\'O\';F.J=6.5.f.y-6.5.1J+\'O\';F.2d=6.5.f.1h+\'O\';F.2c=6.5.f.Y+\'O\';8.c.7.5.1F=d;9(6.5.1i){6.5.S.X=8.c.2o}9(6.5.17!=d){8.c.m.q(\'17\',6.5.17)}9(6.5.N){8.c.m.q(\'N\',6.5.N);9(1P.1O){8.c.m.q(\'2y\',\'2C(N=\'+6.5.N*2z+\')\')}}9(6.5.1f){8.c.m.3a(6.5.1f);8.c.m.Z(0).3e.v.T=\'M\'}9(6.5.1j)6.5.1j.1m(6,[V,6.5.n.x,6.5.n.y]);9(8.L&&8.L.2a>0){8.L.2Z(6)}9(6.5.19==d){1G.T=\'M\'}B d},2q:z(6){9(6.5.p.I==2P){9(6.5.p==\'1w\'){6.5.s=8.1A({x:0,y:0},8.E.1K(6.1p));k 1t=8.E.2f(6.1p,G);6.5.s.w=6.5.s.1h-1t.l-1t.r;6.5.s.h=6.5.s.Y-1t.t-1t.b}H 9(6.5.p==\'1c\'){k 29=8.E.3x();6.5.s={x:0,y:0,w:29.w,h:29.h}}}H 9(6.5.p.I==2F){6.5.s={x:u(6.5.p[0])||0,y:u(6.5.p[1])||0,w:u(6.5.p[2])||0,h:u(6.5.p[3])||0}}6.5.s.j=6.5.s.x-6.5.f.x;6.5.s.g=6.5.s.y-6.5.f.y},1C:z(7){9(7.5.1u||7.5.p==\'1w\'){8(\'2H\',1c).1y(8.c.m.Z(0))}8.c.m.2h().3v().q(\'N\',1);9(1P.1O){8.c.m.q(\'2y\',\'2C(N=2z)\')}},1H:z(e){8(1c).27(\'2u\',8.c.20).27(\'2r\',8.c.1H);9(8.c.7==W){B}k 7=8.c.7;8.c.7=W;9(7.5.1E==d){B d}9(7.5.15==G){8(7).q(\'1N\',7.5.1q)}k 1G=7.v;9(7.12){8.c.m.q(\'2J\',\'2N\')}9(7.5.1f){8.c.m.3t(7.5.1f)}9(7.5.1T==d){9(7.5.R>0){9(!7.5.D||7.5.D==\'1S\'){k x=2D 8.R(7,{2m:7.5.R},\'K\');x.2i(7.5.n.x,7.5.1l)}9(!7.5.D||7.5.D==\'1Q\'){k y=2D 8.R(7,{2m:7.5.R},\'J\');y.2i(7.5.n.y,7.5.1k)}}H{9(!7.5.D||7.5.D==\'1S\')7.v.K=7.5.1l+\'O\';9(!7.5.D||7.5.D==\'1Q\')7.v.J=7.5.1k+\'O\'}8.c.1C(7);9(7.5.19==d){8(7).q(\'T\',7.5.1B)}}H 9(7.5.R>0){7.5.1F=G;k 1e=d;9(8.L&&8.1D&&7.5.15){1e=8.E.26(8.1D.m.Z(0))}8.c.m.3i({K:1e?1e.x:7.5.f.x,J:1e?1e.y:7.5.f.y},7.5.R,z(){7.5.1F=d;9(7.5.19==d){7.v.T=7.5.1B}8.c.1C(7)})}H{8.c.1C(7);9(7.5.19==d){8(7).q(\'T\',7.5.1B)}}9(8.L&&8.L.2a>0){8.L.3h(7)}9(8.1D&&7.5.15){8.1D.3m(7)}9(7.5.11&&(7.5.1l!=7.5.n.x||7.5.1k!=7.5.n.y)){7.5.11.1m(7,7.5.3r||[0,0,7.5.1l,7.5.1k])}9(7.5.1g)7.5.1g.1m(7);B d},2o:z(x,y,j,g){9(j!=0)j=u((j+(a.5.1i*j/U.2k(j))/2)/a.5.1i)*a.5.1i;9(g!=0)g=u((g+(a.5.1s*g/U.2k(g))/2)/a.5.1s)*a.5.1s;B{j:j,g:g,x:0,y:0}},2j:z(x,y,j,g){j=U.2l(U.2T(j,a.5.s.j),a.5.s.w+a.5.s.j-a.5.f.1h);g=U.2l(U.2T(g,a.5.s.g),a.5.s.h+a.5.s.g-a.5.f.Y);B{j:j,g:g,x:0,y:0}},20:z(e){9(8.c.7==W||8.c.7.5.1F==G){B}k 7=8.c.7;7.5.10=8.E.2U(e);9(7.5.1E==d){2E=U.3l(U.2O(7.5.C.x-7.5.10.x,2)+U.2O(7.5.C.y-7.5.10.y,2));9(2E<7.5.1R){B}H{8.c.2I(e)}}k j=7.5.10.x-7.5.C.x;k g=7.5.10.y-7.5.C.y;3k(k i 3s 7.5.S){k 14=7.5.S[i].1m(7,[7.5.n.x+j,7.5.n.y+g,j,g]);9(14&&14.I==3A){j=i!=\'1d\'?14.j:(14.x-7.5.n.x);g=i!=\'1d\'?14.g:(14.y-7.5.n.y)}}7.5.1I=7.5.f.x+j-7.5.1L;7.5.1M=7.5.f.y+g-7.5.1J;9(7.5.12&&(7.5.1a||7.5.11)){8.1Y.1a(7,7.5.1I,7.5.1M)}9(7.5.18)7.5.18.1m(7,[7.5.n.x+j,7.5.n.y+g]);9(!7.5.D||7.5.D==\'1S\'){7.5.1l=7.5.n.x+j;8.c.m.Z(0).v.K=7.5.1I+\'O\'}9(!7.5.D||7.5.D==\'1Q\'){7.5.1k=7.5.n.y+g;8.c.m.Z(0).v.J=7.5.1M+\'O\'}9(8.L&&8.L.2a>0){8.L.3u(7)}B d},2M:z(o){9(!8.c.m){8(\'2H\',1c).1y(\'<2X 3w="2S"></2X>\');8.c.m=8(\'#2S\');k 1n=8.c.m.Z(0);k Q=1n.v;Q.1N=\'2W\';Q.T=\'M\';Q.2J=\'2N\';Q.30=\'M\';Q.39=\'3c\';9(1P.1O){1n.1U="2R"}H{Q.3d=\'M\';Q.2G=\'M\';Q.2V=\'M\'}}9(!o){o={}}B a.1x(z(){9(a.1v||!8.E)B;9(1P.1O){a.33=z(){B d};a.32=z(){B d}}k 1n=a;k P=o.2Q?8(a).35(o.2Q):8(a);9(8.13.1o){P.1x(z(){a.1U="2R"})}H{P.q(\'-36-1d-1W\',\'M\');P.q(\'1d-1W\',\'M\');P.q(\'-2Y-1d-1W\',\'M\')}a.5={P:P,1T:o.1T?G:d,19:o.19?G:d,15:o.15?o.15:d,12:o.12?o.12:d,1u:o.1u?o.1u:d,17:o.17?u(o.17)||0:d,N:o.N?3B(o.N):d,R:u(o.R)||W,23:o.23?o.23:d,S:{},C:{},1j:o.1j&&o.1j.I==1b?o.1j:d,1g:o.1g&&o.1g.I==1b?o.1g:d,11:o.11&&o.11.I==1b?o.11:d,D:/1Q|1S/.3j(o.D)?o.D:d,1R:o.1R?u(o.1R)||0:0,A:o.A?o.A:d,1Z:o.1Z?G:d,1f:o.1f||d};9(o.S&&o.S.I==1b)a.5.S.1d=o.S;9(o.18&&o.18.I==1b)a.5.18=o.18;9(o.p&&((o.p.I==2P&&(o.p==\'1w\'||o.p==\'1c\'))||(o.p.I==2F&&o.p.2K==4))){a.5.p=o.p}9(o.2e){a.5.2e=o.2e}9(o.X){9(3C o.X==\'3q\'){a.5.1i=u(o.X)||1;a.5.1s=u(o.X)||1}H 9(o.X.2K==2){a.5.1i=u(o.X[0])||1;a.5.1s=u(o.X[1])||1}}9(o.1a&&o.1a.I==1b){a.5.1a=o.1a}a.1v=G;P.1x(z(){a.1z=1n});P.24(\'2L\',8.c.1X)})}};8.3z.1A({3p:8.c.2g,3b:8.c.2M});',62,225,'|||||dragCfg|elm|dragged|jQuery|if|this||iDrag|false||oC|dy|||dx|var||helper|oR||containment|css||cont||parseInt|style||||function|cursorAt|return|pointer|axis|iUtil|dhs|true|else|constructor|top|left|iDrop|none|opacity|px|dhe|els|fx|onDragModifier|display|Math|clonedEl|null|grid|hb|get|currentPointer|onChange|si|browser|newCoords|so|0px|zIndex|onDrag|ghosting|onSlide|Function|document|user|dh|frameClass|onStop|wb|gx|onStart|nRy|nRx|apply|el|msie|parentNode|oP|parentBorders|gy|contBorders|insideParent|isDraggable|parent|each|append|dragElem|extend|oD|hidehelper|iSort|init|prot|dEs|dragstop|nx|diffY|getSize|diffX|ny|position|ActiveXObject|window|vertically|snapDistance|horizontally|revert|unselectable|oldBorder|select|draginit|iSlider|autoSize|dragmove|parentPos|sliderSize|hpc|bind|sliderPos|getPosition|unbind|bottom|clnt|count|right|height|width|fractions|getBorder|destroy|empty|custom|fitToContainer|abs|min|duration|opera|snapToGrid|initialPosition|getContainment|mouseup|marginLeft|marginBottom|mousemove|marginRight|marginTop|block|filter|100|relative|auto|alpha|new|distance|Array|userSelect|body|dragstart|cursor|length|mousedown|build|move|pow|String|handle|on|dragHelper|max|getPointer|KhtmlUserSelect|absolute|div|khtml|highlight|listStyle|modifyContainer|ondragstart|onselectstart|cloneNode|find|moz|offsetLeft|offsetTop|overflow|addClass|Draggable|hidden|mozUserSelect|firstChild|selectKeyHelper|fromHandler|checkdrop|animate|test|for|sqrt|check|MozUserSelect|off|DraggableDestroy|number|lastSi|in|removeClass|checkhover|hide|id|getClient|dragmoveBy|fn|Object|parseFloat|typeof'.split('|'),0,{}))
/** idrop **/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('1.4={1o:l(u,r,G,F){v u<=1.6.8.9.X&&(u+G)>=(1.6.8.9.X+1.6.8.9.S.w)&&r<=1.6.8.9.Q&&(r+F)>=(1.6.8.9.Q+1.6.8.9.S.h)?k:7},1r:l(u,r,G,F){v!(u>(1.6.8.9.X+1.6.8.9.S.w)||(u+G)<1.6.8.9.X||r>(1.6.8.9.Q+1.6.8.9.S.h)||(r+F)<1.6.8.9.Q)?k:7},1q:l(u,r,G,F){v u<1.6.8.9.O.x&&(u+G)>1.6.8.9.O.x&&r<1.6.8.9.O.y&&(r+F)>1.6.8.9.O.y?k:7},C:7,g:{},1u:0,j:{},1E:l(D){5(1.6.8==E){v}n i;1.4.g={};n 15=7;T(i R 1.4.j){5(1.4.j[i]!=E){n 2=1.4.j[i].q(0);5(1(1.6.8).1d(\'.\'+2.3.a)){5(2.3.m==7){2.3.p=1.18(1.K.1c(2),1.K.1b(2));2.3.m=k}5(2.3.A){1.4.j[i].13(2.3.A)}1.4.g[i]=1.4.j[i];5(1.c&&2.3.s&&1.6.8.9.W){2.3.1e=1(\'.\'+2.3.a,2);D.I.H=\'16\';1.c.1f(2);2.3.1k=1.c.1l(1.12(2,\'z\')).1t;D.I.H=D.9.1h;15=k}5(2.3.V){2.3.V.Z(1.4.j[i].q(0),[1.6.8])}}}}5(15){1.c.1F()}},1w:l(){1.4.g={};T(i R 1.4.j){5(1.4.j[i]!=E){n 2=1.4.j[i].q(0);5(1(1.6.8).1d(\'.\'+2.3.a)){2.3.p=1.18(1.K.1c(2),1.K.1b(2));5(2.3.A){1.4.j[i].13(2.3.A)}1.4.g[i]=1.4.j[i];5(1.c&&2.3.s&&1.6.8.9.W){2.3.1e=1(\'.\'+2.3.a,2);D.I.H=\'16\';1.c.1f(2);D.I.H=D.9.1h}}}}},1a:l(e){5(1.6.8==E){v}1.4.C=7;n i;n 14=7;n 1g=0;T(i R 1.4.g){n 2=1.4.g[i].q(0);5(1.4.C==7&&1.4[2.3.t](2.3.p.x,2.3.p.y,2.3.p.1A,2.3.p.1y)){5(2.3.B&&2.3.h==7){1.4.g[i].13(2.3.B)}5(2.3.h==7&&2.3.M){14=k}2.3.h=k;1.4.C=2;5(1.c&&2.3.s&&1.6.8.9.W){1.c.P.q(0).1J=2.3.1m;1.c.1a(2)}1g++}1U 5(2.3.h==k){5(2.3.N){2.3.N.Z(2,[e,1.6.P.q(0).1i,2.3.J])}5(2.3.B){1.4.g[i].11(2.3.B)}2.3.h=7}}5(1.c&&!1.4.C&&1.6.8.W){1.c.P.q(0).I.H=\'16\'}5(14){1.4.C.3.M.Z(1.4.C,[e,1.6.P.q(0).1i])}},1N:l(e){n i;T(i R 1.4.g){n 2=1.4.g[i].q(0);5(2.3.A){1.4.g[i].11(2.3.A)}5(2.3.B){1.4.g[i].11(2.3.B)}5(2.3.s){1.c.19[1.c.19.1Q]=i}5(2.3.L&&2.3.h==k){2.3.h=7;2.3.L.Z(2,[e,2.3.J])}2.3.m=7;2.3.h=7}1.4.g={}},1v:l(){v b.1j(l(){5(b.U){5(b.3.s){z=1.12(b,\'z\');1.c.1p[z]=E;1(\'.\'+b.3.a,b).1P()}1.4.j[\'d\'+b.17]=E;b.U=7;b.f=E}})},1n:l(o){v b.1j(l(){5(b.U==k||!o.1s||!1.K||!1.6){v}b.3={a:o.1s,A:o.1R||7,B:o.1O||7,1m:o.1K||7,L:o.1L||o.L||7,M:o.M||o.1T||7,N:o.N||o.1S||7,V:o.V||7,t:o.Y&&(o.Y==\'1o\'||o.Y==\'1r\')?o.Y:\'1q\',J:o.J?o.J:7,m:7,h:7};5(o.1D==k&&1.c){z=1.12(b,\'z\');1.c.1p[z]=b.3.a;b.3.s=k;5(o.10){b.3.10=o.10;b.3.1k=1.c.1l(z).1t}}b.U=k;b.17=1H(1G.1I()*1B);1.4.j[\'d\'+b.17]=1(b);1.4.1u++})}};1.1z.18({1x:1.4.1v,1C:1.4.1n});1.1M=1.4.1w;',62,119,'|jQuery|iEL|dropCfg|iDrop|if|iDrag|false|dragged|dragCfg||this|iSort||||highlighted|||zones|true|function||var|||get|zoney|||zonex|return||||id|ac|hc|overzone|elm|null|zoneh|zonew|display|style|fx|iUtil|onDrop|onHover|onOut|currentPointer|helper|ny|in|oC|for|isDroppable|onActivate|so|nx|tolerance|apply|onChange|removeClass|attr|addClass|applyOnHover|oneIsSortable|none|idsa|extend|changed|checkhover|getSizeLite|getPositionLite|is|el|measure|hlt|oD|firstChild|each|os|serialize|shc|build|fit|collected|pointer|intersect|accept|hash|count|destroy|remeasure|DroppableDestroy|hb|fn|wb|10000|Droppable|sortable|highlight|start|Math|parseInt|random|className|helperclass|ondrop|recallDroppables|checkdrop|hoverclass|DraggableDestroy|length|activeclass|onout|onhover|else'.split('|'),0,{}))
/** isort **/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('3.4={17:[],H:{},d:6,T:n,1T:k(){5(3.f.j==n){D}m w,U,c,I;3.4.d.8(0).1U=3.f.j.9.14;w=3.4.d.8(0).L;w.M=\'1k\';3.4.d.1l=3.1i(3.S.1X(3.4.d.8(0)),3.S.1Y(3.4.d.8(0)));w.1V=3.f.j.9.1l.1r+\'1E\';w.27=3.f.j.9.1l.1h+\'1E\';U=3.S.20(3.f.j);w.1z=U.t;w.1C=U.r;w.1y=U.b;w.1Q=U.l;5(3.f.j.9.J==u){c=3.f.j.28(u);I=c.L;I.1z=\'13\';I.1C=\'13\';I.1y=\'13\';I.1Q=\'13\';I.M=\'1k\';3.4.d.24().18(c)}3(3.f.j).1x(3.4.d.8(0));3.f.j.L.M=\'1a\'},23:k(e){5(!e.9.1e&&3.15.1t.1K){5(e.9.P)e.9.P.22(j);3(e).21(\'25\',e.9.26||e.9.2a);3(e).1u();3(3.15.1t).1S(e)}3.4.d.29(e.9.14).2b(\'&1N;\');3.4.T=n;m w=3.4.d.8(0).L;w.M=\'1a\';3.4.d.1x(e);5(e.9.v>0){3(e).1Z(e.9.v)}3(\'1D\').18(3.4.d.8(0));m Y=[];m V=6;Z(m i=0;i<3.4.17.A;i++){m N=3.15.1W[3.4.17[i]].8(0);m p=3.E(N,\'p\');m X=3.4.1p(p);5(N.g.1q!=X.1b){N.g.1q=X.1b;5(V==6&&N.g.10){V=N.g.10}X.p=p;Y[Y.A]=X}}3.4.17=[];5(V!=6&&Y.A>0){V(Y)}},2e:k(e,o){5(!3.f.j)D;m B=6;m i=0;5(e.g.q.1s()>0){Z(i=e.g.q.1s();i>0;i--){5(e.g.q.8(i-1)!=3.f.j){5(!e.C.1g){5((e.g.q.8(i-1).K.y+e.g.q.8(i-1).K.1h/2)>3.f.j.9.1v){B=e.g.q.8(i-1)}W{2v}}W{5((e.g.q.8(i-1).K.x+e.g.q.8(i-1).K.1r/2)>3.f.j.9.2t&&(e.g.q.8(i-1).K.y+e.g.q.8(i-1).K.1h/2)>3.f.j.9.1v){B=e.g.q.8(i-1)}}}}}5(B&&3.4.T!=B){3.4.T=B;3(B).2x(3.4.d.8(0))}W 5(!B&&(3.4.T!=n||3.4.d.8(0).2B!=e)){3.4.T=n;3(e).18(3.4.d.8(0))}3.4.d.8(0).L.M=\'1k\'},2z:k(e){5(3.f.j==n){D}e.g.q.F(k(){7.K=3.1i(3.S.2A(7),3.S.2y(7))})},1p:k(s){m i;m h=\'\';m o={};5(s){5(3.4.H[s]){o[s]=[];3(\'#\'+s+\' .\'+3.4.H[s]).F(k(){5(h.A>0){h+=\'&\'}h+=s+\'[]=\'+3.E(7,\'p\');o[s][o[s].A]=3.E(7,\'p\')})}W{Z(a 1w s){5(3.4.H[s[a]]){o[s[a]]=[];3(\'#\'+s[a]+\' .\'+3.4.H[s[a]]).F(k(){5(h.A>0){h+=\'&\'}h+=s[a]+\'[]=\'+3.E(7,\'p\');o[s[a]][o[s[a]].A]=3.E(7,\'p\')})}}}}W{Z(i 1w 3.4.H){o[i]=[];3(\'#\'+i+\' .\'+3.4.H[i]).F(k(){5(h.A>0){h+=\'&\'}h+=i+\'[]=\'+3.E(7,\'p\');o[i][o[i].A]=3.E(7,\'p\')})}}D{1b:h,o:o}},1L:k(e){5(!e.2h){D}D 7.F(k(){5(!7.C||!3(e).2g(\'.\'+7.C.z))3(e).2d(7.C.z);3(e).1I(7.C.9)})},1M:k(){D 7.F(k(){3(\'.\'+7.C.z).1u();3(7).2c();7.C=n;7.1H=n})},1A:k(o){5(o.z&&3.S&&3.f&&3.15){5(!3.4.d){3(\'1D\',2i).18(\'<1P p="1R">&1N;</1P>\');3.4.d=3(\'#1R\');3.4.d.8(0).L.M=\'1a\'}7.2j({z:o.z,19:o.19?o.19:6,1c:o.1c?o.1c:6,G:o.G?o.G:6,1O:o.1O||o.2o,1J:o.1J||o.2n,1K:u,10:o.10||o.2m,v:o.v?o.v:6,J:o.J?u:6,1m:o.1m?o.1m:\'2k\'});D 7.F(k(){m 9={11:o.11?u:6,1G:1F,O:o.O?1B(o.O):6,14:o.G?o.G:6,v:o.v?o.v:6,1e:u,J:o.J?u:6,R:o.R?o.R:n,Q:o.Q?o.Q:n,12:o.12&&o.12.1o==1n?o.12:6,16:o.16&&o.16.1o==1n?o.16:6,P:o.P&&o.P.1o==1n?o.P:6,1d:/2l|2f/.2p(o.1d)?o.1d:6,1j:o.1j?2q(o.1j)||0:6,1f:o.1f?o.1f:6};3(\'.\'+o.z,7).1I(9);7.1H=u;7.C={z:o.z,11:o.11?u:6,1G:1F,O:o.O?1B(o.O):6,14:o.G?o.G:6,v:o.v?o.v:6,1e:u,J:o.J?u:6,R:o.R?o.R:n,Q:o.Q?o.Q:n,1g:o.1g?u:6,9:9}})}}};3.2w.1i({2s:3.4.1A,1S:3.4.1L,2r:3.4.1M});3.2u=3.4.1p;',62,162,'|||jQuery|iSort|if|false|this|get|dragCfg||||helper||iDrag|dropCfg|||dragged|function||var|null||id|el||||true|fx|shs|||accept|length|cur|sortCfg|return|attr|each|helperclass|collected|cs|ghosting|pos|style|display|iEL|opacity|onStop|containment|handle|iUtil|inFrontOf|margins|fnc|else|ser|ts|for|onChange|revert|onStart|0px|hpc|iDrop|onDrag|changed|append|activeclass|none|hash|hoverclass|axis|so|cursorAt|floats|hb|extend|snapDistance|block|oC|tolerance|Function|constructor|serialize|os|wb|size|overzone|DraggableDestroy|ny|in|after|marginBottom|marginTop|build|parseFloat|marginRight|body|px|3000|zindex|isSortable|Draggable|onOut|sortable|addItem|destroy|nbsp|onHover|div|marginLeft|sortHelper|SortableAddItem|start|className|width|zones|getPosition|getSize|fadeIn|getMargins|css|apply|check|empty|position|initialPosition|height|cloneNode|removeClass|oP|html|DroppableDestroy|addClass|checkhover|horizontally|is|childNodes|document|Droppable|intersect|vertically|onchange|onout|onhover|test|parseInt|SortableDestroy|Sortable|nx|SortSerialize|break|fn|before|getPositionLite|measure|getSizeLite|parentNode'.split('|'),0,{}))

/*********************** Nested Sortables *****************************/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('2.6={28:9(e,o){5(e.L){2.6.1R(e);8 2.6.1K(e)}r{8 2.6.1D(e,o)}},1D:2.p.2b,1K:9(e){5(!2.v.A){8}5(!(e.1q.1r.1k()>0)){8}5(!e.3.Z){2.p.2n(e);e.3.Z=C}7 a=2.6.1A(e);7 b=2.6.1v(e,a);7 c=(!a)?2.6.24(e):n;7 d=n;5(a){5(e.3.1m===a&&e.3.1W===b){d=C}}r 5(e.3.1m===a&&e.3.1V===c){d=C}e.3.1m=a;e.3.1W=b;e.3.1V=c;5(d){8}5(a!==N){5(b){2.6.1U(e,a)}r{2.6.1Q(e,a)}}r 5(c){2.6.1P(e)}},1R:9(e){5(!e.3.16){8 n}7 a=e.3.15;7 b=e.3.14;7 c=2.v.A.B.2o;7 d=2.1i.1L();5((c.y-d.M)-d.t>-a){1H.1F(0,b)}5(c.y-d.t<a){1H.1F(0,-b)}},18:9(a){2.6.1C(a);8 2.6.1B(a)},1B:2.p.18,1C:9(a){5(2.6.S&&2.6.D){2.6.D.1y(2.6.S);2.6.D=N;2.6.S=""}5(2.1d.1w.L){2.1d.1w.3.Z=n}},X:9(s){5(2(\'#\'+s).q(0).L){8 2.6.27(s)}r{8 2.6.29(s)}},29:2.p.X,27:9(s){7 i;7 h=\'\';7 j=\'\';7 o={};7 e;7 k=9(f){7 g=[];1X=2(f).J(\'.\'+2.p.1b[s]);1X.1p(9(i){7 a=2.2s(m,\'1l\');5(a&&a.1S){a=a.1S(e.3.11)[0]}5(h.I>0){h+=\'&\'}h+=s+j+\'[\'+i+\'][1l]=\'+a;g[i]={1l:a};7 b=2(m).J(e.3.G+"."+e.3.W.V(" ").T(".")).q(0);7 c=j;j+=\'[\'+i+\'][J]\';7 d=k(b);5(d.I>0){g[i].J=d}j=c});8 g};5(s){5(2.p.1b[s]){e=2(\'#\'+s).q(0);o[s]=k(e)}r{1O(a 1N s){5(2.p.1b[s[a]]){e=2(\'#\'+s[a]).q(0);o[s[a]]=k(e)}}}}r{1O(i 1N 2.p.1b){e=2(\'#\'+i).q(0);o[i]=k(e)}}8{2p:h,o:o}},1A:9(e){7 d=0;7 f=2.1M(e.1q.1r,9(i){7 a=(i.z.y<2.v.A.B.1j)&&(i.z.y>d);5(!a){8 n}7 b;5(e.3.Q){b=(i.z.x+i.z.13+e.3.P>2.v.A.B.12+2.v.A.B.1h.13)}r{b=(i.z.x-e.3.P<2.v.A.B.12)}5(!b){8 n}7 c=2.6.1g(e,i);5(c){8 n}d=i.z.y;8 C});5(f.I>0){8 f[(f.I-1)]}r{8 N}},24:9(e){7 c;7 d=2.1M(e.1q.1r,9(i){7 a=(c===1J||i.z.y<c);5(!a){8 n}7 b=2.6.1g(e,i);5(b){8 n}c=i.z.y;8 C});5(d.I>0){d=d[(d.I-1)];8 d.z.y<2.v.A.B.1j+2.v.A.B.1h.2m&&d.z.y>2.v.A.B.1j}r{8 n}},1g:9(e,a){7 b=2.v.A;5(!b){8 n}5(a==b){8 C}5(2(a).2l("."+e.1I.1f.V(" ").T(".")).1G(9(){8 m==b}).I!==0){8 C}r{8 n}},1v:9(e,a){5(!a){8 n}5(e.3.O&&2(a).1G("."+e.3.O).q(0)===a){8 n}5(e.3.Q){8 a.z.x+a.z.13-(e.3.H-e.3.P)>2.v.A.B.12+2.v.A.B.1h.13}r{8 a.z.x+(e.3.H-e.3.P)<2.v.A.B.12}},1U:9(e,a){7 b=2(a).J(e.3.G+"."+e.3.W.V(" ").T("."));7 c=2.p.U;1E=c.q(0).2k;1E.2j=\'2i\';5(!b.1k()){7 d="<"+e.3.G+" 2h=\'"+e.3.W+"\'></"+e.3.G+">";b=2(a).2g(d).J(e.3.G).1z(e.3.1e)}2.6.17(e,b);2.6.Y(e);b.1x(c.q(0));2.6.1a(e)},1Q:9(e,a){2.6.17(e,2(a).1t());2.6.Y(e);2(a).2f(2.p.U.q(0));2.6.1a(e)},1P:9(e){2.6.17(e,e);2.6.Y(e);2(e).1x(2.p.U.q(0));2.6.1a(e)},Y:9(e){7 a=2.p.U.1t(e.3.G+"."+e.3.W.V(" ").T("."));7 b=a.J("."+e.1I.1f.V(" ").T(".")+":2e").1k();5(b===0&&a.q(0)!==e){a.2d()}},1a:9(e){7 a=2.p.U.1t();5(a.q(0)!==e){a.2c()}e.3.Z=n},17:9(e,a){7 b=2(a);5((e.3.K)&&(!2.6.D||b.q(0)!=2.6.D.q(0))){5(2.6.D){2.6.D.1y(e.3.K)}5(b.q(0)!=e){2.6.D=b;b.2E(e.3.K);2.6.S=e.3.K}r{2.6.D=N;2.6.S=""}}},2a:9(){8 m.1p(9(){5(m.L){m.3=N;m.L=N;2(m).2D()}})},26:9(a){5(a.1f&&2.1i&&2.v&&2.1d&&2.p){m.1p(9(){m.L=C;m.3={O:a.O?a.O:n,Q:a.Q?C:n,H:25(a.H,10)||2C,K:a.K?a.K:"",1u:a.1u?a.1u:n,16:a.16!==1J?a.16==C:C,15:a.15?a.15:20,14:a.14?a.14:20,11:a.11?a.11:/[^\\-]*$/};m.3.P=25(m.3.H*0.4,10);m.3.G=m.2B;m.3.W=m.2A;m.3.1e=(m.3.Q)?{"1c-21":0,"1c-1Z":m.3.H+\'1Y\'}:{"1c-21":m.3.H+\'1Y\',"1c-1Z":0};2(m.3.G,m).1z(m.3.1e)});2.p.2b=2.6.28;2.p.18=2.6.18;2.p.X=2.6.X}8 m.2z(a)}};2.2y.2x({2w:2.6.26,2v:2.6.2a});2.1i.1L=9(e){7 t,l,w,h,R,M;5(e&&e.2u.2t()!=\'F\'){t=e.19;l=e.1o;w=e.1n;h=e.1s;R=0;M=0}r{5(u.E&&u.E.19){t=u.E.19;l=u.E.1o;w=u.E.1n;h=u.E.1s}r 5(u.F){t=u.F.19;l=u.F.1o;w=u.F.1n;h=u.F.1s}R=1T.2r||u.E.23||u.F.23||0;M=1T.2q||u.E.22||u.F.22||0}8{t:t,l:l,w:w,h:h,R:R,M:M}};',62,165,'||jQuery|nestedSortCfg||if|iNestedSortable|var|return|function|||||||||||||this|false||iSort|get|else|||document|iDrag||||pos|dragged|dragCfg|true|currentNesting|documentElement|body|nestingTag|nestingPxSpace|length|children|currentNestingClass|isNestedSortable|ih|null|noNestingClass|snapTolerance|rightToLeft|iw|latestNestingClass|join|helper|split|nestingTagClass|serialize|beforeHelperRemove|remeasured||serializeRegExp|nx|wb|scrollSpeed|scrollSensitivity|autoScroll|updateCurrentNestingClass|check|scrollTop|afterHelperInsert|collected|padding|iDrop|styleToAttach|accept|isBeingDragged|oC|iUtil|ny|size|id|lastPrecedingItem|scrollWidth|scrollLeft|each|dropCfg|el|scrollHeight|parent|nestingLimit|shouldNestItem|overzone|prepend|removeClass|css|findPrecedingItem|oldCheck|newCheck|oldCheckHover|styleHelper|scrollBy|filter|window|sortCfg|undefined|newCheckHover|getScroll|grep|in|for|insertOnTop|appendItem|scroll|match|self|nestItem|lastTouchingFirst|lastShouldNest|thisChildren|px|right||left|clientHeight|clientWidth|isTouchingFirstItem|parseInt|build|newSerialize|checkHover|oldSerialize|destroy|checkhover|show|hide|visible|after|append|class|auto|width|style|parents|hb|measure|currentPointer|hash|innerHeight|innerWidth|attr|toLowerCase|nodeName|NestedSortableDestroy|NestedSortable|extend|fn|Sortable|className|tagName|30|SortableDestroy|addClass'.split('|'),0,{}))

/***************************** Menus *********************************/
var arrowimages={down:['menu_arrow_down', DOMAIN+'images/arrow-down.gif', 10], right:['menu_arrow_right', DOMAIN+'images/arrow-right.gif']}
var jquerycssmenu={
	fadesettings: {overduration: 150, outduration: 100},	buildmenu:function(menuid, arrowsvar){
		jQuery(document).ready(function($){
			var $mainmenu=$(menuid+">ul");
			var $headers=$mainmenu.find("ul").parent();
			$headers.each(function(i){
				var $curobj=$(this);
				var $subul=$(this).find('ul:eq(0)');
				this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
				this.istopheader=$curobj.parents("ul").length==1? true : false;
				$subul.css({top:this.istopheader? this._dimensions.h+"px" : 0});
				$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: arrowsvar.down[2]} : {}).append(
					'<!-- <img src="'+ (this.istopheader? arrowsvar.down[1] : arrowsvar.right[1])
					+'" class="' + (this.istopheader? arrowsvar.down[0] : arrowsvar.right[0])
					+ '" style="border:0;" align="top" /> -->'
				);
				$curobj.hover(
					function(e){
						var $targetul=$(this).children("ul:eq(0)");
						this._offsets={left:$(this).offset().left, top:$(this).offset().top}
						var menuleft=this.istopheader? 0 : this._dimensions.w;
						menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft;
						$targetul.css({left:menuleft+"px"}).fadeIn(jquerycssmenu.fadesettings.overduration);
					},
					function(e){
						$(this).children("ul:eq(0)").fadeOut(jquerycssmenu.fadesettings.outduration);
					}
				);
			});
			$mainmenu.find("ul").css({display:'none', visibility:'visible'});
		}) //end document.ready
	}
}
//build menu with class="menu_javascript" on page:
jquerycssmenu.buildmenu(".menu_javascript", arrowimages);

/**************************** Calendar *******************************/
(function($) {var today = new Date();var months = 'January,February,March,April,May,June,July,August,September,October,November,December'.split(',');var monthlengths = '31,28,31,30,31,30,31,31,30,31,30,31'.split(','); var dateRegEx = /^\d{1,2}\/\d{1,2}\/\d{2}|\d{4}$/;var yearRegEx = /^\d{4,4}$/;   $.fn.simpleDatepicker = function(options) {var opts = jQuery.extend({}, jQuery.fn.simpleDatepicker.defaults, options);setupYearRange();function setupYearRange () {var startyear, endyear; if (opts.startdate.constructor == Date) {startyear = opts.startdate.getFullYear();} else if (opts.startdate) {if (yearRegEx.test(opts.startdate)) {startyear = opts.startdate;} else if (dateRegEx.test(opts.startdate)) {opts.startdate = new Date(opts.startdate);startyear = opts.startdate.getFullYear();} else {startyear = today.getFullYear();}} else {startyear = today.getFullYear();}opts.startyear = startyear;if (opts.enddate.constructor == Date) {endyear = opts.enddate.getFullYear();} else if (opts.enddate) {if (yearRegEx.test(opts.enddate)) {endyear = opts.enddate;} else if (dateRegEx.test(opts.enddate)) {opts.enddate = new Date(opts.enddate);endyear = opts.enddate.getFullYear();} else {endyear = today.getFullYear();}} else {endyear = today.getFullYear();}opts.endyear = endyear;}function newDatepickerHTML () {var years = [];for (var i = 0; i <= opts.endyear - opts.startyear; i ++) years[i] = opts.startyear + i;var table = jQuery('<table class="datepicker" cellpadding="0" cellspacing="0"></table>');table.append('<thead></thead>');table.append('<tfoot></tfoot>');table.append('<tbody></tbody>');var monthselect = '<select name="month">';for (var i in months) monthselect += '<option value="'+i+'">'+months[i]+'</option>';monthselect += '</select>';var yearselect = '<select name="year">';for (var i in years) yearselect += '<option>'+years[i]+'</option>';yearselect += '</select>';jQuery("thead",table).append('<tr class="controls"><th colspan="7"><span class="prevMonth">&laquo;</span>&nbsp;'+monthselect+yearselect+'&nbsp;<span class="nextMonth">&raquo;</span></th></tr>');jQuery("thead",table).append('<tr class="days"><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>');jQuery("tfoot",table).append('<tr><td colspan="2"><span class="today">today</span></td><td colspan="3">&nbsp;</td><td colspan="2"><span class="close">close</span></td></tr>');for (var i = 0; i < 6; i++) jQuery("tbody",table).append('<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>');return table;}function findPosition (obj) {var curleft = curtop = 0;if (obj.offsetParent) {do {curleft += obj.offsetLeft;curtop += obj.offsetTop;} while (obj = obj.offsetParent);return [curleft,curtop];} else {return false;}}function loadMonth (e, el, datepicker, chosendate) {var mo = jQuery("select[name=month]", datepicker).get(0).selectedIndex;var yr = jQuery("select[name=year]", datepicker).get(0).selectedIndex;var yrs = jQuery("select[name=year] option", datepicker).get().length;if (e && jQuery(e.target).hasClass('prevMonth')) {if (0 == mo && yr) {yr -= 1; mo = 11;jQuery("select[name=month]", datepicker).get(0).selectedIndex = 11;jQuery("select[name=year]", datepicker).get(0).selectedIndex = yr;} else {mo -= 1;jQuery("select[name=month]", datepicker).get(0).selectedIndex = mo;}} else if (e && jQuery(e.target).hasClass('nextMonth')) {if (11 == mo && yr + 1 < yrs) {yr += 1; mo = 0;jQuery("select[name=month]", datepicker).get(0).selectedIndex = 0;jQuery("select[name=year]", datepicker).get(0).selectedIndex = yr;} else {mo += 1;jQuery("select[name=month]", datepicker).get(0).selectedIndex = mo;}}if (0 == mo && !yr) jQuery("span.prevMonth", datepicker).hide();else jQuery("span.prevMonth", datepicker).show();if (yr + 1 == yrs && 11 == mo) jQuery("span.nextMonth", datepicker).hide();else jQuery("span.nextMonth", datepicker).show();var cells = jQuery("tbody td", datepicker).unbind().empty().removeClass('date');var m = jQuery("select[name=month]", datepicker).val();var y = jQuery("select[name=year]", datepicker).val();var d = new Date(y, m, 1);var startindex = d.getDay();var numdays = monthlengths[m];if (1 == m && ((y%4 == 0 && y%100 != 0) || y%400 == 0)) numdays = 29;if (opts.startdate.constructor == Date) {var startMonth = opts.startdate.getMonth();var startDate = opts.startdate.getDate();}if (opts.enddate.constructor == Date) {var endMonth = opts.enddate.getMonth();var endDate = opts.enddate.getDate();}for (var i = 0; i < numdays; i++) {var cell = jQuery(cells.get(i+startindex)).removeClass('chosen');if ((yr || ((!startDate && !startMonth) || ((i+1 >= startDate && mo == startMonth) || mo > startMonth))) &&(yr + 1 < yrs || ((!endDate && !endMonth) || ((i+1 <= endDate && mo == endMonth) || mo < endMonth)))) {cell.text(i+1).addClass('date').hover(function () { jQuery(this).addClass('over'); },function () { jQuery(this).removeClass('over'); }).click(function () {var chosenDateObj = new Date(jQuery("select[name=year]", datepicker).val(), jQuery("select[name=month]", datepicker).val(), jQuery(this).text());closeIt(el, datepicker, chosenDateObj);});if (i+1 == chosendate.getDate() && m == chosendate.getMonth() && y == chosendate.getFullYear()) cell.addClass('chosen');}}}function closeIt (el, datepicker, dateObj) {if (dateObj && dateObj.constructor == Date)el.val(jQuery.fn.simpleDatepicker.formatOutput(dateObj));datepicker.remove();datepicker = null;jQuery.data(el.get(0), "simpleDatepicker", { hasDatepicker : false });}function createIt(t,b) {$('table.datepicker').remove();$('input.calendar').each(function(e) { jQuery.data(this, "simpleDatepicker", { hasDatepicker : false }); });var $this = jQuery(t);if (false == jQuery.data($this.get(0), "simpleDatepicker").hasDatepicker) {jQuery.data($this.get(0), "simpleDatepicker", { hasDatepicker : true });var initialDate = $this.val();if (initialDate && dateRegEx.test(initialDate)) {var chosendate = new Date(initialDate);} else if (opts.chosendate.constructor == Date) {var chosendate = opts.chosendate;} else if (opts.chosendate) {var chosendate = new Date(opts.chosendate);} else {var chosendate = today;}datepicker = newDatepickerHTML();jQuery("body").prepend(datepicker);if(b == 1) var elPos = findPosition($this.next('img.datepicker_button').get(0));else var elPos = findPosition($this.get(0));var x = (parseInt(opts.x) ? parseInt(opts.x) : 0) + elPos[0];var y = (parseInt(opts.y) ? parseInt(opts.y) : 0) + elPos[1];jQuery(datepicker).css({ position: 'absolute', left: x, top: y });jQuery("span", datepicker).css("cursor","pointer");jQuery("select", datepicker).bind('change', function () { loadMonth (null, $this, datepicker, chosendate); });jQuery("span.prevMonth", datepicker).click(function (e) { loadMonth (e, $this, datepicker, chosendate); });jQuery("span.nextMonth", datepicker).click(function (e) { loadMonth (e, $this, datepicker, chosendate); });jQuery("span.today", datepicker).click(function () { closeIt($this, datepicker, new Date()); });jQuery("span.close", datepicker).click(function () { closeIt($this, datepicker); });jQuery("select[name=month]", datepicker).get(0).selectedIndex = chosendate.getMonth();jQuery("select[name=year]", datepicker).get(0).selectedIndex = Math.max(0, chosendate.getFullYear() - opts.startyear);loadMonth(null, $this, datepicker, chosendate);}} return this.each(function() {var id = $(this).attr('id');if(!id) {id = "datepicker_"+Math.floor(Math.random() * 99999);$(this).attr('id',id);}if ( jQuery(this).is('input') && 'text' == jQuery(this).attr('type')) {var datepicker;jQuery.data(jQuery(this).get(0), "simpleDatepicker", { hasDatepicker : false });jQuery(this).click(function (ev) { createIt(this); });if(opts.button == true && opts.button_url) {var x = 0;$(this).after("<img src='"+opts.button_url+"' alt='...' class='datepicker_button' />");$(this).nextAll("img.datepicker_button").each(function() {if(x == 0) $(this).click(function() { createIt($('#'+id),1); });x++;});}}   });    };jQuery.fn.simpleDatepicker.formatOutput = function (dateObj) {return (dateObj.getMonth() + 1) + "/" + dateObj.getDate() + "/" + dateObj.getFullYear();};jQuery.fn.simpleDatepicker.defaults = {chosendate : today,startdate : today.getFullYear(),enddate : today.getFullYear() + 1,x : 18,y : 18,button : true,button_url : DOMAIN+"images/calendar.png"};})(jQuery);

/**************************** Tooltips *******************************/
;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}update();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}helper.parent.css({left:left,right:right,top:top});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)helper.parent.unfixPNG();}})(jQuery);

/**************************** Sortable *******************************/
;(function($){var _remove=$.fn.remove;$.fn.remove=function(){$("*",this).add(this).triggerHandler("remove");return _remove.apply(this,arguments);};function isVisible(element){function checkStyles(element){var style=element.style;return(style.display!='none'&&style.visibility!='hidden');}
var visible=checkStyles(element);(visible&&$.each($.dir(element,'parentNode'),function(){return(visible=checkStyles(this));}));return visible;}
$.extend($.expr[':'],{data:function(a,i,m){return $.data(a,m[3]);},tabbable:function(a,i,m){var nodeName=a.nodeName.toLowerCase();return(a.tabIndex>=0&&(('a'==nodeName&&a.href)||(/input|select|textarea|button/.test(nodeName)&&'hidden'!=a.type&&!a.disabled))&&isVisible(a));}});$.keyCode={BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38};function getter(namespace,plugin,method,args){function getMethods(type){var methods=$[namespace][plugin][type]||[];return(typeof methods=='string'?methods.split(/,?\s+/):methods);}
var methods=getMethods('getter');if(args.length==1&&typeof args[0]=='string'){methods=methods.concat(getMethods('getterSetter'));}
return($.inArray(method,methods)!=-1);}
$.widget=function(name,prototype){var namespace=name.split(".")[0];name=name.split(".")[1];$.fn[name]=function(options){var isMethodCall=(typeof options=='string'),args=Array.prototype.slice.call(arguments,1);if(isMethodCall&&options.substring(0,1)=='_'){return this;}
if(isMethodCall&&getter(namespace,name,options,args)){var instance=$.data(this[0],name);return(instance?instance[options].apply(instance,args):undefined);}
return this.each(function(){var instance=$.data(this,name);(!instance&&!isMethodCall&&$.data(this,name,new $[namespace][name](this,options)));(instance&&isMethodCall&&$.isFunction(instance[options])&&instance[options].apply(instance,args));});};$[namespace][name]=function(element,options){var self=this;this.widgetName=name;this.widgetEventPrefix=$[namespace][name].eventPrefix||name;this.widgetBaseClass=namespace+'-'+name;this.options=$.extend({},$.widget.defaults,$[namespace][name].defaults,$.metadata&&$.metadata.get(element)[name],options);this.element=$(element).bind('setData.'+name,function(e,key,value){return self._setData(key,value);}).bind('getData.'+name,function(e,key){return self._getData(key);}).bind('remove',function(){return self.destroy();});this._init();};$[namespace][name].prototype=$.extend({},$.widget.prototype,prototype);$[namespace][name].getterSetter='option';};$.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName);},option:function(key,value){var options=key,self=this;if(typeof key=="string"){if(value===undefined){return this._getData(key);}
options={};options[key]=value;}
$.each(options,function(key,value){self._setData(key,value);});},_getData:function(key){return this.options[key];},_setData:function(key,value){this.options[key]=value;if(key=='disabled'){this.element[value?'addClass':'removeClass'](this.widgetBaseClass+'-disabled');}},enable:function(){this._setData('disabled',false);},disable:function(){this._setData('disabled',true);},_trigger:function(type,e,data){var eventName=(type==this.widgetEventPrefix?type:this.widgetEventPrefix+type);e=e||$.event.fix({type:eventName,target:this.element[0]});return this.element.triggerHandler(eventName,[e,data],this.options[type]);}};$.widget.defaults={disabled:false};$.ui={plugin:{add:function(module,option,set){var proto=$.ui[module].prototype;for(var i in set){proto.plugins[i]=proto.plugins[i]||[];proto.plugins[i].push([option,set[i]]);}},call:function(instance,name,args){var set=instance.plugins[name];if(!set){return;}
for(var i=0;i<set.length;i++){if(instance.options[set[i][0]]){set[i][1].apply(instance.element,args);}}}},cssCache:{},css:function(name){if($.ui.cssCache[name]){return $.ui.cssCache[name];}
var tmp=$('<div class="ui-gen">').addClass(name).css({position:'absolute',top:'-5000px',left:'-5000px',display:'block'}).appendTo('body');$.ui.cssCache[name]=!!((!(/auto|default/).test(tmp.css('cursor'))||(/^[1-9]/).test(tmp.css('height'))||(/^[1-9]/).test(tmp.css('width'))||!(/none/).test(tmp.css('backgroundImage'))||!(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor'))));try{$('body').get(0).removeChild(tmp.get(0));}catch(e){}
return $.ui.cssCache[name];},disableSelection:function(el){return $(el).attr('unselectable','on').css('MozUserSelect','none').bind('selectstart.ui',function(){return false;});},enableSelection:function(el){return $(el).attr('unselectable','off').css('MozUserSelect','').unbind('selectstart.ui');},hasScroll:function(e,a){if($(e).css('overflow')=='hidden'){return false;}
var scroll=(a&&a=='left')?'scrollLeft':'scrollTop',has=false;if(e[scroll]>0){return true;}
e[scroll]=1;has=(e[scroll]>0);e[scroll]=0;return has;}};$.ui.mouse={_mouseInit:function(){var self=this;this.element.bind('mousedown.'+this.widgetName,function(e){return self._mouseDown(e);});if($.browser.msie){this._mouseUnselectable=this.element.attr('unselectable');this.element.attr('unselectable','on');}
this.started=false;},_mouseDestroy:function(){this.element.unbind('.'+this.widgetName);($.browser.msie&&this.element.attr('unselectable',this._mouseUnselectable));},_mouseDown:function(e){(this._mouseStarted&&this._mouseUp(e));this._mouseDownEvent=e;var self=this,btnIsLeft=(e.which==1),elIsCancel=(typeof this.options.cancel=="string"?$(e.target).parents().add(e.target).filter(this.options.cancel).length:false);if(!btnIsLeft||elIsCancel||!this._mouseCapture(e)){return true;}
this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){self.mouseDelayMet=true;},this.options.delay);}
if(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)){this._mouseStarted=(this._mouseStart(e)!==false);if(!this._mouseStarted){e.preventDefault();return true;}}
this._mouseMoveDelegate=function(e){return self._mouseMove(e);};this._mouseUpDelegate=function(e){return self._mouseUp(e);};$(document).bind('mousemove.'+this.widgetName,this._mouseMoveDelegate).bind('mouseup.'+this.widgetName,this._mouseUpDelegate);return false;},_mouseMove:function(e){if($.browser.msie&&!e.button){return this._mouseUp(e);}
if(this._mouseStarted){this._mouseDrag(e);return false;}
if(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,e)!==false);(this._mouseStarted?this._mouseDrag(e):this._mouseUp(e));}
return!this._mouseStarted;},_mouseUp:function(e){$(document).unbind('mousemove.'+this.widgetName,this._mouseMoveDelegate).unbind('mouseup.'+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._mouseStop(e);}
return false;},_mouseDistanceMet:function(e){return(Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance);},_mouseDelayMet:function(e){return this.mouseDelayMet;},_mouseStart:function(e){},_mouseDrag:function(e){},_mouseStop:function(e){},_mouseCapture:function(e){return true;}};$.ui.mouse.defaults={cancel:null,distance:1,delay:0};})(jQuery);(function($){$.widget("ui.draggable",$.extend({},$.ui.mouse,{getHandle:function(e){var handle=!this.options.handle||!$(this.options.handle,this.element).length?true:false;$(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==e.target)handle=true;});return handle;},createHelper:function(){var o=this.options;var helper=$.isFunction(o.helper)?$(o.helper.apply(this.element[0],[e])):(o.helper=='clone'?this.element.clone():this.element);if(!helper.parents('body').length)
helper.appendTo((o.appendTo=='parent'?this.element[0].parentNode:o.appendTo));if(helper[0]!=this.element[0]&&!(/(fixed|absolute)/).test(helper.css("position")))
helper.css("position","absolute");return helper;},_init:function(){if(this.options.helper=='original'&&!(/^(?:r|a|f)/).test(this.element.css("position")))
this.element[0].style.position='relative';(this.options.cssNamespace&&this.element.addClass(this.options.cssNamespace+"-draggable"));(this.options.disabled&&this.element.addClass('ui-draggable-disabled'));this._mouseInit();},_mouseCapture:function(e){var o=this.options;if(this.helper||o.disabled||$(e.target).is('.ui-resizable-handle'))
return false;this.handle=this.getHandle(e);if(!this.handle)
return false;return true;},_mouseStart:function(e){var o=this.options;this.helper=this.createHelper();if($.ui.ddmanager)
$.ui.ddmanager.current=this;this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0)};this.cssPosition=this.helper.css("position");this.offset=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.offset.click={left:e.pageX-this.offset.left,top:e.pageY-this.offset.top};this.cacheScrollParents();this.offsetParent=this.helper.offsetParent();var po=this.offsetParent.offset();if(this.offsetParent[0]==document.body&&$.browser.mozilla)po={top:0,left:0};this.offset.parent={top:po.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:po.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};if(this.cssPosition=="relative"){var p=this.element.position();this.offset.relative={top:p.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollTopParent.scrollTop(),left:p.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollLeftParent.scrollLeft()};}else{this.offset.relative={top:0,left:0};}
this.originalPosition=this._generatePosition(e);this.cacheHelperProportions();if(o.cursorAt)
this.adjustOffsetFromHelper(o.cursorAt);$.extend(this,{PAGEY_INCLUDES_SCROLL:(this.cssPosition=="absolute"&&(!this.scrollTopParent[0].tagName||(/(html|body)/i).test(this.scrollTopParent[0].tagName))),PAGEX_INCLUDES_SCROLL:(this.cssPosition=="absolute"&&(!this.scrollLeftParent[0].tagName||(/(html|body)/i).test(this.scrollLeftParent[0].tagName))),OFFSET_PARENT_NOT_SCROLL_PARENT_Y:this.scrollTopParent[0]!=this.offsetParent[0]&&!(this.scrollTopParent[0]==document&&(/(body|html)/i).test(this.offsetParent[0].tagName)),OFFSET_PARENT_NOT_SCROLL_PARENT_X:this.scrollLeftParent[0]!=this.offsetParent[0]&&!(this.scrollLeftParent[0]==document&&(/(body|html)/i).test(this.offsetParent[0].tagName))});if(o.containment)
this.setContainment();this._propagate("start",e);this.cacheHelperProportions();if($.ui.ddmanager&&!o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this,e);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(e);return true;},cacheScrollParents:function(){this.scrollTopParent=function(el){do{if(/auto|scroll/.test(el.css('overflow'))||(/auto|scroll/).test(el.css('overflow-y')))return el;el=el.parent();}while(el[0].parentNode);return $(document);}(this.helper);this.scrollLeftParent=function(el){do{if(/auto|scroll/.test(el.css('overflow'))||(/auto|scroll/).test(el.css('overflow-x')))return el;el=el.parent();}while(el[0].parentNode);return $(document);}(this.helper);},adjustOffsetFromHelper:function(obj){if(obj.left!=undefined)this.offset.click.left=obj.left+this.margins.left;if(obj.right!=undefined)this.offset.click.left=this.helperProportions.width-obj.right+this.margins.left;if(obj.top!=undefined)this.offset.click.top=obj.top+this.margins.top;if(obj.bottom!=undefined)this.offset.click.top=this.helperProportions.height-obj.bottom+this.margins.top;},cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};},setContainment:function(){var o=this.options;if(o.containment=='parent')o.containment=this.helper[0].parentNode;if(o.containment=='document'||o.containment=='window')this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,$(o.containment=='document'?document:window).width()-this.offset.relative.left-this.offset.parent.left-this.helperProportions.width-this.margins.left-(parseInt(this.element.css("marginRight"),10)||0),($(o.containment=='document'?document:window).height()||document.body.parentNode.scrollHeight)-this.offset.relative.top-this.offset.parent.top-this.helperProportions.height-this.margins.top-(parseInt(this.element.css("marginBottom"),10)||0)];if(!(/^(document|window|parent)$/).test(o.containment)){var ce=$(o.containment)[0];var co=$(o.containment).offset();var over=($(ce).css("overflow")!='hidden');this.containment=[co.left+(parseInt($(ce).css("borderLeftWidth"),10)||0)-this.offset.relative.left-this.offset.parent.left,co.top+(parseInt($(ce).css("borderTopWidth"),10)||0)-this.offset.relative.top-this.offset.parent.top,co.left+(over?Math.max(ce.scrollWidth,ce.offsetWidth):ce.offsetWidth)-(parseInt($(ce).css("borderLeftWidth"),10)||0)-this.offset.relative.left-this.offset.parent.left-this.helperProportions.width-this.margins.left-(parseInt(this.element.css("marginRight"),10)||0),co.top+(over?Math.max(ce.scrollHeight,ce.offsetHeight):ce.offsetHeight)-(parseInt($(ce).css("borderTopWidth"),10)||0)-this.offset.relative.top-this.offset.parent.top-this.helperProportions.height-this.margins.top-(parseInt(this.element.css("marginBottom"),10)||0)];}},_convertPositionTo:function(d,pos){if(!pos)pos=this.position;var mod=d=="absolute"?1:-1;return{top:(pos.top
+this.offset.relative.top*mod
+this.offset.parent.top*mod
-(this.cssPosition=="fixed"||this.PAGEY_INCLUDES_SCROLL||this.OFFSET_PARENT_NOT_SCROLL_PARENT_Y?0:this.scrollTopParent.scrollTop())*mod
+(this.cssPosition=="fixed"?$(document).scrollTop():0)*mod
+this.margins.top*mod),left:(pos.left
+this.offset.relative.left*mod
+this.offset.parent.left*mod
-(this.cssPosition=="fixed"||this.PAGEX_INCLUDES_SCROLL||this.OFFSET_PARENT_NOT_SCROLL_PARENT_X?0:this.scrollLeftParent.scrollLeft())*mod
+(this.cssPosition=="fixed"?$(document).scrollLeft():0)*mod
+this.margins.left*mod)};},_generatePosition:function(e){var o=this.options;var position={top:(e.pageY
-this.offset.click.top
-this.offset.relative.top
-this.offset.parent.top
+(this.cssPosition=="fixed"||this.PAGEY_INCLUDES_SCROLL||this.OFFSET_PARENT_NOT_SCROLL_PARENT_Y?0:this.scrollTopParent.scrollTop())
-(this.cssPosition=="fixed"?$(document).scrollTop():0)),left:(e.pageX
-this.offset.click.left
-this.offset.relative.left
-this.offset.parent.left
+(this.cssPosition=="fixed"||this.PAGEX_INCLUDES_SCROLL||this.OFFSET_PARENT_NOT_SCROLL_PARENT_X?0:this.scrollLeftParent.scrollLeft())
-(this.cssPosition=="fixed"?$(document).scrollLeft():0))};if(!this.originalPosition)return position;if(this.containment){if(position.left<this.containment[0])position.left=this.containment[0];if(position.top<this.containment[1])position.top=this.containment[1];if(position.left>this.containment[2])position.left=this.containment[2];if(position.top>this.containment[3])position.top=this.containment[3];}
if(o.grid){var top=this.originalPosition.top+Math.round((position.top-this.originalPosition.top)/o.grid[1])*o.grid[1];position.top=this.containment?(!(top<this.containment[1]||top>this.containment[3])?top:(!(top<this.containment[1])?top-o.grid[1]:top+o.grid[1])):top;var left=this.originalPosition.left+Math.round((position.left-this.originalPosition.left)/o.grid[0])*o.grid[0];position.left=this.containment?(!(left<this.containment[0]||left>this.containment[2])?left:(!(left<this.containment[0])?left-o.grid[0]:left+o.grid[0])):left;}
return position;},_mouseDrag:function(e){this.position=this._generatePosition(e);this.positionAbs=this._convertPositionTo("absolute");this.position=this._propagate("drag",e)||this.position;if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+'px';if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+'px';if($.ui.ddmanager)$.ui.ddmanager.drag(this,e);return false;},_mouseStop:function(e){var dropped=false;if($.ui.ddmanager&&!this.options.dropBehaviour)
var dropped=$.ui.ddmanager.drop(this,e);if((this.options.revert=="invalid"&&!dropped)||(this.options.revert=="valid"&&dropped)||this.options.revert===true||($.isFunction(this.options.revert)&&this.options.revert.call(this.element,dropped))){var self=this;$(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10)||500,function(){self._propagate("stop",e);self._clear();});}else{this._propagate("stop",e);this._clear();}
return false;},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.options.helper!='original'&&!this.cancelHelperRemoval)this.helper.remove();this.helper=null;this.cancelHelperRemoval=false;},plugins:{},uiHash:function(e){return{helper:this.helper,position:this.position,absolutePosition:this.positionAbs,options:this.options};},_propagate:function(n,e){$.ui.plugin.call(this,n,[e,this.uiHash()]);if(n=="drag")this.positionAbs=this._convertPositionTo("absolute");return this.element.triggerHandler(n=="drag"?n:"drag"+n,[e,this.uiHash()],this.options[n]);},destroy:function(){if(!this.element.data('draggable'))return;this.element.removeData("draggable").unbind(".draggable").removeClass('ui-draggable ui-draggable-dragging ui-draggable-disabled');this._mouseDestroy();}}));$.extend($.ui.draggable,{defaults:{appendTo:"parent",axis:false,cancel:":input",delay:0,distance:1,helper:"original",scope:"default",cssNamespace:"ui"}});$.ui.plugin.add("draggable","cursor",{start:function(e,ui){var t=$('body');if(t.css("cursor"))ui.options._cursor=t.css("cursor");t.css("cursor",ui.options.cursor);},stop:function(e,ui){if(ui.options._cursor)$('body').css("cursor",ui.options._cursor);}});$.ui.plugin.add("draggable","zIndex",{start:function(e,ui){var t=$(ui.helper);if(t.css("zIndex"))ui.options._zIndex=t.css("zIndex");t.css('zIndex',ui.options.zIndex);},stop:function(e,ui){if(ui.options._zIndex)$(ui.helper).css('zIndex',ui.options._zIndex);}});$.ui.plugin.add("draggable","opacity",{start:function(e,ui){var t=$(ui.helper);if(t.css("opacity"))ui.options._opacity=t.css("opacity");t.css('opacity',ui.options.opacity);},stop:function(e,ui){if(ui.options._opacity)$(ui.helper).css('opacity',ui.options._opacity);}});$.ui.plugin.add("draggable","iframeFix",{start:function(e,ui){$(ui.options.iframeFix===true?"iframe":ui.options.iframeFix).each(function(){$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css($(this).offset()).appendTo("body");});},stop:function(e,ui){$("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this);});}});$.ui.plugin.add("draggable","scroll",{start:function(e,ui){var o=ui.options;var i=$(this).data("draggable");o.scrollSensitivity=o.scrollSensitivity||20;o.scrollSpeed=o.scrollSpeed||20;i.overflowY=function(el){do{if(/auto|scroll/.test(el.css('overflow'))||(/auto|scroll/).test(el.css('overflow-y')))return el;el=el.parent();}while(el[0].parentNode);return $(document);}(this);i.overflowX=function(el){do{if(/auto|scroll/.test(el.css('overflow'))||(/auto|scroll/).test(el.css('overflow-x')))return el;el=el.parent();}while(el[0].parentNode);return $(document);}(this);if(i.overflowY[0]!=document&&i.overflowY[0].tagName!='HTML')i.overflowYOffset=i.overflowY.offset();if(i.overflowX[0]!=document&&i.overflowX[0].tagName!='HTML')i.overflowXOffset=i.overflowX.offset();},drag:function(e,ui){var o=ui.options,scrolled=false;var i=$(this).data("draggable");if(i.overflowY[0]!=document&&i.overflowY[0].tagName!='HTML'){if((i.overflowYOffset.top+i.overflowY[0].offsetHeight)-e.pageY<o.scrollSensitivity)
i.overflowY[0].scrollTop=scrolled=i.overflowY[0].scrollTop+o.scrollSpeed;if(e.pageY-i.overflowYOffset.top<o.scrollSensitivity)
i.overflowY[0].scrollTop=scrolled=i.overflowY[0].scrollTop-o.scrollSpeed;}else{if(e.pageY-$(document).scrollTop()<o.scrollSensitivity)
scrolled=$(document).scrollTop($(document).scrollTop()-o.scrollSpeed);if($(window).height()-(e.pageY-$(document).scrollTop())<o.scrollSensitivity)
scrolled=$(document).scrollTop($(document).scrollTop()+o.scrollSpeed);}
if(i.overflowX[0]!=document&&i.overflowX[0].tagName!='HTML'){if((i.overflowXOffset.left+i.overflowX[0].offsetWidth)-e.pageX<o.scrollSensitivity)
i.overflowX[0].scrollLeft=scrolled=i.overflowX[0].scrollLeft+o.scrollSpeed;if(e.pageX-i.overflowXOffset.left<o.scrollSensitivity)
i.overflowX[0].scrollLeft=scrolled=i.overflowX[0].scrollLeft-o.scrollSpeed;}else{if(e.pageX-$(document).scrollLeft()<o.scrollSensitivity)
scrolled=$(document).scrollLeft($(document).scrollLeft()-o.scrollSpeed);if($(window).width()-(e.pageX-$(document).scrollLeft())<o.scrollSensitivity)
scrolled=$(document).scrollLeft($(document).scrollLeft()+o.scrollSpeed);}
if(scrolled!==false)
$.ui.ddmanager.prepareOffsets(i,e);}});$.ui.plugin.add("draggable","snap",{start:function(e,ui){var inst=$(this).data("draggable");inst.snapElements=[];$(ui.options.snap.constructor!=String?(ui.options.snap.items||':data(draggable)'):ui.options.snap).each(function(){var $t=$(this);var $o=$t.offset();if(this!=inst.element[0])inst.snapElements.push({item:this,width:$t.outerWidth(),height:$t.outerHeight(),top:$o.top,left:$o.left});});},drag:function(e,ui){var inst=$(this).data("draggable");var d=ui.options.snapTolerance||20;var x1=ui.absolutePosition.left,x2=x1+inst.helperProportions.width,y1=ui.absolutePosition.top,y2=y1+inst.helperProportions.height;for(var i=inst.snapElements.length-1;i>=0;i--){var l=inst.snapElements[i].left,r=l+inst.snapElements[i].width,t=inst.snapElements[i].top,b=t+inst.snapElements[i].height;if(!((l-d<x1&&x1<r+d&&t-d<y1&&y1<b+d)||(l-d<x1&&x1<r+d&&t-d<y2&&y2<b+d)||(l-d<x2&&x2<r+d&&t-d<y1&&y1<b+d)||(l-d<x2&&x2<r+d&&t-d<y2&&y2<b+d))){if(inst.snapElements[i].snapping)(inst.options.snap.release&&inst.options.snap.release.call(inst.element,null,$.extend(inst.uiHash(),{snapItem:inst.snapElements[i].item})));inst.snapElements[i].snapping=false;continue;}
if(ui.options.snapMode!='inner'){var ts=Math.abs(t-y2)<=d;var bs=Math.abs(b-y1)<=d;var ls=Math.abs(l-x2)<=d;var rs=Math.abs(r-x1)<=d;if(ts)ui.position.top=inst._convertPositionTo("relative",{top:t-inst.helperProportions.height,left:0}).top;if(bs)ui.position.top=inst._convertPositionTo("relative",{top:b,left:0}).top;if(ls)ui.position.left=inst._convertPositionTo("relative",{top:0,left:l-inst.helperProportions.width}).left;if(rs)ui.position.left=inst._convertPositionTo("relative",{top:0,left:r}).left;}
var first=(ts||bs||ls||rs);if(ui.options.snapMode!='outer'){var ts=Math.abs(t-y1)<=d;var bs=Math.abs(b-y2)<=d;var ls=Math.abs(l-x1)<=d;var rs=Math.abs(r-x2)<=d;if(ts)ui.position.top=inst._convertPositionTo("relative",{top:t,left:0}).top;if(bs)ui.position.top=inst._convertPositionTo("relative",{top:b-inst.helperProportions.height,left:0}).top;if(ls)ui.position.left=inst._convertPositionTo("relative",{top:0,left:l}).left;if(rs)ui.position.left=inst._convertPositionTo("relative",{top:0,left:r-inst.helperProportions.width}).left;}
if(!inst.snapElements[i].snapping&&(ts||bs||ls||rs||first))
(inst.options.snap.snap&&inst.options.snap.snap.call(inst.element,null,$.extend(inst.uiHash(),{snapItem:inst.snapElements[i].item})));inst.snapElements[i].snapping=(ts||bs||ls||rs||first);};}});$.ui.plugin.add("draggable","connectToSortable",{start:function(e,ui){var inst=$(this).data("draggable");inst.sortables=[];$(ui.options.connectToSortable).each(function(){if($.data(this,'sortable')){var sortable=$.data(this,'sortable');inst.sortables.push({instance:sortable,shouldRevert:sortable.options.revert});sortable._refreshItems();sortable._propagate("activate",e,inst);}});},stop:function(e,ui){var inst=$(this).data("draggable");$.each(inst.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;inst.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(e);this.instance.element.triggerHandler("sortreceive",[e,$.extend(this.instance.ui(),{sender:inst.element})],this.instance.options["receive"]);this.instance.options.helper=this.instance.options._helper;}else{this.instance._propagate("deactivate",e,inst);}});},drag:function(e,ui){var inst=$(this).data("draggable"),self=this;var checkPos=function(o){var l=o.left,r=l+o.width,t=o.top,b=t+o.height;return(l<(this.positionAbs.left+this.offset.click.left)&&(this.positionAbs.left+this.offset.click.left)<r&&t<(this.positionAbs.top+this.offset.click.top)&&(this.positionAbs.top+this.offset.click.top)<b);};$.each(inst.sortables,function(i){if(checkPos.call(inst,this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=$(self).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return ui.helper[0];};e.target=this.instance.currentItem[0];this.instance._mouseCapture(e,true);this.instance._mouseStart(e,true,true);this.instance.offset.click.top=inst.offset.click.top;this.instance.offset.click.left=inst.offset.click.left;this.instance.offset.parent.left-=inst.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=inst.offset.parent.top-this.instance.offset.parent.top;inst._propagate("toSortable",e);}
if(this.instance.currentItem)this.instance._mouseDrag(e);}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._mouseStop(e,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder)this.instance.placeholder.remove();inst._propagate("fromSortable",e);}};});}});$.ui.plugin.add("draggable","stack",{start:function(e,ui){var group=$.makeArray($(ui.options.stack.group)).sort(function(a,b){return(parseInt($(a).css("zIndex"),10)||ui.options.stack.min)-(parseInt($(b).css("zIndex"),10)||ui.options.stack.min);});$(group).each(function(i){this.style.zIndex=ui.options.stack.min+i;});this[0].style.zIndex=ui.options.stack.min+group.length;}});})(jQuery);(function($){function contains(a,b){var safari2=$.browser.safari&&$.browser.version<522;if(a.contains&&!safari2){return a.contains(b);}
if(a.compareDocumentPosition)
return!!(a.compareDocumentPosition(b)&16);while(b=b.parentNode)
if(b==a)return true;return false;};$.widget("ui.sortable",$.extend({},$.ui.mouse,{_init:function(){var o=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?(/left|right/).test(this.items[0].item.css('float')):false;this.offset=this.element.offset();this._mouseInit();},plugins:{},ui:function(inst){return{helper:(inst||this)["helper"],placeholder:(inst||this)["placeholder"]||$([]),position:(inst||this)["position"],absolutePosition:(inst||this)["positionAbs"],options:this.options,element:this.element,item:(inst||this)["currentItem"],sender:inst?inst.element:null};},_propagate:function(n,e,inst,noPropagation){$.ui.plugin.call(this,n,[e,this.ui(inst)]);if(!noPropagation)this.element.triggerHandler(n=="sort"?n:"sort"+n,[e,this.ui(inst)],this.options[n]);},serialize:function(o){var items=this._getItemsAsjQuery(o&&o.connected);var str=[];o=o||{};$(items).each(function(){var res=($(this.item||this).attr(o.attribute||'id')||'').match(o.expression||(/(.+)[-=_](.+)/));if(res)str.push((o.key||res[1]+'[]')+'='+(o.key&&o.expression?res[1]:res[2]));});return str.join('&');},toArray:function(o){var items=this._getItemsAsjQuery(o&&o.connected);var ret=[];items.each(function(){ret.push($(this).attr(o.attr||'id'));});return ret;},_intersectsWith:function(item){var x1=this.positionAbs.left,x2=x1+this.helperProportions.width,y1=this.positionAbs.top,y2=y1+this.helperProportions.height;var l=item.left,r=l+item.width,t=item.top,b=t+item.height;var dyClick=this.offset.click.top,dxClick=this.offset.click.left;var isOverElement=(y1+dyClick)>t&&(y1+dyClick)<b&&(x1+dxClick)>l&&(x1+dxClick)<r;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance=="guess"&&this.helperProportions[this.floating?'width':'height']>item[this.floating?'width':'height'])){return isOverElement;}else{return(l<x1+(this.helperProportions.width/2)&&x2-(this.helperProportions.width/2)<r&&t<y1+(this.helperProportions.height/2)&&y2-(this.helperProportions.height/2)<b);}},_intersectsWithEdge:function(item){var x1=this.positionAbs.left,x2=x1+this.helperProportions.width,y1=this.positionAbs.top,y2=y1+this.helperProportions.height;var l=item.left,r=l+item.width,t=item.top,b=t+item.height;var dyClick=this.offset.click.top,dxClick=this.offset.click.left;var isOverElement=(y1+dyClick)>t&&(y1+dyClick)<b&&(x1+dxClick)>l&&(x1+dxClick)<r;if(this.options.tolerance=="pointer"||(this.options.tolerance=="guess"&&this.helperProportions[this.floating?'width':'height']>item[this.floating?'width':'height'])){if(!isOverElement)return false;if(this.floating){if((x1+dxClick)>l&&(x1+dxClick)<l+item.width/2)return 2;if((x1+dxClick)>l+item.width/2&&(x1+dxClick)<r)return 1;}else{var height=item.height;var direction=y1-this.updateOriginalPosition.top<0?2:1;if(direction==1&&(y1+dyClick)<t+height/2){return 2;}
else if(direction==2&&(y1+dyClick)>t+height/2){return 1;}}}else{if(!(l<x1+(this.helperProportions.width/2)&&x2-(this.helperProportions.width/2)<r&&t<y1+(this.helperProportions.height/2)&&y2-(this.helperProportions.height/2)<b))return false;if(this.floating){if(x2>l&&x1<l)return 2;if(x1<r&&x2>r)return 1;}else{if(y2>t&&y1<t)return 1;if(y1<b&&y2>b)return 2;}}
return false;},refresh:function(){this._refreshItems();this.refreshPositions();},_getItemsAsjQuery:function(connected){var self=this;var items=[];var queries=[];if(this.options.connectWith&&connected){for(var i=this.options.connectWith.length-1;i>=0;i--){var cur=$(this.options.connectWith[i]);for(var j=cur.length-1;j>=0;j--){var inst=$.data(cur[j],'sortable');if(inst&&inst!=this&&!inst.options.disabled){queries.push([$.isFunction(inst.options.items)?inst.options.items.call(inst.element):$(inst.options.items,inst.element).not(".ui-sortable-helper"),inst]);}};};}
queries.push([$.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):$(this.options.items,this.element).not(".ui-sortable-helper"),this]);for(var i=queries.length-1;i>=0;i--){queries[i][0].each(function(){items.push(this);});};return $(items);},_removeCurrentsFromItems:function(){var list=this.currentItem.find(":data(sortable-item)");for(var i=0;i<this.items.length;i++){for(var j=0;j<list.length;j++){if(list[j]==this.items[i].item[0])
this.items.splice(i,1);};};},_refreshItems:function(){this.items=[];this.containers=[this];var items=this.items;var self=this;var queries=[[$.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):$(this.options.items,this.element),this]];if(this.options.connectWith){for(var i=this.options.connectWith.length-1;i>=0;i--){var cur=$(this.options.connectWith[i]);for(var j=cur.length-1;j>=0;j--){var inst=$.data(cur[j],'sortable');if(inst&&inst!=this&&!inst.options.disabled){queries.push([$.isFunction(inst.options.items)?inst.options.items.call(inst.element):$(inst.options.items,inst.element),inst]);this.containers.push(inst);}};};}
for(var i=queries.length-1;i>=0;i--){queries[i][0].each(function(){$.data(this,'sortable-item',queries[i][1]);items.push({item:$(this),instance:queries[i][1],width:0,height:0,left:0,top:0});});};},refreshPositions:function(fast){if(this.offsetParent){var po=this.offsetParent.offset();this.offset.parent={top:po.top+this.offsetParentBorders.top,left:po.left+this.offsetParentBorders.left};}
for(var i=this.items.length-1;i>=0;i--){if(this.items[i].instance!=this.currentContainer&&this.currentContainer&&this.items[i].item[0]!=this.currentItem[0])
continue;var t=this.options.toleranceElement?$(this.options.toleranceElement,this.items[i].item):this.items[i].item;if(!fast){this.items[i].width=t[0].offsetWidth;this.items[i].height=t[0].offsetHeight;}
var p=t.offset();this.items[i].left=p.left;this.items[i].top=p.top;};if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this);}else{for(var i=this.containers.length-1;i>=0;i--){var p=this.containers[i].element.offset();this.containers[i].containerCache.left=p.left;this.containers[i].containerCache.top=p.top;this.containers[i].containerCache.width=this.containers[i].element.outerWidth();this.containers[i].containerCache.height=this.containers[i].element.outerHeight();};}},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var i=this.items.length-1;i>=0;i--)
this.items[i].item.removeData("sortable-item");},_createPlaceholder:function(that){var self=that||this,o=self.options;if(!o.placeholder||o.placeholder.constructor==String){var className=o.placeholder;o.placeholder={element:function(){var el=$(document.createElement(self.currentItem[0].nodeName)).addClass(className||"ui-sortable-placeholder")[0];if(!className){el.style.visibility="hidden";document.body.appendChild(el);el.innerHTML=self.currentItem[0].innerHTML;document.body.removeChild(el);};return el;},update:function(container,p){if(className&&!o.forcePlaceholderSize)return;if(!p.height()){p.height(self.currentItem.innerHeight()-parseInt(self.currentItem.css('paddingTop')||0,10)-parseInt(self.currentItem.css('paddingBottom')||0,10));};if(!p.width()){p.width(self.currentItem.innerWidth()-parseInt(self.currentItem.css('paddingLeft')||0,10)-parseInt(self.currentItem.css('paddingRight')||0,10));};}};}
self.placeholder=$(o.placeholder.element.call(self.element,self.currentItem))
self.currentItem.parent()[0].appendChild(self.placeholder[0]);self.placeholder[0].parentNode.insertBefore(self.placeholder[0],self.currentItem[0]);o.placeholder.update(self,self.placeholder);},_contactContainers:function(e){for(var i=this.containers.length-1;i>=0;i--){if(this._intersectsWith(this.containers[i].containerCache)){if(!this.containers[i].containerCache.over){if(this.currentContainer!=this.containers[i]){var dist=10000;var itemWithLeastDistance=null;var base=this.positionAbs[this.containers[i].floating?'left':'top'];for(var j=this.items.length-1;j>=0;j--){if(!contains(this.containers[i].element[0],this.items[j].item[0]))continue;var cur=this.items[j][this.containers[i].floating?'left':'top'];if(Math.abs(cur-base)<dist){dist=Math.abs(cur-base);itemWithLeastDistance=this.items[j];}}
if(!itemWithLeastDistance&&!this.options.dropOnEmpty)
continue;this.currentContainer=this.containers[i];itemWithLeastDistance?this.options.sortIndicator.call(this,e,itemWithLeastDistance,null,true):this.options.sortIndicator.call(this,e,null,this.containers[i].element,true);this._propagate("change",e);this.containers[i]._propagate("change",e,this);this.options.placeholder.update(this.currentContainer,this.placeholder);}
this.containers[i]._propagate("over",e,this);this.containers[i].containerCache.over=1;}}else{if(this.containers[i].containerCache.over){this.containers[i]._propagate("out",e,this);this.containers[i].containerCache.over=0;}}};},_mouseCapture:function(e,overrideHandle){if(this.options.disabled||this.options.type=='static')return false;this._refreshItems();var currentItem=null,self=this,nodes=$(e.target).parents().each(function(){if($.data(this,'sortable-item')==self){currentItem=$(this);return false;}});if($.data(e.target,'sortable-item')==self)currentItem=$(e.target);if(!currentItem)return false;if(this.options.handle&&!overrideHandle){var validHandle=false;$(this.options.handle,currentItem).find("*").andSelf().each(function(){if(this==e.target)validHandle=true;});if(!validHandle)return false;}
this.currentItem=currentItem;this._removeCurrentsFromItems();return true;},createHelper:function(e){var o=this.options;var helper=typeof o.helper=='function'?$(o.helper.apply(this.element[0],[e,this.currentItem])):(o.helper=="original"?this.currentItem:this.currentItem.clone());if(!helper.parents('body').length)
$(o.appendTo!='parent'?o.appendTo:this.currentItem[0].parentNode)[0].appendChild(helper[0]);return helper;},_mouseStart:function(e,overrideHandle,noActivation){var o=this.options;this.currentContainer=this;this.refreshPositions();this.helper=this.createHelper(e);this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)};this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.offset.click={left:e.pageX-this.offset.left,top:e.pageY-this.offset.top};this.offsetParent=this.helper.offsetParent();var po=this.offsetParent.offset();this.offsetParentBorders={top:(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};this.offset.parent={top:po.top+this.offsetParentBorders.top,left:po.left+this.offsetParentBorders.left};this.updateOriginalPosition=this.originalPosition=this._generatePosition(e);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};if(o.helper=="original"){this._storedCSS={position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left"),clear:this.currentItem.css("clear")};}else{this.currentItem.hide();}
this.helper.css({position:'absolute',clear:'both'}).addClass('ui-sortable-helper');this._createPlaceholder();this._propagate("start",e);if(!this._preserveHelperProportions)
this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};if(o.cursorAt){if(o.cursorAt.left!=undefined)this.offset.click.left=o.cursorAt.left;if(o.cursorAt.right!=undefined)this.offset.click.left=this.helperProportions.width-o.cursorAt.right;if(o.cursorAt.top!=undefined)this.offset.click.top=o.cursorAt.top;if(o.cursorAt.bottom!=undefined)this.offset.click.top=this.helperProportions.height-o.cursorAt.bottom;}
if(o.containment){if(o.containment=='parent')o.containment=this.helper[0].parentNode;if(o.containment=='document'||o.containment=='window')this.containment=[0-this.offset.parent.left,0-this.offset.parent.top,$(o.containment=='document'?document:window).width()-this.offset.parent.left-this.helperProportions.width-this.margins.left-(parseInt(this.element.css("marginRight"),10)||0),($(o.containment=='document'?document:window).height()||document.body.parentNode.scrollHeight)-this.offset.parent.top-this.helperProportions.height-this.margins.top-(parseInt(this.element.css("marginBottom"),10)||0)];if(!(/^(document|window|parent)$/).test(o.containment)){var ce=$(o.containment)[0];var co=$(o.containment).offset();var over=($(ce).css("overflow")!='hidden');this.containment=[co.left+(parseInt($(ce).css("borderLeftWidth"),10)||0)-this.offset.parent.left,co.top+(parseInt($(ce).css("borderTopWidth"),10)||0)-this.offset.parent.top,co.left+(over?Math.max(ce.scrollWidth,ce.offsetWidth):ce.offsetWidth)-(parseInt($(ce).css("borderLeftWidth"),10)||0)-this.offset.parent.left-this.helperProportions.width-this.margins.left-(parseInt(this.currentItem.css("marginRight"),10)||0),co.top+(over?Math.max(ce.scrollHeight,ce.offsetHeight):ce.offsetHeight)-(parseInt($(ce).css("borderTopWidth"),10)||0)-this.offset.parent.top-this.helperProportions.height-this.margins.top-(parseInt(this.currentItem.css("marginBottom"),10)||0)];}}
if(!noActivation){for(var i=this.containers.length-1;i>=0;i--){this.containers[i]._propagate("activate",e,this);}}
if($.ui.ddmanager)
$.ui.ddmanager.current=this;if($.ui.ddmanager&&!o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this,e);this.dragging=true;this._mouseDrag(e);return true;},_convertPositionTo:function(d,pos){if(!pos)pos=this.position;var mod=d=="absolute"?1:-1;return{top:(pos.top
+this.offset.parent.top*mod
-(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)*mod
+this.margins.top*mod),left:(pos.left
+this.offset.parent.left*mod
-(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft)*mod
+this.margins.left*mod)};},_generatePosition:function(e){var o=this.options;var position={top:(e.pageY
-this.offset.click.top
-this.offset.parent.top
+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)),left:(e.pageX
-this.offset.click.left
-this.offset.parent.left
+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft))};if(!this.originalPosition)return position;if(this.containment){if(position.left<this.containment[0])position.left=this.containment[0];if(position.top<this.containment[1])position.top=this.containment[1];if(position.left>this.containment[2])position.left=this.containment[2];if(position.top>this.containment[3])position.top=this.containment[3];}
if(o.grid){var top=this.originalPosition.top+Math.round((position.top-this.originalPosition.top)/o.grid[1])*o.grid[1];position.top=this.containment?(!(top<this.containment[1]||top>this.containment[3])?top:(!(top<this.containment[1])?top-o.grid[1]:top+o.grid[1])):top;var left=this.originalPosition.left+Math.round((position.left-this.originalPosition.left)/o.grid[0])*o.grid[0];position.left=this.containment?(!(left<this.containment[0]||left>this.containment[2])?left:(!(left<this.containment[0])?left-o.grid[0]:left+o.grid[0])):left;}
return position;},_mouseDrag:function(e){this.position=this._generatePosition(e);this.positionAbs=this._convertPositionTo("absolute");$.ui.plugin.call(this,"sort",[e,this.ui()]);this.positionAbs=this._convertPositionTo("absolute");this.helper[0].style.left=this.position.left+'px';this.helper[0].style.top=this.position.top+'px';for(var i=this.items.length-1;i>=0;i--){var intersection=this._intersectsWithEdge(this.items[i]);if(!intersection)continue;if(this.items[i].item[0]!=this.currentItem[0]&&this.placeholder[intersection==1?"next":"prev"]()[0]!=this.items[i].item[0]&&!contains(this.placeholder[0],this.items[i].item[0])&&(this.options.type=='semi-dynamic'?!contains(this.element[0],this.items[i].item[0]):true)){this.updateOriginalPosition=this._generatePosition(e);this.direction=intersection==1?"down":"up";this.options.sortIndicator.call(this,e,this.items[i]);this._propagate("change",e);break;}}
this._contactContainers(e);if($.ui.ddmanager)$.ui.ddmanager.drag(this,e);this.element.triggerHandler("sort",[e,this.ui()],this.options["sort"]);return false;},_rearrange:function(e,i,a,hardRefresh){a?a[0].appendChild(this.placeholder[0]):i.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=='down'?i.item[0]:i.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var self=this,counter=this.counter;window.setTimeout(function(){if(counter==self.counter)self.refreshPositions(!hardRefresh);},0);},_mouseStop:function(e,noPropagation){if($.ui.ddmanager&&!this.options.dropBehaviour)
$.ui.ddmanager.drop(this,e);if(this.options.revert){var self=this;var cur=self.placeholder.offset();$(this.helper).animate({left:cur.left-this.offset.parent.left-self.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:cur.top-this.offset.parent.top-self.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){self._clear(e);});}else{this._clear(e,noPropagation);}
return false;},_clear:function(e,noPropagation){if(!this._noFinalSort)this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.options.helper=="original")
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");else
this.currentItem.show();if(this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])this._propagate("update",e,null,noPropagation);if(!contains(this.element[0],this.currentItem[0])){this._propagate("remove",e,null,noPropagation);for(var i=this.containers.length-1;i>=0;i--){if(contains(this.containers[i].element[0],this.currentItem[0])){this.containers[i]._propagate("update",e,this,noPropagation);this.containers[i]._propagate("receive",e,this,noPropagation);}};};for(var i=this.containers.length-1;i>=0;i--){this.containers[i]._propagate("deactivate",e,this,noPropagation);if(this.containers[i].containerCache.over){this.containers[i]._propagate("out",e,this);this.containers[i].containerCache.over=0;}}
this.dragging=false;if(this.cancelHelperRemoval){this._propagate("beforeStop",e,null,noPropagation);this._propagate("stop",e,null,noPropagation);return false;}
this._propagate("beforeStop",e,null,noPropagation);this.placeholder.remove();if(this.options.helper!="original")this.helper.remove();this.helper=null;this._propagate("stop",e,null,noPropagation);return true;}}));$.extend($.ui.sortable,{getter:"serialize toArray",defaults:{helper:"original",tolerance:"guess",distance:1,delay:0,scroll:true,scrollSensitivity:20,scrollSpeed:20,cancel:":input",items:'> *',zIndex:1000,dropOnEmpty:true,appendTo:"parent",sortIndicator:$.ui.sortable.prototype._rearrange,scope:"default",forcePlaceholderSize:false}});$.ui.plugin.add("sortable","cursor",{start:function(e,ui){var t=$('body');if(t.css("cursor"))ui.options._cursor=t.css("cursor");t.css("cursor",ui.options.cursor);},beforeStop:function(e,ui){if(ui.options._cursor)$('body').css("cursor",ui.options._cursor);}});$.ui.plugin.add("sortable","zIndex",{start:function(e,ui){var t=ui.helper;if(t.css("zIndex"))ui.options._zIndex=t.css("zIndex");t.css('zIndex',ui.options.zIndex);},beforeStop:function(e,ui){if(ui.options._zIndex)$(ui.helper).css('zIndex',ui.options._zIndex);}});$.ui.plugin.add("sortable","opacity",{start:function(e,ui){var t=ui.helper;if(t.css("opacity"))ui.options._opacity=t.css("opacity");t.css('opacity',ui.options.opacity);},beforeStop:function(e,ui){if(ui.options._opacity)$(ui.helper).css('opacity',ui.options._opacity);}});$.ui.plugin.add("sortable","scroll",{start:function(e,ui){var o=ui.options;var i=$(this).data("sortable");i.overflowY=function(el){do{if(/auto|scroll/.test(el.css('overflow'))||(/auto|scroll/).test(el.css('overflow-y')))return el;el=el.parent();}while(el[0].parentNode);return $(document);}(i.currentItem);i.overflowX=function(el){do{if(/auto|scroll/.test(el.css('overflow'))||(/auto|scroll/).test(el.css('overflow-x')))return el;el=el.parent();}while(el[0].parentNode);return $(document);}(i.currentItem);if(i.overflowY[0]!=document&&i.overflowY[0].tagName!='HTML')i.overflowYOffset=i.overflowY.offset();if(i.overflowX[0]!=document&&i.overflowX[0].tagName!='HTML')i.overflowXOffset=i.overflowX.offset();},sort:function(e,ui){var o=ui.options;var i=$(this).data("sortable");if(i.overflowY[0]!=document&&i.overflowY[0].tagName!='HTML'){if((i.overflowYOffset.top+i.overflowY[0].offsetHeight)-e.pageY<o.scrollSensitivity)
i.overflowY[0].scrollTop=i.overflowY[0].scrollTop+o.scrollSpeed;if(e.pageY-i.overflowYOffset.top<o.scrollSensitivity)
i.overflowY[0].scrollTop=i.overflowY[0].scrollTop-o.scrollSpeed;}else{if(e.pageY-$(document).scrollTop()<o.scrollSensitivity)
$(document).scrollTop($(document).scrollTop()-o.scrollSpeed);if($(window).height()-(e.pageY-$(document).scrollTop())<o.scrollSensitivity)
$(document).scrollTop($(document).scrollTop()+o.scrollSpeed);}
if(i.overflowX[0]!=document&&i.overflowX[0].tagName!='HTML'){if((i.overflowXOffset.left+i.overflowX[0].offsetWidth)-e.pageX<o.scrollSensitivity)
i.overflowX[0].scrollLeft=i.overflowX[0].scrollLeft+o.scrollSpeed;if(e.pageX-i.overflowXOffset.left<o.scrollSensitivity)
i.overflowX[0].scrollLeft=i.overflowX[0].scrollLeft-o.scrollSpeed;}else{if(e.pageX-$(document).scrollLeft()<o.scrollSensitivity)
$(document).scrollLeft($(document).scrollLeft()-o.scrollSpeed);if($(window).width()-(e.pageX-$(document).scrollLeft())<o.scrollSensitivity)
$(document).scrollLeft($(document).scrollLeft()+o.scrollSpeed);}}});$.ui.plugin.add("sortable","axis",{sort:function(e,ui){var i=$(this).data("sortable");if(ui.options.axis=="y")i.position.left=i.originalPosition.left;if(ui.options.axis=="x")i.position.top=i.originalPosition.top;}});})(jQuery);

/***************************** Upload ********************************/
// http://www.phpletter.com/Our-Projects/AjaxFileUpload/
jQuery.extend({
    createUploadIframe: function(id, uri)
	{
			//create frame
            var frameId = 'jUploadFrame' + id;
            
            if(window.ActiveXObject) {
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                }
                else if(typeof uri== 'string'){
                    io.src = uri;
                }
            }
            else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);

            return io			
    },
    createUploadForm: function(id, fileElementId)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1200px');
		$(form).css('left', '-1200px');
		$(form).appendTo('body');		
		return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()        
		var form = jQuery.createUploadForm(id, s.fileElementId);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout") 
			{				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											$(io).remove();
											$(form).remove();	
											
										} catch(e) 
										{
											jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{
           // var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
            if(form.encoding)
			{
                form.encoding = 'multipart/form-data';				
            }
            else
			{				
                form.enctype = 'multipart/form-data';
            }			
            $(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        } 		
        return {abort: function () {}};	

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
			//alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
});

/***************************** Validate ********************************/
(function($){$.extend($.fn,{validate:function(options){if(!this.length){options&&options.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return;}var validator=$.data(this[0],'validator');if(validator){return validator;}validator=new $.validator(options,this[0]);$.data(this[0],'validator',validator);if(validator.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){validator.cancelSubmit=true;});this.submit(function(event){if(validator.settings.debug)event.preventDefault();function handle(){if(validator.settings.submitHandler){validator.settings.submitHandler.call(validator,validator.currentForm);return false;}return true;}if(validator.cancelSubmit){validator.cancelSubmit=false;return handle();}if(validator.form()){if(validator.pendingRequest){validator.formSubmitted=true;return false;}return handle();}else{validator.focusInvalid();return false;}});}return validator;},valid:function(){if($(this[0]).is('form')){return this.validate().form();}else{var valid=false;var validator=$(this[0].form).validate();this.each(function(){valid|=validator.element(this);});return valid;}},removeAttrs:function(attributes){var result={},$element=this;$.each(attributes.split(/\s/),function(){result[this]=$element.attr(this);$element.removeAttr(this);});return result;},rules:function(command,argument){var element=this[0];if(command){var staticRules=$.data(element.form,'validator').settings.rules;var existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));staticRules[element.name]=existingRules;break;case"remove":if(!argument){delete staticRules[element.name];return existingRules;}var filtered={};$.each(argument.split(/\s/),function(index,method){filtered[method]=existingRules[method];delete existingRules[method];});return filtered;}}var data=$.validator.normalizeRules($.extend({},$.validator.metadataRules(element),$.validator.classRules(element),$.validator.attributeRules(element),$.validator.staticRules(element)),element);if(data.required){var param=data.required;delete data.required;data=$.extend({required:param},data);}return data;},push:function(t){return this.setArray(this.add(t).get());}});$.extend($.expr[":"],{blank:function(a){return!$.trim(a.value);},filled:function(a){return!!$.trim(a.value);},unchecked:function(a){return!a.checked;}});$.format=function(source,params){if(arguments.length==1)return function(){var args=$.makeArray(arguments);args.unshift(source);return $.format.apply(this,args);};if(arguments.length>2&&params.constructor!=Array){params=$.makeArray(arguments).slice(1);}if(params.constructor!=Array){params=[params];}$.each(params,function(i,n){source=source.replace(new RegExp("\\{"+i+"\\}","g"),n);});return source;};$.validator=function(options,form){this.settings=$.extend({},$.validator.defaults,options);this.currentForm=form;this.init();};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",errorElement:"label",focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:[],onfocusin:function(element){this.lastActive=element;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,element,this.settings.errorClass);this.errorsFor(element).hide();}},onfocusout:function(element){if(!this.checkable(element)&&(element.name in this.submitted||!this.optional(element))){this.element(element);}},onkeyup:function(element){if(element.name in this.submitted||element==this.lastElement){this.element(element);}},onclick:function(element){if(element.name in this.submitted)this.element(element);},highlight:function(element,errorClass){$(element).addClass(errorClass);},unhighlight:function(element,errorClass){$(element).removeClass(errorClass);}},setDefaults:function(settings){$.extend($.validator.defaults,settings);},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",dateDE:"Bitte geben Sie ein gültiges Datum ein.",number:"Please enter a valid number.",numberDE:"Bitte geben Sie eine Nummer ein.",digits:"Please enter only digits",creditcard:"Please enter a valid credit card.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:$.format("Please enter no more than {0} characters."),minlength:$.format("Please enter at least {0} characters."),rangelength:$.format("Please enter a value between {0} and {1} characters long."),range:$.format("Please enter a value between {0} and {1}."),max:$.format("Please enter a value less than or equal to {0}."),min:$.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=$(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||$(this.currentForm);this.containers=$(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var groups=(this.groups={});$.each(this.settings.groups,function(key,value){$.each(value.split(/\s/),function(index,name){groups[name]=key;});});var rules=this.settings.rules;$.each(rules,function(key,value){rules[key]=$.validator.normalizeRule(value);});function delegate(event){var validator=$.data(this[0].form,"validator");validator.settings["on"+event.type]&&validator.settings["on"+event.type].call(validator,this[0]);}$(this.currentForm).delegate("focusin focusout keyup",":text, :password, :file, select, textarea",delegate).delegate("click",":radio, :checkbox",delegate);},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid())$(this.currentForm).triggerHandler("invalid-form.validate",[this]);this.showErrors();return this.valid();},checkForm:function(){this.prepareForm();for(var i=0,elements=(this.currentElements=this.elements());elements[i];i++){this.check(elements[i]);}return this.valid();},element:function(element){element=this.clean(element);this.lastElement=element;this.prepareElement(element);this.currentElements=$(element);var result=this.check(element);if(result){delete this.invalid[element.name];}else{this.invalid[element.name]=true;}if(!this.numberOfInvalids()){this.toHide.push(this.containers);}this.showErrors();return result;},showErrors:function(errors){if(errors){$.extend(this.errorMap,errors);this.errorList=[];for(var name in errors){this.errorList.push({message:errors[name],element:this.findByName(name)[0]});}this.successList=$.grep(this.successList,function(element){return!(element.name in errors);});}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors();},resetForm:function(){if($.fn.resetForm)$(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass);},numberOfInvalids:function(){return this.objectLength(this.invalid);},objectLength:function(obj){var count=0;for(var i in obj)count++;return count;},hideErrors:function(){this.addWrapper(this.toHide).hide();},valid:function(){return this.size()==0;},size:function(){return this.errorList.length;},focusInvalid:function(){if(this.settings.focusInvalid){try{$(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus();}catch(e){}}},findLastActive:function(){var lastActive=this.lastActive;return lastActive&&$.grep(this.errorList,function(n){return n.element.name==lastActive.name;}).length==1&&lastActive;},elements:function(){var validator=this,rulesCache={};return $([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&validator.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in rulesCache||!validator.objectLength($(this).rules()))return false;rulesCache[this.name]=true;return true;});},clean:function(selector){return $(selector)[0];},errors:function(){return $(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext);},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=$([]);this.toHide=$([]);this.formSubmitted=false;this.currentElements=$([]);},prepareForm:function(){this.reset();this.toHide=this.errors().push(this.containers);},prepareElement:function(element){this.reset();this.toHide=this.errorsFor(element);},check:function(element){element=this.clean(element);if(this.checkable(element)){element=this.findByName(element.name)[0];}var rules=$(element).rules();var dependencyMismatch=false;for(method in rules){var rule={method:method,parameters:rules[method]};try{var result=$.validator.methods[method].call(this,$.trim(element.value),element,rule.parameters);if(result=="dependency-mismatch"){dependencyMismatch=true;continue;}dependencyMismatch=false;if(result=="pending"){this.toHide=this.toHide.not(this.errorsFor(element));return;}if(!result){this.formatAndAdd(element,rule);return false;}}catch(e){this.settings.debug&&window.console&&console.log("exception occured when checking element "+element.id
+", check the '"+rule.method+"' method");throw e;}}if(dependencyMismatch)return;if(this.objectLength(rules))this.successList.push(element);return true;},customMetaMessage:function(element,method){if(!$.metadata)return;var meta=this.settings.meta?$(element).metadata()[this.settings.meta]:$(element).metadata();return meta.messages&&meta.messages[method];},customMessage:function(name,method){var m=this.settings.messages[name];return m&&(m.constructor==String?m:m[method]);},findDefined:function(){for(var i=0;i<arguments.length;i++){if(arguments[i]!==undefined)return arguments[i];}return undefined;},defaultMessage:function(element,method){return this.findDefined(this.customMessage(element.name,method),this.customMetaMessage(element,method),element.title||undefined,$.validator.messages[method],"<strong>Warning: No message defined for "+element.name+"</strong>");},formatAndAdd:function(element,rule){var message=this.defaultMessage(element,rule.method);if(typeof message=="function")message=message.call(this,rule.parameters,element);this.errorList.push({message:message,element:element});this.errorMap[element.name]=message;this.submitted[element.name]=message;},addWrapper:function(toToggle){if(this.settings.wrapper)toToggle.push(toToggle.parents(this.settings.wrapper));return toToggle;},defaultShowErrors:function(){for(var i=0;this.errorList[i];i++){var error=this.errorList[i];this.settings.highlight&&this.settings.highlight.call(this,error.element,this.settings.errorClass);this.showLabel(error.element,error.message);}if(this.errorList.length){this.toShow.push(this.containers);}if(this.settings.success){for(var i=0;this.successList[i];i++){this.showLabel(this.successList[i]);}}if(this.settings.unhighlight){for(var i=0,elements=this.validElements();elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass);}}this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show();},validElements:function(){return this.currentElements.not(this.invalidElements());},invalidElements:function(){return $(this.errorList).map(function(){return this.element;});},showLabel:function(element,message){var label=this.errorsFor(element);if(label.length){label.removeClass().addClass(this.settings.errorClass);label.attr("generated")&&label.html(message);}else{label=$("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(element),generated:true}).addClass(this.settings.errorClass).html(message||"");if(this.settings.wrapper){label=label.hide().show().wrap("<"+this.settings.wrapper+">").parent();}if(!this.labelContainer.append(label).length)this.settings.errorPlacement?this.settings.errorPlacement(label,$(element)):label.insertAfter(element);}if(!message&&this.settings.success){label.text("");typeof this.settings.success=="string"?label.addClass(this.settings.success):this.settings.success(label);}this.toShow.push(label);},errorsFor:function(element){return this.errors().filter("[@for='"+this.idOrName(element)+"']");},idOrName:function(element){return this.groups[element.name]||(this.checkable(element)?element.name:element.id||element.name);},checkable:function(element){return/radio|checkbox/i.test(element.type);},findByName:function(name){var form=this.currentForm;return $(document.getElementsByName(name)).map(function(index,element){return element.form==form&&element.name==name&&element||null;});},getLength:function(value,element){switch(element.nodeName.toLowerCase()){case'select':return $("option:selected",element).length;case'input':if(this.checkable(element))return this.findByName(element.name).filter(':checked').length;}return value.length;},depend:function(param,element){return this.dependTypes[typeof param]?this.dependTypes[typeof param](param,element):true;},dependTypes:{"boolean":function(param,element){return param;},"string":function(param,element){return!!$(param,element.form).length;},"function":function(param,element){return param(element);}},optional:function(element){return!$.validator.methods.required.call(this,$.trim(element.value),element)&&"dependency-mismatch";},startRequest:function(element){if(!this.pending[element.name]){this.pendingRequest++;this.pending[element.name]=true;}},stopRequest:function(element,valid){this.pendingRequest--;if(this.pendingRequest<0)this.pendingRequest=0;delete this.pending[element.name];if(valid&&this.pendingRequest==0&&this.formSubmitted&&this.form()){$(this.currentForm).submit();}},previousValue:function(element){return $.data(element,"previousValue")||$.data(element,"previousValue",previous={old:null,valid:true,message:this.defaultMessage(element,"remote")});}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true},phoneUS:{phoneUS:true}},addClassRules:function(className,rules){className.constructor==String?this.classRuleSettings[className]=rules:$.extend(this.classRuleSettings,className);},classRules:function(element){var rules={};var classes=$(element).attr('class');classes&&$.each(classes.split(' '),function(){if(this in $.validator.classRuleSettings){$.extend(rules,$.validator.classRuleSettings[this]);}});return rules;},attributeRules:function(element){var rules={};var $element=$(element);for(method in $.validator.methods){var value=$element.attr(method);if(value){rules[method]=value;}}if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){delete rules.maxlength;}return rules;},metadataRules:function(element){if(!$.metadata)return{};var meta=$.data(element.form,'validator').settings.meta;return meta?$(element).metadata()[meta]:$(element).metadata();},staticRules:function(element){var rules={};var validator=$.data(element.form,'validator');if(validator.settings.rules){rules=$.validator.normalizeRule(validator.settings.rules[element.name])||{};}return rules;},normalizeRules:function(rules,element){$.each(rules,function(prop,val){if(val===false){delete rules[prop];return;}if(val.param||val.depends){var keepRule=true;switch(typeof val.depends){case"string":keepRule=!!$(val.depends,element.form).length;break;case"function":keepRule=val.depends.call(element,element);break;}if(keepRule){rules[prop]=val.param!==undefined?val.param:true;}else{delete rules[prop];}}});$.each(rules,function(rule,parameter){rules[rule]=$.isFunction(parameter)?parameter(element):parameter;});$.each(['minlength','maxlength','min','max'],function(){if(rules[this]){rules[this]=Number(rules[this]);}});$.each(['rangelength','range'],function(){if(rules[this]){rules[this]=[Number(rules[this][0]),Number(rules[this][1])];}});if($.validator.autoCreateRanges){if(rules.min&&rules.max){rules.range=[rules.min,rules.max];delete rules.min;delete rules.max;}if(rules.minlength&&rules.maxlength){rules.rangelength=[rules.minlength,rules.maxlength];delete rules.minlength;delete rules.maxlength;}}if(rules.messages){delete rules.messages}return rules;},normalizeRule:function(data){if(typeof data=="string"){var transformed={};$.each(data.split(/\s/),function(){transformed[this]=true;});data=transformed;}return data;},addMethod:function(name,method,message){$.validator.methods[name]=method;$.validator.messages[name]=message;if(method.length<3){$.validator.addClassRules(name,$.validator.normalizeRule(name));}},methods:{required:function(value,element,param){if(!this.depend(param,element))return"dependency-mismatch";switch(element.nodeName.toLowerCase()){case'select':var options=$("option:selected",element);return options.length>0&&(element.type=="select-multiple"||($.browser.msie&&!(options[0].attributes['value'].specified)?options[0].text:options[0].value).length>0);case'input':if(this.checkable(element))return this.getLength(value,element)>0;default:return value.length>0;}},remote:function(value,element,param){if(this.optional(element))return"dependency-mismatch";var previous=this.previousValue(element);if(!this.settings.messages[element.name])this.settings.messages[element.name]={};this.settings.messages[element.name].remote=typeof previous.message=="function"?previous.message(value):previous.message;if(previous.old!==value){previous.old=value;var validator=this;this.startRequest(element);var data={};data[element.name]=value;$.ajax({url:param,mode:"abort",port:"validate"+element.name,dataType:"json",data:data,success:function(response){if(!response){var errors={};errors[element.name]=response||validator.defaultMessage(element,"remote");validator.showErrors(errors);}else{var submitted=validator.formSubmitted;validator.prepareElement(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.showErrors();}previous.valid=response;validator.stopRequest(element,response);}});return"pending";}else if(this.pending[element.name]){return"pending";}return previous.valid;},minlength:function(value,element,param){return this.optional(element)||this.getLength(value,element)>=param;},maxlength:function(value,element,param){return this.optional(element)||this.getLength(value,element)<=param;},rangelength:function(value,element,param){var length=this.getLength(value,element);return this.optional(element)||(length>=param[0]&&length<=param[1]);},min:function(value,element,param){return this.optional(element)||value>=param;},max:function(value,element,param){return this.optional(element)||value<=param;},range:function(value,element,param){return this.optional(element)||(value>=param[0]&&value<=param[1]);},email:function(value,element){return this.optional(element)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(element.value);},url:function(value,element){return this.optional(element)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(element.value);},date:function(value,element){return this.optional(element)||!/Invalid|NaN/.test(new Date(value));},dateISO:function(value,element){return this.optional(element)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);},dateDE:function(value,element){return this.optional(element)||/^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);},number:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);},numberDE:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);},digits:function(value,element){return this.optional(element)||/^\d+$/.test(value);},creditcard:function(value,element){if(this.optional(element))return"dependency-mismatch";if(/[^0-9-]+/.test(value))return false;var nCheck=0,nDigit=0,bEven=false;value=value.replace(/\D/g,"");for(n=value.length-1;n>=0;n--){var cDigit=value.charAt(n);var nDigit=parseInt(cDigit,10);if(bEven){if((nDigit*=2)>9)nDigit-=9;}nCheck+=nDigit;bEven=!bEven;}return(nCheck%10)==0;},accept:function(value,element,param){param=typeof param=="string"?param:"png|jpe?g|gif";return this.optional(element)||value.match(new RegExp(".("+param+")$","i"));},equalTo:function(value,element,param){return value==$(param).val();}}});})(jQuery);;(function($){var ajax=$.ajax;var pendingRequests={};$.ajax=function(settings){settings=$.extend(settings,$.extend({},$.ajaxSettings,settings));var port=settings.port;if(settings.mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}return(pendingRequests[port]=ajax.apply(this,arguments));}return ajax.apply(this,arguments);};})(jQuery);;(function($){$.each({focus:'focusin',blur:'focusout'},function(original,fix){$.event.special[fix]={setup:function(){if($.browser.msie)return false;this.addEventListener(original,$.event.special[fix].handler,true);},teardown:function(){if($.browser.msie)return false;this.removeEventListener(original,$.event.special[fix].handler,true);},handler:function(e){arguments[0]=$.event.fix(e);arguments[0].type=fix;return $.event.handle.apply(this,arguments);}};});$.extend($.fn,{delegate:function(type,delegate,handler){return this.bind(type,function(event){var target=$(event.target);if(target.is(delegate)){return handler.apply(target,arguments);}});},triggerEvent:function(type,target){return this.triggerHandler(type,[$.event.fix({type:type,target:target})]);}})})(jQuery);

// Regular Expression Method		
jQuery.validator.addMethod("regex", function(value, element, regex) {
	var expression = new RegExp(regex, 'g');
	return (value.replace(expression,"").length == 0);
});
// Phone Number (US)
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
// Multiple Emails (separated by commas) // Does not work in IE
jQuery.validator.addMethod("emails", function(value, element) {
	if (this.optional(element)) return true;
	var valid = true;
	var emails = value.split( new RegExp("\\s*,\\s*", "gi"));
	for(var i = 0; i < emails.length; i++) {
		var email = emails[i];
		valid = valid && /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email);
	}
	return valid;
},jQuery.validator.messages.email);
// URL (with or without http)
jQuery.validator.addMethod("url_basic", function(value, element) {
   return this.optional(element) || /^(http:\/\/|https:\/\/|ftp:\/\/|www\.)(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
}, "Please enter a valid url");

/***************************** Thickbox ********************************/
var tb_pathToImage = DOMAIN+"images/loadingAnimation.gif";
//on page load call tb_init
$(document).ready(function(){   
  tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
  imgLoader = new Image();// preload image
  imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
  $(domChunk).click(function(){
  var t = this.title || this.name || null;
  var a = this.href || this.alt;
  var g = this.rel || false;
  tb_show(t,a,g);
  this.blur();
  return false;
  });
  
  // Refresh jQuery
  refreshIt(1);
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
  try {
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
      $("body","html").css({height: "100%", width: "100%"});
      $("html").css("overflow","hidden");
      if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
        $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
        $("#TB_overlay").click(tb_remove);
      }
    }else{//all others
      if(document.getElementById("TB_overlay") === null){
        $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
        $("#TB_overlay").click(tb_remove);
      }
    }
    
    if(tb_detectMacXFF()){
      $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
    }else{
      $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
    }
    
    if(caption===null){caption="";}
    $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
    $('#TB_load').show();//show loader
    
    var baseURL;
     if(url.indexOf("?")!==-1){ //ff there is a query string involved
      baseURL = url.substr(0, url.indexOf("?"));
     }else{ 
         baseURL = url;
     }
     
     var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
     var urlType = baseURL.toLowerCase().match(urlString);
    if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
        
      TB_PrevCaption = "";
      TB_PrevURL = "";
      TB_PrevHTML = "";
      TB_NextCaption = "";
      TB_NextURL = "";
      TB_NextHTML = "";
      TB_imageCount = "";
      TB_FoundURL = false;
      if(imageGroup){
        TB_TempArray = $("a[@rel="+imageGroup+"]").get();
        for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
          var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
            if (!(TB_TempArray[TB_Counter].href == url)) {            
              if (TB_FoundURL) {
                TB_NextCaption = TB_TempArray[TB_Counter].title;
                TB_NextURL = TB_TempArray[TB_Counter].href;
                TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
              } else {
                TB_PrevCaption = TB_TempArray[TB_Counter].title;
                TB_PrevURL = TB_TempArray[TB_Counter].href;
                TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
              }
            } else {
              TB_FoundURL = true;
              TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);                      
            }
        }
      }
      imgPreloader = new Image();
      imgPreloader.onload = function(){    
      imgPreloader.onload = null;
        
      // Resizing large images - orginal by Christian Montoya edited by me.
      var pagesize = tb_getPageSize();
      var x = pagesize[0] - 150;
      var y = pagesize[1] - 150;
      var imageWidth = imgPreloader.width;
      var imageHeight = imgPreloader.height;
      if (imageWidth > x) {
        imageHeight = imageHeight * (x / imageWidth); 
        imageWidth = x; 
        if (imageHeight > y) { 
          imageWidth = imageWidth * (y / imageHeight); 
          imageHeight = y; 
        }
      } else if (imageHeight > y) { 
        imageWidth = imageWidth * (y / imageHeight); 
        imageHeight = y; 
        if (imageWidth > x) { 
          imageHeight = imageHeight * (x / imageWidth); 
          imageWidth = x;
        }
      }
      // End Resizing
      
      TB_WIDTH = imageWidth + 30;
      TB_HEIGHT = imageHeight + 60;
      $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'><img src='" + DOMAIN + "images/close.gif' alt='[x]' /></a></div>");     
      
      $("#TB_closeWindowButton").click(tb_remove);
      
      if (!(TB_PrevHTML === "")) {
        function goPrev(){
          if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
          return false;  
        }
        $("#TB_prev").click(goPrev);
      }
      
      if (!(TB_NextHTML === "")) {    
        function goNext(){
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(TB_NextCaption, TB_NextURL, imageGroup);        
          return false;  
        }
        $("#TB_next").click(goNext);
        
      }
      document.onkeydown = function(e){   
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        } else if(keycode == 190){ // display previous image
          if(!(TB_NextHTML == "")){
            document.onkeydown = "";
            goNext();
          }
        } else if(keycode == 188){ // display next image
          if(!(TB_PrevHTML == "")){
            document.onkeydown = "";
            goPrev();
          }
        }  
      };
      
      tb_position();
      $("#TB_load").remove();
      $("#TB_ImageOff").click(tb_remove);
      $("#TB_window").css({display:"block"}); //for safari using css instead of show
      };
      
      imgPreloader.src = url;
    }else{//code to show html
      
      var queryString = url.replace(/^[^\?]+\??/,'');
      var params = tb_parseQuery( queryString );
      TB_WIDTH = (params['width']*1) + 30 || 740; //defaults to 630 if no paramaters were added to URL
      TB_HEIGHT = (params['height']*1) + 40 || 500; //defaults to 440 if no paramaters were added to URL
      ajaxContentW = TB_WIDTH - 30;
      ajaxContentH = TB_HEIGHT - 45;
      
      if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window    
          urlNoQuery = url.split('TB_');
          $("#TB_iframeContent").remove();
          if(params['modal'] != "true"){//iframe no modal
            $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'><img src='" + DOMAIN + "images/close.gif' alt='[x]' /></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
          }else{//iframe modal
          $("#TB_overlay").unbind();
            $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
          }
      }else{// not an iframe, ajax
          if($("#TB_window").css("display") != "block"){
            if(params['modal'] != "true"){//ajax no modal
            $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><img src='" + DOMAIN + "images/close.gif' alt='[x]' /></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
            }else{//ajax modal
            $("#TB_overlay").unbind();
            $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");  
            }
          }else{//this means the window is already up, we are just loading new content via ajax
            $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
            $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
            $("#TB_ajaxContent")[0].scrollTop = 0;
            $("#TB_ajaxWindowTitle").html(caption);
          }
      }
          
      $("#TB_closeWindowButton").click(tb_remove);
      
        if(url.indexOf('TB_inline') != -1){  
          $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
          $("#TB_window").unload(function () {
            $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
          });
          tb_position();
          $("#TB_load").remove();
          $("#TB_window").css({display:"block"}); 
        }else if(url.indexOf('TB_iframe') != -1){
          tb_position();
          if($.browser.safari){//safari needs help because it will not fire iframe onload
            $("#TB_load").remove();
            $("#TB_window").css({display:"block"});
          }
        }else{
          $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
            tb_position();
            $("#TB_load").remove();
            tb_init("#TB_ajaxContent a.thickbox");
            $("#TB_window").css({display:"block"});
          });
        }
      
    }
    if(!params['modal']){
      document.onkeyup = function(e){   
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        }  
      };
    }
    
  } catch(e) {
    //nothing here
  }
}
//helper functions below
function tb_showIframe(){
  $("#TB_load").remove();
  $("#TB_window").css({display:"block"});
}
function tb_remove() {
   $("#TB_imageOff").unbind("click");
  $("#TB_closeWindowButton").unbind("click");
  $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
  $("#TB_load").remove();
  if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    $("body","html").css({height: "auto", width: "auto"});
    $("html").css("overflow","");
  }
  document.onkeydown = "";
  document.onkeyup = "";
  return false;
}
function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
  if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
  }
}
function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}
function tb_getPageSize(){
  var de = document.documentElement;
  var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
  var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
  arrayPageSize = [w,h];
  return arrayPageSize;
}
function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

/***************************** Scroll To ********************************/
;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

/***************************** Auto Complete ********************************/
;(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){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){v=words.slice(0,words.length-1).join(options.multipleSeparator)+options.multipleSeparator+v;}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[""];}var words=value.split(options.multipleSeparator);var result=[];$.each(words,function(i,value){if($.trim(value))result[i]=$.trim(value);});return result;}function lastWord(value){if(!options.multiple)return value;var words=trimWords(value);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));$.Autocompleter.Selection(input,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("");}});}if(wasVisible)$.Autocompleter.Selection(input,input.value.length,input.value.length);};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(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();}};};$.Autocompleter.Selection=function(field,start,end){if(field.createTextRange){var selRange=field.createTextRange();selRange.collapse(true);selRange.moveStart("character",start);selRange.moveEnd("character",end);selRange.select();}else if(field.setSelectionRange){field.setSelectionRange(start,end);}else{if(field.selectionStart){field.selectionStart=start;field.selectionEnd=end;}}field.focus();};})(jQuery);


/***************************** Rating ********************************/
// http://www.fyneworks.com/jquery/star-rating/
/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/
	
	// IE6 Background Image Fix
	if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { };
	// Thanks to http://www.visualjquery.com/rating/rating_redux.html
	
	// plugin initialization
	$.fn.rating = function(options){
		if(this.length==0) return this; // quick fail
		
		// Handle API methods
		if(typeof arguments[0]=='string'){
			// Perform API methods on individual elements
			if(this.length>1){
				var args = arguments;
				return this.each(function(){
					$.fn.rating.apply($(this), args);
    });
			};
			// Invoke API method handler
			$.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
			// Quick exit...
			return this;
		};
		
		// Initialize options for this call
		var options = $.extend(
			{}/* new object */,
			$.fn.rating.options/* default options */,
			options || {} /* just-in-time options */
		);
		
		// Allow multiple controls with the same name by making each call unique
		$.fn.rating.calls++;
		
		// loop through each matched element
		this
		 .not('.star-rating-applied')
			.addClass('star-rating-applied')
		.each(function(){
			
			// Load control parameters / find context / etc
			var control, input = $(this);
			var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,'');
			var context = $(this.form || document.body);
			
			// FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23
			var raters = context.data('rating');
			if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls };
			var rater = raters[eid];
			
			// if rater is available, verify that the control still exists
			if(rater) control = rater.data('rating');
			
			if(rater && control)//{// save a byte!
				// add star to control if rater is available and the same control still exists
				control.count++;
				
			//}// save a byte!
			else{
				// create new control if first star or control element was removed/replaced
				
				// Initialize options for this raters
				control = $.extend(
					{}/* new object */,
					options || {} /* current call options */,
					($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */
					{ count:0, stars: [], inputs: [] }
				);
				
				// increment number of rating controls
				control.serial = raters.count++;
				
				// create rating element
				rater = $('<span class="star-rating-control"/>');
				input.before(rater);
				
				// Mark element for initialization (once all stars are ready)
				rater.addClass('rating-to-be-drawn');
				
				// Accept readOnly setting from 'disabled' property
				if(input.attr('disabled')) control.readOnly = true;
				
				// Create 'cancel' button
				rater.append(
					control.cancel = $('<div class="rating-cancel"><a title="' + control.cancelText + '">' + control.cancelValue + '</a></div>')
					.mouseover(function(){
						$(this).rating('drain');
						$(this).addClass('star-rating-hover');
						//$(this).rating('focus');
					})
					.mouseout(function(){
						$(this).rating('draw');
						$(this).removeClass('star-rating-hover');
						//$(this).rating('blur');
					})
					.click(function(){
					 $(this).rating('select');
					})
					.data('rating', control)
				);
				
			}; // first element of group
			
			// insert rating star
			var star = $('<div class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>');
			rater.append(star);
			
			// inherit attributes from input element
			if(this.id) star.attr('id', this.id);
			if(this.className) star.addClass(this.className);
			
			// Half-stars?
			if(control.half) control.split = 2;
			
			// Prepare division control
			if(typeof control.split=='number' && control.split>0){
				var stw = ($.fn.width ? star.width() : 0) || control.starWidth;
				var spi = (control.count % control.split), spw = Math.floor(stw/control.split);
				star
				// restrict star's width and hide overflow (already in CSS)
				.width(spw)
				// move the star left by using a negative margin
				// this is work-around to IE's stupid box model (position:relative doesn't work)
				.find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' })
			};
			
			// readOnly?
			if(control.readOnly)//{ //save a byte!
				// Mark star as readOnly so user can customize display
				star.addClass('star-rating-readonly');
			//}  //save a byte!
			else//{ //save a byte!
			 // Enable hover css effects
				star.addClass('star-rating-live')
				 // Attach mouse events
					.mouseover(function(){
						$(this).rating('fill');
						$(this).rating('focus');
					})
					.mouseout(function(){
						$(this).rating('draw');
						$(this).rating('blur');
					})
					.click(function(){
						$(this).rating('select');
					})
				;
			//}; //save a byte!
			
			// set current selection
			if(this.checked)	control.current = star;
			
			// hide input element
			input.hide();
			
			// backward compatibility, form element to plugin
			input.change(function(){
    $(this).rating('select');
   });
			
			// attach reference to star to input element and vice-versa
			star.data('rating.input', input.data('rating.star', star));
			
			// store control information in form (or body when form not available)
			control.stars[control.stars.length] = star[0];
			control.inputs[control.inputs.length] = input[0];
			control.rater = raters[eid] = rater;
			control.context = context;
			
			input.data('rating', control);
			rater.data('rating', control);
			star.data('rating', control);
			context.data('rating', raters);
  }); // each element
		
		// Initialize ratings (first draw)
		$('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn');
		
		return this; // don't break the chain...
	};
	
	/*--------------------------------------------------------*/
	
	/*
		### Core functionality and API ###
	*/
	$.extend($.fn.rating, {
		// Used to append a unique serial number to internal control ID
		// each time the plugin is invoked so same name controls can co-exist
		calls: 0,
		
		focus: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.focus) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
   // focus handler, as requested by focusdigital.co.uk
			if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.focus
		
		blur: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.blur) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
   // blur handler, as requested by focusdigital.co.uk
			if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.blur
		
		fill: function(){ // fill to the current mouse position.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// Reset all stars and highlight them up to this element
			this.rating('drain');
			this.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-hover');
		},// $.fn.rating.fill
		
		drain: function() { // drain all the stars.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// Reset all stars
			control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover');
		},// $.fn.rating.drain
		
		draw: function(){ // set value and stars to reflect current selection
			var control = this.data('rating'); if(!control) return this;
			// Clear all stars
			this.rating('drain');
			// Set control value
			if(control.current){
				control.current.data('rating.input').attr('checked','checked');
				control.current.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-on');
			}
			else
			 $(control.inputs).removeAttr('checked');
			// Show/hide 'cancel' button
			control.cancel[control.readOnly || control.required || control.cancelButton == false ? 'hide':'show']();
			// Add/remove read-only classes to remove hand pointer
			this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly');
		},// $.fn.rating.draw
		
		select: function(value){ // select a value
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// clear selection
			control.current = null;
			// programmatically (based on user input)
			if(typeof value!='undefined'){
			 // select by index (0 based)
				if(typeof value=='number')
 			 return $(control.stars[value]).rating('select');
				// select by literal value (must be passed as a string
				if(typeof value=='string')
					//return 
					$.each(control.stars, function(){
						if($(this).data('rating.input').val()==value) $(this).rating('select');
					});
			}
			else
				control.current = this[0].tagName=='INPUT' ? 
				 this.data('rating.star') : 
					(this.is('.rater-'+ control.serial) ? this : null);
			
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
			// find data for event
			var input = $( control.current ? control.current.data('rating.input') : null );
			// click callback, as requested here: http://plugins.jquery.com/node/1655
			if(control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event
		},// $.fn.rating.select
		
		readOnly: function(toggle, disable){ // make the control read-only (still submits value)
			var control = this.data('rating'); if(!control) return this;
			// setread-only status
			control.readOnly = toggle || toggle==undefined ? true : false;
			// enable/disable control value submission
			if(disable) $(control.inputs).attr("disabled", "disabled");
			else     			$(control.inputs).removeAttr("disabled");
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
		},// $.fn.rating.readOnly
		
		disable: function(){ // make read-only and never submit value
			this.rating('readOnly', true, true);
		},// $.fn.rating.disable
		
		enable: function(){ // make read/write and submit value
			this.rating('readOnly', false, false);
		}// $.fn.rating.select
		
 });
	
	/*--------------------------------------------------------*/
	
	/*
		### Default Settings ###
		eg.: You can override default control like this:
		$.fn.rating.options.cancelText = 'Clear';
	*/
	$.fn.rating.options = { //$.extend($.fn.rating, { options: {
			cancelButton: false,   // show cancel button
			cancelText: 'Cancel Rating',   // advisory title for the 'cancel' link
			cancelValue: '',           // value to submit when user click the 'cancel' link
			split: 0,                  // split the star into how many parts?
			
			// Width of star image in case the plugin can't work it out. This can happen if
			// the jQuery.dimensions plugin is not available OR the image is hidden at installation
			starWidth: 16//,
			
			//NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code!
			//half:     false,         // just a shortcut to control.split = 2
			//required: false,         // disables the 'cancel' button so user can only select one of the specified values
			//readOnly: false,         // disable rating plugin interaction/ values cannot be changed
			//focus:    function(){},  // executed when stars are focused
			//blur:     function(){},  // executed when stars are focused
			//callback: function(){},  // executed when a star is clicked
 }; //} });
	
	/*--------------------------------------------------------*/
	
	/*
		### Default implementation ###
		The plugin will attach itself to file inputs
		with the class 'multi' when the page loads
	*/
	$(function(){
	 $('input[type=radio].star').rating();
	});
	
	
	
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/

/******************************** Meta Data *********************************/
(function($) {$.extend({metadata : {defaults : {type: 'class',name: 'metadata',cre: /({.*})/,single: 'metadata'},setType: function( type, name ){this.defaults.type = type;this.defaults.name = name;},get: function( elem, opts ){var settings = $.extend({},this.defaults,opts);if ( !settings.single.length ) settings.single = 'metadata';var data = $.data(elem, settings.single);if ( data ) return data;data = "{}";if ( settings.type == "class" ) {var m = settings.cre.exec( elem.className );if ( m )data = m[1];} else if ( settings.type == "elem" ) {if( !elem.getElementsByTagName ) return;var e = elem.getElementsByTagName(settings.name);if ( e.length )data = $.trim(e[0].innerHTML);} else if ( elem.getAttribute != undefined ) {var attr = elem.getAttribute( settings.name );if ( attr )data = attr;}if ( data.indexOf( '{' ) <0 )data = "{" + data + "}";data = eval("(" + data + ")");$.data( elem, settings.single, data );return data;}}});$.fn.metadata = function( opts ){return $.metadata.get( this[0], opts );};})(jQuery);

/******************************** pngFix*********************************/
(function($) {jQuery.fn.pngFix = function(settings) {settings = jQuery.extend({blankgif: DOMAIN+'images/blank.gif'}, settings);var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);if (jQuery.browser.msie && (ie55 || ie6)) {jQuery(this).find("img[src$=.png]").each(function() {jQuery(this).attr('width',jQuery(this).width());jQuery(this).attr('height',jQuery(this).height());var prevStyle = '';var strNewHTML = '';var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';if (this.style.border) {prevStyle += 'border:'+this.style.border+';';this.style.border = '';}if (this.style.padding) {prevStyle += 'padding:'+this.style.padding+';';this.style.padding = '';}if (this.style.margin) {prevStyle += 'margin:'+this.style.margin+';';this.style.margin = '';}var imgStyle = (this.style.cssText);strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';strNewHTML += imgStyle+'"></span>';if (prevStyle != ''){strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';}jQuery(this).hide();jQuery(this).after(strNewHTML);});jQuery(this).find("*").each(function(){var bgIMG = jQuery(this).css('background-image');if(bgIMG.indexOf(".png")!=-1){var iebg = bgIMG.split('url("')[1].split('")')[0];jQuery(this).css('background-image', 'none');jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";}});jQuery(this).find("input[src$=.png]").each(function() {var bgIMG = jQuery(this).attr('src');jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';jQuery(this).attr('src', settings.blankgif);});}return jQuery;};})(jQuery);

/*********************** Keyboard Shortcuts *****************************/
(function(jQuery){jQuery.fn.__bind__=jQuery.fn.bind;jQuery.fn.__unbind__=jQuery.fn.unbind;jQuery.fn.__find__=jQuery.fn.find;var hotkeys={version:'0.7.9',override:/keypress|keydown|keyup/g,triggersMap:{},specialKeys:{27:'esc',9:'tab',32:'space',13:'return',8:'backspace',145:'scroll',20:'capslock',144:'numlock',19:'pause',45:'insert',36:'home',46:'del',35:'end',33:'pageup',34:'pagedown',37:'left',38:'up',39:'right',40:'down',109:'-',112:'f1',113:'f2',114:'f3',115:'f4',116:'f5',117:'f6',118:'f7',119:'f8',120:'f9',121:'f10',122:'f11',123:'f12',191:'/'},shiftNums:{"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"},newTrigger:function(type,combi,callback){var result={};result[type]={};result[type][combi]={cb:callback,disableInInput:false};return result;}};hotkeys.specialKeys=jQuery.extend(hotkeys.specialKeys,{96:'0',97:'1',98:'2',99:'3',100:'4',101:'5',102:'6',103:'7',104:'8',105:'9',106:'*',107:'+',109:'-',110:'.',111:'/'});jQuery.fn.find=function(selector){this.query=selector;return jQuery.fn.__find__.apply(this,arguments);};jQuery.fn.unbind=function(type,combi,fn){if(jQuery.isFunction(combi)){fn=combi;combi=null;}if(combi&&typeof combi==='string'){var selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();var hkTypes=type.split(' ');for(var x=0;x<hkTypes.length;x++){delete hotkeys.triggersMap[selectorId][hkTypes[x]][combi];}}return this.__unbind__(type,fn);};jQuery.fn.bind=function(type,data,fn){var handle=type.match(hotkeys.override);if(jQuery.isFunction(data)||!handle){return this.__bind__(type,data,fn);}else{var result=null,pass2jq=jQuery.trim(type.replace(hotkeys.override,''));if(pass2jq){result=this.__bind__(pass2jq,data,fn);}if(typeof data==="string"){data={'combi':data};}if(data.combi){for(var x=0;x<handle.length;x++){var eventType=handle[x];var combi=data.combi.toLowerCase(),trigger=hotkeys.newTrigger(eventType,combi,fn),selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();trigger[eventType][combi].disableInInput=data.disableInInput;if(!hotkeys.triggersMap[selectorId]){hotkeys.triggersMap[selectorId]=trigger;}else if(!hotkeys.triggersMap[selectorId][eventType]){hotkeys.triggersMap[selectorId][eventType]=trigger[eventType];}var mapPoint=hotkeys.triggersMap[selectorId][eventType][combi];if(!mapPoint){hotkeys.triggersMap[selectorId][eventType][combi]=[trigger[eventType][combi]];}else if(mapPoint.constructor!==Array){hotkeys.triggersMap[selectorId][eventType][combi]=[mapPoint];}else{hotkeys.triggersMap[selectorId][eventType][combi][mapPoint.length]=trigger[eventType][combi];}this.each(function(){var jqElem=jQuery(this);if(jqElem.attr('hkId')&&jqElem.attr('hkId')!==selectorId){selectorId=jqElem.attr('hkId')+";"+selectorId;}jqElem.attr('hkId',selectorId);});result=this.__bind__(handle.join(' '),data,hotkeys.handler)}}return result;}};hotkeys.findElement=function(elem){if(!jQuery(elem).attr('hkId')){if(jQuery.browser.opera||jQuery.browser.safari){while(!jQuery(elem).attr('hkId')&&elem.parentNode){elem=elem.parentNode;}}}return elem;};hotkeys.handler=function(event){var target=hotkeys.findElement(event.currentTarget),jTarget=jQuery(target),ids=jTarget.attr('hkId');if(ids){ids=ids.split(';');var code=event.which,type=event.type,special=hotkeys.specialKeys[code],character=!special&&String.fromCharCode(code).toLowerCase(),shift=event.shiftKey,ctrl=event.ctrlKey,alt=event.altKey||event.originalEvent.altKey,mapPoint=null;for(var x=0;x<ids.length;x++){if(hotkeys.triggersMap[ids[x]][type]){mapPoint=hotkeys.triggersMap[ids[x]][type];break;}}if(mapPoint){var trigger;if(!shift&&!ctrl&&!alt){trigger=mapPoint[special]||(character&&mapPoint[character]);}else{var modif='';if(alt)modif+='alt+';if(ctrl)modif+='ctrl+';if(shift)modif+='shift+';trigger=mapPoint[modif+special];if(!trigger){if(character){trigger=mapPoint[modif+character]||mapPoint[modif+hotkeys.shiftNums[character]]||(modif==='shift+'&&mapPoint[hotkeys.shiftNums[character]]);}}}if(trigger){var result=false;for(var x=0;x<trigger.length;x++){if(trigger[x].disableInInput){var elem=jQuery(event.target);if(jTarget.is("input")||jTarget.is("textarea")||jTarget.is("select")||elem.is("input")||elem.is("textarea")||elem.is("select")){return true;}}result=result||trigger[x].cb.apply(this,[event]);}return result;}}}};window.hotkeys=hotkeys;return jQuery;})(jQuery);

/******************************** Quicksearch *********************************/
jQuery.fn.liveUpdate = function(list){list = jQuery(list);if ( list.length ) {var rows = list.children('li'),cache = rows.map(function(){ return this.innerHTML.toLowerCase(); });this.keyup(filter).keyup().parents('form').submit(function(){return false;});}return this;function filter(){var classes = jQuery(this).attr('class');if(str_replace('default','',classes) == classes) {var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];if ( !term ) {rows.show();} else {rows.hide();cache.each(function(i){var score = this.score(term);if (score > 0) { scores.push([score, i]); }});jQuery.each(scores.sort(function(a, b){return b[0] - a[0];}), function(){jQuery(rows[ this[1] ]).show(); });}}}};

/*********************** Silverlight *****************************/
String.prototype.score = function(abbreviation,offset) {offset = offset || 0; if(abbreviation.length == 0) return 0.9;if(abbreviation.length > this.length) return 0.0;for (var i = abbreviation.length; i > 0; i--) {var sub_abbreviation = abbreviation.substring(0,i); var index = this.indexOf(sub_abbreviation); if(index < 0) continue;if(index + abbreviation.length > this.length + offset) continue;var next_string = this.substring(index+sub_abbreviation.length); var next_abbreviation = null;if(i >= abbreviation.length) next_abbreviation = '';else next_abbreviation = abbreviation.substring(i); var remaining_score = next_string.score(next_abbreviation,offset+index);if (remaining_score > 0) { var score = this.length-next_string.length;if(index != 0) { var j = 0; var c = this.charCodeAt(index-1); if(c==32 || c == 9) { for(var j=(index-2); j >= 0; j--) { c = this.charCodeAt(j);score -= ((c == 32 || c == 9) ? 1 : 0.15);}} else score -= index; } score += remaining_score * next_string.length;score /= this.length; return score;}}return 0.0;}

/********************************** Add This ************************************/
/* (c) 2008, 2009 Add This, LLC */
if(!window._ate){var _atd="www.addthis.com/",_atr="//s7.addthis.com/",_euc=encodeURIComponent,_duc=decodeURIComponent,_atu="undefined",_atc={dr:0,ver:250,loc:0,enote:"",cwait:500,tamp:-1,samp:0.01,camp:1,vamp:1,addr:-1,addt:1,xfl:!!window.addthis_disable_flash,abf:!!window.addthis_do_ab};(function(){try{var I=window.location;if(I.protocol.indexOf("file")===0){_atr="http:"+_atr}if(I.hostname.indexOf("localhost")!=-1){_atc.loc=1}}catch(M){}var L=navigator.userAgent.toLowerCase(),N=document,u=window,t=u.addEventListener,h=u.attachEvent,J=N.location,P={win:/windows/.test(L),chr:/chrome/.test(L),iph:/iphone/.test(L),saf:/safari/.test(L),web:/webkit/.test(L),opr:/opera/.test(L),msi:(/msie/.test(L))&&!(/opera/.test(L)),ffx:/firefox/.test(L),ff2:/firefox\/2/.test(L),ie6:/msie 6.0/.test(L),ie7:/msie 7.0/.test(L),mod:-1},n={isBound:false,isReady:false,readyList:window.addthis_onload||[],onReady:function(){if(!n.isReady){n.isReady=true;var a=n.readyList;for(var b=0;b<a.length;b++){a[b].call(window)}n.readyList=[]}},addLoad:function(a){var b=u.onload;if(typeof u.onload!="function"){u.onload=a}else{u.onload=function(){if(b){b()}a()}}},bindReady:function(){if(A.isBound){return}A.isBound=true;if(N.addEventListener&&!P.opr){N.addEventListener("DOMContentLoaded",A.onReady,false)}var a=window.addthis_product;if(a&&a.indexOf("f")>-1){A.onReady();return}if(P.msi&&window==top){(function(){if(A.isReady){return}try{N.documentElement.doScroll("left")}catch(c){setTimeout(arguments.callee,0);return}A.onReady()})()}if(P.opr){N.addEventListener("DOMContentLoaded",function(){if(A.isReady){return}for(var c=0;c<N.styleSheets.length;c++){if(N.styleSheets[c].disabled){setTimeout(arguments.callee,0);return}}A.onReady()},false)}if(P.saf){var b;(function(){if(A.isReady){return}if(N.readyState!="loaded"&&N.readyState!="complete"){setTimeout(arguments.callee,0);return}if(b===undefined){var c=N.gn("link");for(var d=0;d<c.length;d++){if(c[d].getAttribute("rel")=="stylesheet"){b++}}var e=N.gn("style");b+=e.length}if(N.styleSheets.length!=b){setTimeout(arguments.callee,0);return}A.onReady()})()}A.addLoad(A.onReady)},append:function(b,a){A.bindReady();if(A.isReady){b.call(window,[])}else{A.readyList.push(function(){return b.call(window,[])})}}},A=n,v=function(q,l,p,c){if(!q){return p}if(q instanceof Array){for(var e=0,a=q.length,b=q[0];e<a;b=q[++e]){p=l.call(c||q,p,b,e,q)}}else{for(var d in q){p=l.call(c||q,p,q[d],d,q)}}return p},D=Array.prototype.slice,F=function(b){return D.apply(b,D.call(arguments,1))},E=function(a){return a.replace(/(^\s+|\s+$)/g,"")},j=function(b,a){return v(b,function(e,d,c){c=E(c);if(c){e.push(_euc(c)+"="+_euc(E(d)))}return e},[]).join(a||"&")},g=function(b,a){return v((b||"").split(a||"&"),function(i,l){var e=l.split("="),d=E(_duc(e[0])),c=E(_duc(e.slice(1).join("=")));if(d){i[d]=c}return i},{})},f={vst:[],rev:"$Rev: 71445 $",bro:P,clck:1,show:1,dl:J,camp:_atc.camp-Math.random(),samp:_atc.samp-Math.random(),vamp:_atc.vamp-Math.random(),tamp:_atc.tamp-Math.random(),ab:"-",scnt:1,seq:1,inst:1,wait:500,tmo:null,cvt:[],svt:[],sttm:new Date().getTime(),max:268435455,pix:"tev",sid:0,sub:!!window.at_sub,uid:null,oot:null,swf:"//bin.clearspring.com/at/v/1/button1.6.swf",evu:"//e1.clearspring.com/at/",spt:"static/r07/widget11.png",ifpp:null,gat:function(){},com:function(a){if(window.parent&&window.postMessage){window.parent.postMessage(a,"*")}else{f.ifm(a)}},ifwn:function(){var b=f;try{b.rec(b.sifr.contentWindow.name)}catch(c){}},ifm:function(b){if(addthis_wpl){var c=(addthis_wpl.split("#"))[0];window.parent.location.href=c+"#at"+b}return false},hash:window.location.hash,ifp:function(){var c=f,b=window.location.hash,i=0;if(b&&b.indexOf("#at")>-1){b=b.substr(3).split(";");for(var e in b){var d=b[e].length>3?b[e].substr(0,3):null;switch(d){case"ssh":i=1;c.ssh(b[e].substr(4));break;case"uid":i=1;c.asetup(b[e].substr(4));break}}if(i){if(!c.hash.length||c.hash==""){c.hash="#"}window.location.hash=c.hash}}if(c.gssh&&c.guid){clearInterval(c.ifpp)}},pmh:function(a){if(a.origin.slice(-12)==".addthis.com"){f.rec(a.data)}},rec:function(d){if(!d){return}var e=g(d),b=f,c=b.sifr;if(e.ssh){b.ssh(e.ssh)}if(e.uid){b.asetup(e.uid)}if(c&&c.parentNode){c.parentNode.removeChild(c);b.sifr=null}},ssh:function(a){f.gssh=1;window.addthis_ssh=_duc(a)},mun:function(c){var a=291;if(c){for(var b=0;b<c.length;b++){a=(a*(c.charCodeAt(b)+b)+3)&1048575}}return(a&16777215).toString(32)},ibt:function(){if(f.bti){return f.bti}var a=(window.addthis_product||"men").substr(0,3),b=a=="bkm"||a=="fct"||a=="fxe";if(b){f.bti=b}return b},off:function(){return Math.floor((new Date().getTime()-f.sttm)/100).toString(16)},ran:function(){return Math.floor(Math.random()*4294967295).toString(36)},srd:function(){if(f.dr){return"&pre="+_euc(f.dr)}else{return""}},cst:function(a){return"CXNID=2000001.521545608054043907"+(a||2)+"NXC"},imgz:[],hrr:function(c){if(c&&c.urls&&c.urls instanceof Array){for(var b=0;b<c.urls.length;b++){var a=new Image();f.imgz.push(a);a.src=c.urls[b]}}},img:function(l,q){if(!window.at_sub&&!_atc.xtr){var d=f,p=d.dr,b=((d.rev||"").split(" "));if(p){p=p.split("?").shift().split("http://").pop().split("https://").pop();if(p.length>25){p=p.substr(0,25)}}var e=new Image();d.imgz.push(e);e.src=_atr+"live/t00/"+l+".gif?"+(d.uid!==null?"uid="+d.uid+"&":"")+d.ran()+"&"+d.cst(q)+(d.pub()?"&pub="+d.pub():"")+(p?"&dr="+_euc(p):"")+(b.length>1?"&rev="+b[1]:"")}},cuid:function(){return(f.sttm&f.max).toString(16)+(Math.floor(Math.random()*f.max)).toString(16)},ssid:function(){if(f.sid===0){f.sid=f.cuid()}return f.sid},sev:function(b,a){f.pix="sev-"+(typeof(b)!=="number"?_euc(b):b);f.svt.push(b+";"+f.off());if(a===1){f.xmi(true)}else{f.sxm(true)}},cev:function(b,a){f.pix="cev-"+_euc(b);f.cvt.push(_euc(b)+"="+_euc(a)+";"+f.off());f.sxm(true)},sxm:function(a){if(f.tmo!==null){clearTimeout(f.tmo)}if(a){f.tmo=f.sto("_ate.xmi(false)",f.wait)}},sto:function(b,a){return setTimeout(b,a)},sta:function(){var b=f;return"AT-"+(b.pub()?b.pub():"unknown")+"/-/"+b.ab+"/"+b.ssid()+"/"+(b.seq++)+(b.uid!==null?"/"+b.uid:"")},xred:function(){var q=window,p=f,r=0,d=N.referer||N.referrer||"",b=J?J.href:null,l=0;if(p.camp>=0&&b&&J&&J.protocol&&(d.indexOf(".com")>-1)&&(J.protocol.indexOf("https")==-1)){if(d&&d.match(/ws\/results\/(Web|Images|Video|News)/)){l=1}else{if(d.indexOf(".com/search")>-1){var s=d.split("?").pop().split("&");for(var e=0;e<s.length;e++){if(s[e].indexOf("q=")===0||s[e].indexOf("p=")===0||s[e].indexOf("query")===0||s[e].indexOf("qry")===0||s[e].indexOf("text")===0){l=1;break}}}}if(!_atc.xtr&&!_atc.xck&&l&&p.mun(p.pub())!=="mu2r"){var c=N.ce("script");c.src="//cf.addthis.com/red/p.json?callback=_ate.hrr"+(p.pub()?"&pub="+p.pub():"")+(p.uid&&p.uid!=="anonymous"?"&uid="+_euc(p.uid):"")+"&url="+_euc(b)+"&ref="+_euc((N.referer||N.referrer));N.gn("head")[0].appendChild(c)}}},xld:function(){var b=f;if(!b.xld_p){b.xld_p=1;if(b.samp>=0&&!b.sub){b.sev("20");b.cev("plo",Math.round(1/_atc.samp));if(b.dr){b.cev("pre",b.dr)}}b.xred();b.img(_atc.ver+"lo","2")}},xmi:function(r){var b=f,p=b.dl?b.dl.hostname:"";if(!b.uid){b.dck("X"+b.cuid())}else{b.coo()}if(b.cvt.length+b.svt.length>0){b.sxm(false);if(b.seq===1){b.cev("pin",b.inst)}if(_atc.xtr){return}if(p.indexOf(".gov")>-1||p.indexOf(".mil")>-1){_atc.xck=1}var s=b.pix+"-"+b.ran()+".png?ev="+f.sta()+"&se="+b.svt.join(",")+"&ce="+b.cvt.join(",")+(_atc.xck?"&xck=1":""),e=b.evu+s;b.cvt=[];b.svt=[];if(r){var q=document,l=q.ce("iframe");l.id="_atf";l.src=e;f.opp(l.style);q.body.appendChild(l);l=q.getElementById("_atf")}else{var c=new Image();b.imgz.push(c);c.src=e}}},loc:function(){return _atc.loc},opp:function(a){a.width=a.height="1px";a.position="absolute";a.zIndex=100000},pub:function(){return _euc(window.addthis_config&&addthis_config.username?addthis_config.username:(window.addthis_pub||""))},plo:[],lad:function(a){f.plo.push(a)},lng:function(a){var b=document;if(a&&(a.toLowerCase()).indexOf("en")!==0&&!f.pll){f.pll=f.ajs("static/r07/lang02.js")}},ajs:function(a){var b=N.ce("script");b.src=_atr+a;N.gn("head")[0].appendChild(b);return b},jlo:function(){try{var p=document,b=f,l=(window.addthis_language||addthis_config.ui_language||(b.bro.msi?navigator.userLanguage:navigator.language));b.lng(l);if(!b.pld){if(b.bro.ie6){var c=new Image();b.imgz.push(c);c.src=_atr+b.spt;if(window.addthis_feed){c=new Image();b.imgz.push(c);c.src=_atr+"static/r05/feed00.gif"}}b.pld=b.ajs("static/r07/menu39.js")}}catch(i){}},igv:function(a,b){if(!u.addthis_share){u.addthis_share={}}if(!addthis_share.url){u.addthis_share.url=u.addthis_url||a}if(!addthis_share.title){u.addthis_share.title=u.addthis_title||b}if(!u.addthis_config){u.addthis_config={username:u.addthis_pub}}else{if(addthis_config.data_use_flash===false){_atc.xfl=1}if(addthis_config.data_use_cookies===false){_atc.xck=1}}},lod:function(y){try{var S=window,ah=f,s=ah.bro.msi,c=0,W=N.referer||N.referrer||"",V=J?J.href:null,ad=J.hostname,ag=V?V.indexOf("sms_ss"):-1,ae=((y===1||S.addthis_load_flash)&&!_atc.abf),Z=((S.addthis_language||(S.addthis_config?S.addthis_config.ui_language:null)||(ah.bro.msi?navigator.userLanguage:navigator.language)).split("-")).shift(),r=(J.href.indexOf(_atr)==-1)&&!ah.bro.ie6&&!ah.bro.ie7,aa=N.gn("link"),p=_atr+"static/r07/sh09.html",x="_ate.ifwn()",q,R;if(!S.postMessage){var U=N.gn("img");for(var ab=0;ab<U.length;ab++){if(U[ab].src.split("//").pop().indexOf(ad)==0){q=U[ab].src;break}}}if(r&&(!_atc.xic||(S.postMessage||ah.bro.msi))){if(!s){R=N.ce("iframe")}else{var T=N.ce("div");T.style.visibility="hidden";ah.opp(T.style);N.body.insertBefore(T,N.body.firstChild);T.innerHTML='<iframe id="_atssh" width="1" height="1" name="_atssh" '+(!S.postMessage?'onload="'+x+'" ':"")+">";R=N.getElementById("_atssh")}}for(var ab=0;ab<aa.length;ab++){var Y=aa[ab];if(Y.rel&&Y.rel=="canonical"&&Y.href){V=Y.href}}ah.igv(V,N.title||"");ah.gov();ah.dr=W;var d=(ah.swf&&!_atc.xfl&&!(ah.loc())&&!_atc.abf&&(ae||ah.uid===null||(ah.uid!=="anonymous"&&ah.oot&&((new Date()).getTime()-ah.oot>60480000))));p+="#swfp="+(d&&s?1:0);if(!s&&d){var b=function(e,l,a){var i=N.ce("param");i.name=l;i.value=a;e.appendChild(i)},T=N.ce("div"),X=N.ce("object");T.id="atffc";ah.opp(T.style);X.id="atff";X.data=ah.swf;X.width=X.height="1px";X.quality="high";X.type="application/x-shockwave-flash";b(X,"wmode","transparent");b(X,"allowScriptAccess","always");T.appendChild(X);N.body.insertBefore(T,N.body.firstChild)}if(r&&R){R.id="_atssh";ah.opp(R.style);R.frameborder=R.style.border=0;R.style.top=R.style.left=0;if(S.postMessage){R.src=p;if(s){S.attachEvent("onmessage",ah.pmh)}else{S.addEventListener("message",ah.pmh,false)}R=N.body.appendChild(R)}else{if(q&&!_atc.xic&&ah.bro.msi&&window==top){R.onload=x;R.src=q;R=N.body.appendChild(R);R.src=p+"&wpl="+_euc(q)}}ah.sifr=R}if(!ae){if(d){ah.uoo();if(ah.bro.ie6||ah.bro.ie7){ah.sto("if (_ate.xld) _ate.xld()",5000)}else{ah.sto("_ate.xld()",5000)}}else{ah.guid=1;ah.xld()}if(ag>-1&&V.indexOf(_atd+"book")==-1){var ac=V.substr(ag);ac=ac.split("&").shift().split("#").shift().split("=").pop();if(ah.vamp>=0&&!ah.sub&&ac.length){ah.cev("plv",Math.round(1/_atc.vamp));ah.cev("rsc",ac)}}}if(ah.plo.length>0){ah.jlo()}}catch(af){}},kck:function(a){var b=document;if(b.cookie){b.cookie=a+"= ; expires=Tue, 31 Mar 2009 05:47:11 UTC; path=/"}},rck:function(e){var p=document;if(p.cookie){var b=p.cookie.split(";");for(var l=0;l<b.length;l++){var q=b[l],a=q.indexOf(e+"=");if(a>=0){return q.substring(a+(e.length+1))}}}return},uoo:function(){f.sck("_csoot",(new Date().getTime()))},coo:function(a){if(f.uid=="anonymous"&&!f.oot){f.xck=1;f.uoo()}},dck:function(a){f.uid=a;f.sck("_csuid",a);f.coo()},gov:function(){var b=f.dl?f.dl.hostname:"";if(b.indexOf(".gov")>-1||b.indexOf(".mil")>-1){_atc.xck=1;_atc.xfl=1}var c=f.pub(),a=["usarmymedia","govdelivery"];for(K in a){if(c==a[K]){_atc.xck=1;_atc.xfl=1;break}}},sck:function(b,a,c){f.gov();if(!_atc.xck){N.cookie=b+"="+a+(!c?"; expires=Wed, 04 Oct 2028 03:19:53 GMT":"")+"; path=/"}},asetup:function(b){var c=f;try{if(!c.guid){c.guid=1;if(b!==null&&b!==_atu){c.dck(b)}c.xld()}}catch(d){}return b},ao:function(b,i,e,c,d,a){f.lad(["open",b,i,e,c,d,a]);f.jlo();return false},ac:function(){},as:function(b,c,a){f.lad(["send",b,c,a]);f.jlo()}},Q=f;u._ate=Q;u._adr=A;N.ce=N.createElement;N.gn=N.getElementsByTagName;A.bindReady();if(!_atc.ost){if(!u.addthis_conf){u.addthis_conf={}}for(var K in addthis_conf){_atc[K]=addthis_conf[K]}_atc.ost=1}A.append(Q.lod);if(N.cookie){var m=N.cookie.split(";");for(var K=0;K<m.length;K++){var O=m[K],o=O.indexOf("_csuid="),k=O.indexOf("_csoot=");if(o>=0){f.uid=O.substring(o+7)}else{if(k>=0){f.oot=O.substring(k+7)}}}}try{var I=N.ce("link");I.rel="stylesheet";I.type="text/css";I.href=_atr+"static/r07/widget24.css";I.media="all";N.gn("head")[0].appendChild(I)}catch(M){}var H=N.gn("script"),z=H[H.length-1],B=z.src.indexOf("#")>-1?z.src.replace(/^[^\#]+\#?/,""):z.src.replace(/^[^\?]+\??/,""),C=g(B);if(C.pub){u.addthis_pub=_duc(C.pub)}else{if(C.username){u.addthis_pub=_duc(C.username)}}if(u.addthis_pub&&u.addthis_config){u.addthis_config.username=u.addthis_pub}if(C.domready){_atc.dr=1}try{if(_atc.ver===120){var G="atb"+u._ate.cuid();N.write('<span id="'+G+'"></span>');u._ate.igv();u._ate.lad(["span",G,addthis_share.url||"[url]",addthis_share.title||"[title]"])}if(u.addthis_clickout){f.lad(["cout"])}}catch(M){}})();function addthis_open(b,f,e,c,d,a){if(typeof d=="string"){d=null}return _ate.ao(b,f,e,c,d,a)}function addthis_close(){_ate.ac()}function addthis_sendto(b,c,a){_ate.as(b,c,a);return false}if(_atc.dr){_adr.onReady()}}else{_ate.inst++}if(_atc.abf){addthis_open(document.getElementById("ab"),"emailab",window.addthis_url||"[URL]",window.addthis_title||"[TITLE]")};if(!window.addthis||window.addthis.nodeType!==undefined){window.addthis={ost:0,cache:{},plo:[],links:[],ems:[],button:function(){this.plo.push({call:"button",args:arguments})},toolbox:function(){this.plo.push({call:"toolbox",args:arguments})},update:function(){this.plo.push({call:"update",args:arguments})}}}_adr.append((function(){if(!window.addthis.ost){var d=document,u=undefined,w=window,unaccent=function(s){if(s.indexOf("&")>-1){s=s.replace(/&([aeiou]).+;/g,"$1")}return s},customServices={},globalConfig=w.addthis_config,globalShare=w.addthis_share,upConfig={},upShare={},body=d.gn("body").item(0),mrg=function(o,n){if(n&&o!==n){for(var k in n){if(o[k]===u){o[k]=n[k]}}}},addga=function(o,ss,au){var oldclick=o.onclick||function(){};if(o.conf.data_ga_tracker||addthis_config.data_ga_tracker||o.conf.data_ga_property||addthis_config.data_ga_property){o.onclick=function(){_ate.gat(ss,au,o.conf,o.share);oldclick()}}},rpl=function(o,n){var r={};for(var k in o){if(n[k]){r[k]=n[k]}else{r[k]=o[k]}}return r},addthis=window.addthis,genieu=function(share){return"mailto:?subject="+(share.title?share.title:"%20")+"&body="+(share.title?share.title+"%0D%0A":"")+(share.url)+"%0D%0A%0D%0AShared via AddThis.com"},gebcn=function(oParent,tag,className,allowSuffix,optimizable){tag=tag.toUpperCase();var els=(oParent==body&&addthis.cache[tag]?addthis.cache[tag]:(oParent||body).getElementsByTagName(tag)),rv=[],i,o;if(oParent==body){addthis.cache[tag]=els}if(optimizable){for(i=0;i<els.length;i++){o=els[i];if(o.className.indexOf(className)>-1){rv.push(o)}}}else{className=className.replace(/\-/g,"\\-");var rx=new RegExp("(^|\\s)"+className+(allowSuffix?"\\w*":"")+"(\\s|$)");for(i=0;i<els.length;i++){o=els[i];if(rx.test(o.className)){rv.push(o)}}}return(rv)},s_list={aim:"AIM",kirtsy:"kIRTSY",linkagogo:"Link-a-Gogo",meneame:"Men&eacute;ame",misterwong:"Mister Wong",myaol:"myAOL",myspace:"MySpace",yahoobkm:"Y! Bookmarks",typepad:"TypePad",wordpress:"WordPress"},b_title={email:"Email",desktopemail:"Email",print:"Print",favorites:"Save to Favorites",twitter:"Tweet This",digg:"Digg This"},json={services_custom:1},nosend={more:1,email:1,desktopemail:1},nowindow={email:1,desktopemail:1,print:1,more:1,favorites:1},a_config=["username","services_custom","services_custom_name","services_custom_url","services_custom_title","services_exclude","services_compact","services_expanded","ui_click","ui_hide_embed","ui_delay","ui_hover_direction","ui_language","ui_offset_top","ui_offset_left","ui_header_color","ui_header_background","ui_use_embeddable_services_beta","ui_icons","ui_cobrand","data_use_flash","data_use_cookies","data_track_linkback"],a_share=["url","title","templates","email_template","email_vars","html","swfurl","width","height","screenshot","author","description","content"],getElementsByClassName=d.getElementsByClassname||gebcn,_svcurl=function(config,share){var sv=config.services instanceof Array?config.services[0]:config.services||"";return"http://"+_atd+"bookmark.php?v="+_atc.ver+"&pub="+_euc(_ate.pub())+"&s="+sv+(share.url?"&url="+_euc(share.url):"")+(share.title?"&title="+_euc(share.title):"")+"&tt=0"},_select=function(what){if(typeof what=="string"){var c=what.substr(0,1);if(c=="#"){what=d.getElementById(what.substr(1))}else{if(c=="."){what=getElementsByClassName(body,"*",what.substr(1))}else{}}}if(!(what instanceof Array)){what=[what]}return what},_parseAttributes=function(el,attrs,overrides,childWins){var rv={};overrides=overrides||{};for(var i=0;i<attrs.length;i++){if(overrides[attrs[i]]&&!childWins){rv[attrs[i]]=overrides[attrs[i]]}else{if(el){var p="addthis:"+attrs[i],v=el.getAttribute?el.getAttribute(p)||el[p]:el[p];if(v){rv[attrs[i]]=v}else{if(overrides[attrs[i]]){rv[attrs[i]]=overrides[attrs[i]]}}if(rv[attrs[i]]==="true"){rv[attrs[i]]=true}else{if(rv[attrs[i]]==="false"){rv[attrs[i]]=false}}}}if(rv[attrs[i]]!==undefined&&json[attrs[i]]&&(typeof rv[attrs[i]]=="string")){eval("var e = "+rv[attrs[i]]);rv[attrs[i]]=e}}return rv},_processCustomServices=function(conf){var acs=(conf||{}).services_custom;if(!acs){return}if(!(acs instanceof Array)){acs=[acs]}for(var i=0;i<acs.length;i++){var service=acs[i];if(service.name&&service.icon&&service.url){service.code=service.url=service.url.replace(/ /g,"");if(service.code.indexOf("http")===0){service.code=service.code.substr((service.code.indexOf("https")===0?8:7))}service.code=service.code.split("?").shift().split("/").shift().toLowerCase();customServices[service.code]=service}}},_getCustomService=function(ss,conf){return customServices[ss]||{}},_getATtributes=function(el,config,share,childWins){var rv={conf:config||{},share:share||{}};rv.conf=_parseAttributes(el,a_config,config,childWins);rv.share=_parseAttributes(el,a_share,share,childWins);return rv},_render=function(what,conf,attrs){if(what){conf=conf||{};attrs=attrs||{};var config=conf.conf||globalConfig,share=conf.share||globalShare;var onmouseover=attrs.onmouseover,onmouseout=attrs.onmouseout,onclick=attrs.onclick,internal=attrs.internal,ss=attrs.singleservice;if(ss){config.product="tbx-"+_atc.ver;if(onclick===u){onclick=nosend[ss]?function(el,config,share){var s=rpl(share,upShare);return addthis_open(el,ss,s.url,s.title,rpl(config,upConfig),s)}:nowindow[ss]?function(el,config,share){var s=rpl(share,upShare);return addthis_sendto(ss,rpl(config,upConfig),s)}:null}}else{if(!attrs.noevents){if(!attrs.nohover&&(!config||!config.ui_click)){if(onmouseover===u){onmouseover=function(el,config,share){return addthis_open(el,"",null,null,config,share)}}if(onmouseout===u){onmouseout=function(el){return addthis_close()}}if(onclick===u){onclick=function(el,config,share){return addthis_sendto("more",config,share)}}}else{if(!config||!config.ui_click){if(onclick===u){onclick=function(el,config,share){return addthis_open(el,"more")}}}else{if(onclick===u){onclick=function(el,config,share){return addthis_open(el,"",null,null,config,share)}}}}}}what=_select(what);for(var i=0;i<what.length;i++){var o=what[i],oattr=_getATtributes(o,config,share,true)||{};mrg(oattr.conf,globalConfig);mrg(oattr.share,globalShare);o.conf=oattr.conf;o.share=oattr.share;if(o.conf.ui_language){_ate.lng(o.conf.ui_language)}_processCustomServices(o.conf);if(onmouseover){o.onmouseover=function(){return onmouseover(this,this.conf,this.share)}}if(onmouseout){o.onmouseout=function(){return onmouseout(this)}}if(onclick){o.onclick=function(){return onclick(this,this.conf,this.share)}}if(o.tagName.toLowerCase()=="a"){if(ss){var customService=_getCustomService(ss,o.conf);o.conf.product="tbx-"+_atc.ver;if(customService&&customService.code&&customService.icon){if(o.firstChild&&o.firstChild.className.indexOf("at300bs")>-1){o.firstChild.style.background="url("+customService.icon+") no-repeat top left"}}if((_ate.bro.ffx||_ate.bro.saf||_ate.bro.chr||_ate.bro.iph)&&!nowindow[ss]){var template=o.share.templates&&o.share.templates[ss]?o.share.templates[ss]:"",url=o.share.url||addthis_share.url,title=o.share.title||addthis_share.title,swfurl=o.share.swfurl||addthis_share.swfurl,width=o.share.width||addthis_share.width,height=o.share.height||addthis_share.height,description=o.share.description||addthis_share.description,screenshot=o.share.screenshot||addthis_share.screenshot;o.href="//"+_atd+"bookmark.php?pub="+_euc(addthis_config.username||o.conf.username||_ate.pub())+"&v="+_atc.ver+"&source=tbx-"+_atc.ver+"&tt=0&s="+ss+"&url="+_euc(url||"")+"&title="+_euc(title||"")+"&content="+_euc(o.share.content||addthis_share.content||"")+(template?"&template="+_euc(template):"")+(o.conf.data_track_linkback?"&sms_ss=1":"")+"&lng="+((window.addthis_language||o.conf.ui_language||navigator.language||"xy").split("-").shift())+(description?"&description="+_euc(description):"")+(swfurl?"&swfurl="+_euc(swfurl):"")+(width?"&width="+_euc(width):"")+(height?"&height="+_euc(height):"")+(screenshot?"&screenshot="+_euc(screenshot):"")+(customService&&customService.url?"&acn="+_euc(customService.name)+"&acc="+_euc(customService.code)+"&acu="+_euc(customService.url):"")+(_ate.uid?"&uid="+_euc(_ate.uid):"");addga(o,ss,url);o.target="_blank";addthis.links.push(o)}else{if(!nowindow[ss]){o.onclick=function(){return addthis_sendto.call(this,ss,rpl(this.conf,upConfig),rpl(this.share,upShare))}}else{if(ss=="desktopemail"||(ss=="email"&&(o.conf.ui_use_mailto||_ate.bro.iph))){o.href=genieu(o.share);addga(o,ss,url);addthis.ems.push(o)}}}if(!o.title){o.title=unaccent(b_title[ss]?b_title[ss]:"Send to "+(s_list[ss]?s_list[ss]:ss.substr(0,1).toUpperCase()+ss.substr(1)))}}}if(internal){var app=internal;if(!o.hasChildNodes()){if(internal=="img"){var img=d.ce("img");img.width=125;img.height=16;img.border=0;img.alt="Share";img.src="//s7.addthis.com/static/btn/v2/lg-share-en.gif";app=img}o.appendChild(app)}}}}},buttons=gebcn(body,"A","addthis_button_",true,true),_renderToolbox=function(collection,config,share,reprocess){for(var i=0;i<collection.length;i++){var b=collection[i];if(b==null){continue}if(reprocess!==false||!b.ost){var config=config||globalConfig,share=share||globalShare,attr=_getATtributes(b,config,share,true),hc=0,a="at300",c=b.className||"",s=c.match(/addthis_button_([\w\.]+)(?:\s|$)/),opts=u,sv=s&&s.length?s[1]:0;if(sv){if(!b.childNodes.length){var sp=d.ce("span");b.appendChild(sp);sp.className=a+"bs at15t_"+sv}else{if(b.childNodes.length==1){var cn=b.childNodes[0];if(cn.nodeType==3){var sp=d.ce("span"),tv=cn.nodeValue;b.insertBefore(sp,cn);sp.className=a+"bs at15t_"+sv}}else{hc=1}}if(sv==="compact"){if(!hc&&c.indexOf(a)==-1){b.className+=" "+a+"m"}}else{if(sv==="expanded"){if(!hc&&c.indexOf(a)==-1){b.className+=" "+a+"m"}opts={nohover:true}}else{if(!hc&&c.indexOf(a)==-1){b.className+=" "+a+"b"}opts={singleservice:sv}}}_render([b],attr,opts);b.ost=1}}}},gat=function(s,au,conf,share){var pageTracker=conf.data_ga_tracker,propertyId=conf.data_ga_property;if(propertyId&&typeof(window._gat)=="object"){pageTracker=_gat._getTracker(propertyId)}if(pageTracker&&typeof(pageTracker)=="object"){var gaUrl=au||(share||{}).url||location.href;if(gaUrl.toLowerCase().replace("https","http").indexOf("http%3a%2f%2f")==0){gaUrl=_duc(gaUrl)}try{pageTracker._trackEvent("addthis",s,gaUrl)}catch(e){try{pageTracker._initData();pageTracker._trackEvent("addthis",s,gaUrl)}catch(e){}}}};_ate.gat=gat;addthis.update=function(which,what,value){if(which=="share"){if(!window.addthis_share){window.addthis_share={}}window.addthis_share[what]=value;upShare[what]=value;for(var i in addthis.links){var o=addthis.links[i],rx=new RegExp("&"+what+"=(.*)&"),ns="&"+what+"="+_euc(value)+"&";o.href=o.href.replace(rx,ns);if(o.href.indexOf(what)==-1){o.href+=ns}}for(var i in addthis.ems){var o=addthis.ems[i];o.href=genieu(addthis_share)}}else{if(which=="config"){if(!window.addthis_config){window.addthis_config={}}window.addthis_config[what]=value;upConfig[what]=value}}};addthis.button=function(what,config,share){_render(what,{conf:config,share:share},{internal:"img"})};addthis.toolbox=function(what,config,share){var toolboxes=_select(what);for(var i=0;i<toolboxes.length;i++){var tb=toolboxes[i],attr=_getATtributes(tb,config,share),sp=d.ce("div"),c=tb.getElementsByTagName("a");if(c){_renderToolbox(c,attr.conf,attr.share)}tb.appendChild(sp);sp.className="atclear"}};addthis.ready=function(){if(this.ost){return}this.ost=1;var a=".addthis_";addthis.toolbox(a+"toolbox");addthis.button(a+"button");_renderToolbox(buttons,null,null,false);for(var i=0;i<this.plo.length;i++){addthis[this.plo[i].call].apply(this,this.plo[i].args)}};window.addthis=addthis;window.addthis.ready()}}));

/********************************** AC_RunActiveContent.js ************************************/
var isIE= (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;function ControlVersion(){var version;var axo;var e;try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");version = axo.GetVariable("$version");} catch (e) {}if (!version){try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");version = "WIN 6,0,21,0";axo.AllowScriptAccess = "always";version = axo.GetVariable("$version");} catch (e) {}}if (!version){try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version = axo.GetVariable("$version");} catch (e) {}}if (!version){try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version = "WIN 3,0,18,0";} catch (e) {}}if (!version){try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");version = "WIN 2,0,0,11";} catch (e) {version = -1;}}return version;}function GetSwfVer(){var flashVer = -1;if (navigator.plugins != null && navigator.plugins.length > 0) {if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;var descArray = flashDescription.split(" ");var tempArrayMajor = descArray[2].split(".");var versionMajor = tempArrayMajor[0];var versionMinor = tempArrayMajor[1];var versionRevision = descArray[3];if (versionRevision == "") {versionRevision = descArray[4];}if (versionRevision[0] == "d") {versionRevision = versionRevision.substring(1);} else if (versionRevision[0] == "r") {versionRevision = versionRevision.substring(1);if (versionRevision.indexOf("d") > 0) {versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));}}var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;}}else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;else if ( isIE && isWin && !isOpera ) {flashVer = ControlVersion();}return flashVer;}function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision){versionStr = GetSwfVer();if (versionStr == -1 ) {return false;} else if (versionStr != 0) {if(isIE && isWin && !isOpera) {tempArray= versionStr.split(" "); tempString= tempArray[1];versionArray= tempString.split(",");} else {versionArray= versionStr.split(".");}var versionMajor= versionArray[0];var versionMinor= versionArray[1];var versionRevision= versionArray[2];if (versionMajor > parseFloat(reqMajorVer)) {return true;} else if (versionMajor == parseFloat(reqMajorVer)) {if (versionMinor > parseFloat(reqMinorVer))return true;else if (versionMinor == parseFloat(reqMinorVer)) {if (versionRevision >= parseFloat(reqRevision))return true;}}return false;}}function AC_AddExtension(src, ext){if (src.indexOf('?') != -1)return src.replace(/\?/, ext+'?');else return src + ext;}function AC_Generateobj(objAttrs, params, embedAttrs) {var str = '';if (isIE && isWin && !isOpera){str += '<object ';for (var i in objAttrs){str += i + '="' + objAttrs[i] + '" ';}str += '>';for (var i in params){str += '<param name="' + i + '" value="' + params[i] + '" /> ';}str += '</object>';}else{str += '<embed ';for (var i in embedAttrs){str += i + '="' + embedAttrs[i] + '" ';}str += '> </embed>';}document.write(str);}function AC_FL_RunContent(){var ret = AC_GetArgs(arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" , "application/x-shockwave-flash");AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);}function AC_SW_RunContent(){var ret = AC_GetArgs(arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000" , null);AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);}function AC_GetArgs(args, ext, srcParamName, classid, mimeType){var ret = new Object();ret.embedAttrs = new Object();ret.params = new Object();ret.objAttrs = new Object();for (var i=0; i < args.length; i=i+2){var currArg = args[i].toLowerCase();switch (currArg){case "classid":break;case "pluginspage":ret.embedAttrs[args[i]] = args[i+1];break;case "src":case "movie":args[i+1] = AC_AddExtension(args[i+1], ext);ret.embedAttrs["src"] = args[i+1];ret.params[srcParamName] = args[i+1];break;case "onafterupdate":case "onbeforeupdate":case "onblur":case "oncellchange":case "onclick":case "ondblclick":case "ondrag":case "ondragend":case "ondragenter":case "ondragleave":case "ondragover":case "ondrop":case "onfinish":case "onfocus":case "onhelp":case "onmousedown":case "onmouseup":case "onmouseover":case "onmousemove":case "onmouseout":case "onkeypress":case "onkeydown":case "onkeyup":case "onload":case "onlosecapture":case "onpropertychange":case "onreadystatechange":case "onrowsdelete":case "onrowenter":case "onrowexit":case "onrowsinserted":case "onstart":case "onscroll":case "onbeforeeditfocus":case "onactivate":case "onbeforedeactivate":case "ondeactivate":case "type":case "codebase":case "id":ret.objAttrs[args[i]] = args[i+1];break;case "width":case "height":case "align":case "vspace": case "hspace":case "class":case "title":case "accesskey":case "name":case "tabindex":ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];break;default:ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];}}ret.objAttrs["classid"] = classid;if (mimeType) ret.embedAttrs["type"] = mimeType;return ret;}