/**
 *
 * Color picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 */
(function ($) {
	var ColorPicker = function () {
		var
			ids = {},
			inAction,
			charMin = 65,
			visible,
			tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
			defaults = {
				eventName: 'click',
				onShow: function () {},
				onBeforeShow: function(){},
				onHide: function () {},
				onChange: function () {},
				onSubmit: function () {},
				color: 'ff0000',
				livePreview: true,
				flat: false
			},
			fillRGBFields = function  (hsb, cal) {
				var rgb = HSBToRGB(hsb);
				$(cal).data('colorpicker').fields
					.eq(1).val(rgb.r).end()
					.eq(2).val(rgb.g).end()
					.eq(3).val(rgb.b).end();
			},
			fillHSBFields = function  (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(4).val(hsb.h).end()
					.eq(5).val(hsb.s).end()
					.eq(6).val(hsb.b).end();
			},
			fillHexFields = function (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(0).val(HSBToHex(hsb)).end();
			},
			setSelector = function (hsb, cal) {
				$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
				$(cal).data('colorpicker').selectorIndic.css({
					left: parseInt(150 * hsb.s/100, 10),
					top: parseInt(150 * (100-hsb.b)/100, 10)
				});
			},
			setHue = function (hsb, cal) {
				$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
			},
			setCurrentColor = function (hsb, cal) {
				$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			setNewColor = function (hsb, cal) {
				$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			keyDown = function (ev) {
				var pressedKey = ev.charCode || ev.keyCode || -1;
				if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
					return false;
				}
				var cal = $(this).parent().parent();
				if (cal.data('colorpicker').livePreview === true) {
					change.apply(this);
				}
			},
			change = function (ev) {
				var cal = $(this).parent().parent(), col;
				if (this.parentNode.className.indexOf('_hex') > 0) {
					cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
				} else if (this.parentNode.className.indexOf('_hsb') > 0) {
					cal.data('colorpicker').color = col = fixHSB({
						h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
						s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
					});
				} else {
					cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
						r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
						g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
					}));
				}
				if (ev) {
					fillRGBFields(col, cal.get(0));
					fillHexFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				}
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
				cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
			},
			blur = function (ev) {
				var cal = $(this).parent().parent();
				cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus')
			},
			focus = function () {
				charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
				$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
				$(this).parent().addClass('colorpicker_focus');
			},
			downIncrement = function (ev) {
				var field = $(this).parent().find('input').focus();
				var current = {
					el: $(this).parent().addClass('colorpicker_slider'),
					max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
					y: ev.pageY,
					field: field,
					val: parseInt(field.val(), 10),
					preview: $(this).parent().parent().data('colorpicker').livePreview					
				};
				$(document).bind('mouseup', current, upIncrement);
				$(document).bind('mousemove', current, moveIncrement);
			},
			moveIncrement = function (ev) {
				ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
				if (ev.data.preview) {
					change.apply(ev.data.field.get(0), [true]);
				}
				return false;
			},
			upIncrement = function (ev) {
				change.apply(ev.data.field.get(0), [true]);
				ev.data.el.removeClass('colorpicker_slider').find('input').focus();
				$(document).unbind('mouseup', upIncrement);
				$(document).unbind('mousemove', moveIncrement);
				return false;
			},
			downHue = function (ev) {
				var current = {
					cal: $(this).parent(),
					y: $(this).offset().top
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upHue);
				$(document).bind('mousemove', current, moveHue);
			},
			moveHue = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(4)
						.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upHue = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upHue);
				$(document).unbind('mousemove', moveHue);
				return false;
			},
			downSelector = function (ev) {
				var current = {
					cal: $(this).parent(),
					pos: $(this).offset()
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upSelector);
				$(document).bind('mousemove', current, moveSelector);
			},
			moveSelector = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(6)
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
						.end()
						.eq(5)
						.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upSelector = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upSelector);
				$(document).unbind('mousemove', moveSelector);
				return false;
			},
			enterSubmit = function (ev) {
				$(this).addClass('colorpicker_focus');
			},
			leaveSubmit = function (ev) {
				$(this).removeClass('colorpicker_focus');
			},
			clickSubmit = function (ev) {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').color;
				cal.data('colorpicker').origColor = col;
				setCurrentColor(col, cal.get(0));
				cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col));
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('colorpickerId'));
				cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
				var pos = $(this).offset();
				var viewPort = getViewport();
				var top = pos.top + this.offsetHeight;
				var left = pos.left;
				if (top + 176 > viewPort.t + viewPort.h) {
					top -= this.offsetHeight + 176;
				}
				if (left + 356 > viewPort.l + viewPort.w) {
					left -= 356;
				}
				cal.css({left: left + 'px', top: top + 'px'});
				if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
					cal.show();
				}
				$(document).bind('mousedown', {cal: cal}, hide);
				return false;
			},
			hide = function (ev) {
				if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			fixHSB = function (hsb) {
				return {
					h: Math.min(360, Math.max(0, hsb.h)),
					s: Math.min(100, Math.max(0, hsb.s)),
					b: Math.min(100, Math.max(0, hsb.b))
				};
			}, 
			fixRGB = function (rgb) {
				return {
					r: Math.min(255, Math.max(0, rgb.r)),
					g: Math.min(255, Math.max(0, rgb.g)),
					b: Math.min(255, Math.max(0, rgb.b))
				};
			},
			fixHex = function (hex) {
				var len = 6 - hex.length;
				if (len > 0) {
					var o = [];
					for (var i=0; i<len; i++) {
						o.push('0');
					}
					o.push(hex);
					hex = o.join('');
				}
				return hex;
			}, 
			HexToRGB = function (hex) {
				var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
				return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
			},
			HexToHSB = function (hex) {
				return RGBToHSB(HexToRGB(hex));
			},
			RGBToHSB = function (rgb) {
				var hsb = {};
				hsb.b = Math.max(Math.max(rgb.r,rgb.g),rgb.b);
				hsb.s = (hsb.b <= 0) ? 0 : Math.round(100*(hsb.b - Math.min(Math.min(rgb.r,rgb.g),rgb.b))/hsb.b);
				hsb.b = Math.round((hsb.b /255)*100);
				if((rgb.r==rgb.g) && (rgb.g==rgb.b)) hsb.h = 0;
				else if(rgb.r>=rgb.g && rgb.g>=rgb.b) hsb.h = 60*(rgb.g-rgb.b)/(rgb.r-rgb.b);
				else if(rgb.g>=rgb.r && rgb.r>=rgb.b) hsb.h = 60  + 60*(rgb.g-rgb.r)/(rgb.g-rgb.b);
				else if(rgb.g>=rgb.b && rgb.b>=rgb.r) hsb.h = 120 + 60*(rgb.b-rgb.r)/(rgb.g-rgb.r);
				else if(rgb.b>=rgb.g && rgb.g>=rgb.r) hsb.h = 180 + 60*(rgb.b-rgb.g)/(rgb.b-rgb.r);
				else if(rgb.b>=rgb.r && rgb.r>=rgb.g) hsb.h = 240 + 60*(rgb.r-rgb.g)/(rgb.b-rgb.g);
				else if(rgb.r>=rgb.b && rgb.b>=rgb.g) hsb.h = 300 + 60*(rgb.r-rgb.b)/(rgb.r-rgb.g);
				else hsb.h = 0;
				hsb.h = Math.round(hsb.h);
				return hsb;
			},
			HSBToRGB = function (hsb) {
				var rgb = {};
				var h = Math.round(hsb.h);
				var s = Math.round(hsb.s*255/100);
				var v = Math.round(hsb.b*255/100);
				if(s == 0) {
					rgb.r = rgb.g = rgb.b = v;
				} else {
					var t1 = v;
					var t2 = (255-s)*v/255;
					var t3 = (t1-t2)*(h%60)/60;
					if(h==360) h = 0;
					if(h<60) {rgb.r=t1;	rgb.b=t2; rgb.g=t2+t3}
					else if(h<120) {rgb.g=t1; rgb.b=t2;	rgb.r=t1-t3}
					else if(h<180) {rgb.g=t1; rgb.r=t2;	rgb.b=t2+t3}
					else if(h<240) {rgb.b=t1; rgb.r=t2;	rgb.g=t1-t3}
					else if(h<300) {rgb.b=t1; rgb.g=t2;	rgb.r=t2+t3}
					else if(h<360) {rgb.r=t1; rgb.g=t2;	rgb.b=t1-t3}
					else {rgb.r=0; rgb.g=0;	rgb.b=0}
				}
				return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
			},
			RGBToHex = function (rgb) {
				var hex = [
					rgb.r.toString(16),
					rgb.g.toString(16),
					rgb.b.toString(16)
				];
				$.each(hex, function (nr, val) {
					if (val.length == 1) {
						hex[nr] = '0' + val;
					}
				});
				return hex.join('');
			},
			HSBToHex = function (hsb) {
				return RGBToHex(HSBToRGB(hsb));
			};
		return {
			init: function (options) {
				options = $.extend({}, defaults, options||{});
				if (typeof options.color == 'string') {
					options.color = HexToHSB(options.color);
				} else if (options.color.r != undefined && options.color.g != undefined && options.color.b != undefined) {
					options.color = RGBToHSB(options.color);
				} else if (options.color.h != undefined && options.color.s != undefined && options.color.b != undefined) {
					options.color = fixHSB(options.color);
				} else {
					return this;
				}
				options.origColor = options.color;
				return this.each(function () {
					if (!$(this).data('colorpickerId')) {
						var id = 'collorpicker_' + parseInt(Math.random() * 1000);
						$(this).data('colorpickerId', id);
						var cal = $(tpl).attr('id', id);
						if (options.flat) {
							cal.appendTo(this).show();
						} else {
							cal.appendTo(document.body);
						}
						options.fields = cal
											.find('input')
												.bind('keydown', keyDown)
												.bind('change', change)
												.bind('blur', blur)
												.bind('focus', focus);
						cal.find('span').bind('mousedown', downIncrement);
						options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
						options.selectorIndic = options.selector.find('div div');
						options.hue = cal.find('div.colorpicker_hue div');
						cal.find('div.colorpicker_hue').bind('mousedown', downHue);
						options.newColor = cal.find('div.colorpicker_new_color');
						options.currentColor = cal.find('div.colorpicker_current_color');
						cal.data('colorpicker', options);
						cal.find('div.colorpicker_submit')
							.bind('mouseenter', enterSubmit)
							.bind('mouseleave', leaveSubmit)
							.bind('click', clickSubmit);
						fillRGBFields(options.color, cal.get(0));
						fillHSBFields(options.color, cal.get(0));
						fillHexFields(options.color, cal.get(0));
						setHue(options.color, cal.get(0));
						setSelector(options.color, cal.get(0));
						setCurrentColor(options.color, cal.get(0));
						setNewColor(options.color, cal.get(0));
						if (options.flat) {
							cal.css({
								position: 'relative',
								display: 'block'
							});
						} else {
							$(this).bind(options.eventName, show);
						}
					}
				});
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						$('#' + $(this).data('colorpickerId')).hide();
					}
				});
			},
			setColor: function(col) {
				if (typeof col == 'string') {
					col = HexToHSB(col);
				} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
					col = RGBToHSB(col);
				} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
					col = fixHSB(col);
				} else {
					return this;
				}
				return this.each(function(){
					if ($(this).data('colorpickerId')) {
						var cal = $('#' + $(this).data('colorpickerId'));
						cal.data('colorpicker').color = col;
						cal.data('colorpicker').origColor = col;
						fillRGBFields(col, cal.get(0));
						fillHSBFields(col, cal.get(0));
						fillHexFields(col, cal.get(0));
						setHue(col, cal.get(0));
						setSelector(col, cal.get(0));
						setCurrentColor(col, cal.get(0));
						setNewColor(col, cal.get(0));
					}
				});
			}
		};
	}();
	$.fn.extend({
		ColorPicker: ColorPicker.init,
		ColorPickerHide: ColorPicker.hide,
		ColorPickerShow: ColorPicker.show,
		ColorPickerSetColor: ColorPicker.setColor
	});
})(jQuery);$(function() {
	if ($('#node-list-filters').length) {
		var mode = location.href.indexOf('+') == -1 ? 'single' : 'multiple';
		$('#node-list-filters').append('<span class="mode">Выбор метки приведет к фильтрации <a class="single" href="#">только по этой метке</a><a class="multiple" href="#">по этой и ранее выбранным меткам</a></span>');
		$('#node-list-filters span.mode a.' + mode).addClass('active');
		$('#node-list-filters span.mode a:not(".active")').live('click', function() {
			mode = $(this).attr('class');
			$(this).siblings('a').andSelf().toggleClass('active');
			return false;
		});
		$('table.nodes .about a[href*="tags"]').click(function() {
			if (mode == 'multiple') {
				location.href = $(this).attr('href').replace('value=', 'value=' + location.href.match(/tags=([\d\+]+)/)[1] + '+')
				return false;
			}
		});
	}
});
;$(function() {
	var picker = $('#theme-constructor-colors div.picker');
	
	function applyColoring(color, value) {
		picker.ColorPickerSetColor(value);
		switch (color) {
			case 1:
				$('#t-c-c-element').css('background-color', '#' + value);
			break;
			case 2:
				$('#t-c-c-element').find('p, h1, li').css('color', '#' + value);
			break;
			case 3:
				$('.t-c-c-e-c-1 p a, .t-c-c-e-footer a').css('color', '#' + value);
			break;
			case 4:
				$('.t-c-c-e-c-1 ul li a').css('color', '#' + value);
			break;
			case 41:
				$('.t-c-c-e-c-1-header').css('color', '#' + value);
			break;
			case 42:
				$('.t-c-c-e-header').css('background-color', '#' + value);
			break;
			case 5:
				$('.t-c-c-e-c-2-block').css('background-color', '#' + value);
			break;
			case 6:
				$('.t-c-c-e-c-2-block h1').css('background-color', '#' + value);
			break;
			case 7:
				$('.t-c-c-e-c-2-block h1').css('color', '#' + value);
			break;
			case 8:
				$('.t-c-c-e-c-2-block a').css('color', '#' + value);
			break;
			case 9:
				$('.t-c-c-e-c-2-block p').css('color', '#' + value);
			break;
		}
	}
	
	picker.ColorPicker({
		flat: true,
		color: '#00ff00',
		onSubmit: function(hsb, hex, rgb) {
			$(curEl).css('background-color', '#' + hex);
			$(curEl).attr('alt', hex);
			$(curEl).siblings('input').val(hex);
			applyColoring(color, hex);
			picker.hide();
			curEl = color = null;
		}
	});
	
	var curEl, color;
	$('#theme-constructor-colors ul li img').click(function() {
		curEl = this;
		color = parseInt($(this).parent().attr('class').match(/\d+/gi), 10);
		picker.ColorPickerSetColor($(this).attr('alt') );
		picker.css({
			left: $(this).offset().left + 30,
			top: $(this).offset().top
		}).show();
	});
	
	
	var config = {};
	$('#theme-constructor-order input[checked]').each(function() {
		config[$(this).attr('name')] = $(this).siblings('span').text();
	});
	
	function applyConfig() {
		$.each(config, function(k, v) {
			switch (k) {
				case 'layoutlogo':
					switch (v) {
						case 'Слева':
							$('.t-c-c-e-h-1').text('Логотип');
							$('.t-c-c-e-h-2').text('Рекламный баннер');
							if (config.layoutauth == 'Сверху') {
								$('.t-c-c-e-h-3').text('Поиск и авторизация');
							} else {
								$('.t-c-c-e-h-3').text('');
							}
						break;
						case 'Справа':
							$('.t-c-c-e-h-3').text('Логотип');
							if (config.layoutauth == 'Сверху') {
								$('.t-c-c-e-h-1').text('Поиск и авторизация');
								$('.t-c-c-e-h-2').text('Рекламный баннер');
							} else {
								$('.t-c-c-e-h-1').text('Рекламный баннер');
								$('.t-c-c-e-h-2').text('');
							}
						break;
					}
				break;
				case 'layoutauth':
					switch (v) {
						case 'Не выводится':
							$('.t-c-c-e-c-auth').hide();
						break;
						case 'Сверху':
							$('.t-c-c-e-c-auth').hide();
						break;
						case 'Снизу':
							$('.t-c-c-e-c-auth').show();
						break;
					}
				break;
				case 'layoutcolumn':
					switch (v) {
						case 'Справа':
							$('.t-c-c-e-c-1').css('float', 'left');
							$('.t-c-c-e-c-2').css('float', 'right');
						break;
						case 'Слева':
							$('.t-c-c-e-c-1').css('float', 'right');
							$('.t-c-c-e-c-2').css('float', 'left');
						break;
					}
				break;
				case 'layoutnews':
					switch (v) {
						case 'Не выводится':
							$('.t-c-c-e-c-1-news, .t-c-c-e-c-2-news').hide();
						break;
						case 'В области основного контента':
							$('.t-c-c-e-c-1-news').show();
							$('.t-c-c-e-c-2-news').hide();
						break;
						case 'В колонке':
							$('.t-c-c-e-c-1-news').hide();
							$('.t-c-c-e-c-2-news').show();
						break;
					}
				break;
				case 'layoutnav':
					switch (v) {
						case 'В области основного контента':
							$('.t-c-c-e-c-1 ul').show();
							$('.t-c-c-e-c-2-nav').hide();
						break;
						case 'В колонке':
							$('.t-c-c-e-c-1 ul').hide();
							$('.t-c-c-e-c-2-nav').show();
						break;
					}
				break;
				case 'layoutcontacts':
					switch (v) {
						case 'Справа':
							$('.t-c-c-e-f-1').css('float', 'left');
							$('.t-c-c-e-f-2').css('float', 'right');
						break;
						case 'Слева':
							$('.t-c-c-e-f-1').css('float', 'right');
							$('.t-c-c-e-f-2').css('float', 'left');
						break;
					}
				break;
			}
		});
	}
	
	$('#theme-constructor-order input').click(function() {
		config[$(this).attr('name')] = $(this).siblings('span').text();
		applyConfig();
	});
	
	$('#theme-constructor-colors ul li img').each(function() {
		var color = parseInt($(this).parent().attr('class').match(/\d+/gi), 10);
		var value = $(this).attr('alt');
		applyColoring(color, value);
	});
	
	applyConfig();

});// synonym to console.log or alert
log = (function() {
	return (window.console && console.firebug) ? console.log : function() {
		$('body').prepend(arguments[0].toString() );
	};
})();

// namespace
var mcms = {};

/* Работа с формами
------------------------------------------------------------------------------------------------------------------- */
mcms.forms = {};
/* ---------------------------------------------------------------------------------------------------------------- */

/* Специфические действия для IE6
------------------------------------------------------------------------------------------------------------------- */
if ($.browser.msie && $.browser.version < 7 ) {
	mcms.ie = {};
	// фиксирование ширины документа на 1000px (min-width)
	mcms.ie.controlBodyWidth = function() {
	 	if ($(window).width() < 1000) {
			document.body.style.width = '1000px';
		} else {
			document.body.style.width = 'auto';
		}
	 }
	 
	// действия при готовности DOM
	 $(function() {
	 	// корректирует ширину эл-та body (min-width)
	 	mcms.ie.controlBodyWidth();
	 });
	 
	 // действия при ресайзе окна
	$(window).resize(function() {
	 	// корректирует ширину эл-та body (min-width)
	 	mcms.ie.controlBodyWidth();
	 });

	
}
/* ---------------------------------------------------------------------------------------------------------------- */	

/**
 * Действия при готовности DOM
 */
$(document).ready(function () {
	// замедляем скрытие подпунктов осн. навигации
	$('#toolbar ul.navigation>li').each(function() {
		var t;
		$(this).hover(function(e) {
			clearTimeout(t);
			$(this).addClass('hovered').siblings().removeClass('hovered');
		}, function(e) {
			var that = this;
			t = setTimeout(function() {
				$(that).removeClass('hovered');
			}, 600);
		});
	});
	
  try {
    var win = window.opener ? window.opener : window.dialogArguments, c;
      if (win) { tinyMCE = win.tinyMCE; }
  } catch (e) { }
		
	$("input:checked").parent().parent().addClass("current");

	$(":checkbox").change(function(){
		$(this).parent().parent().toggleClass("current");
	});
	
	$("input[name='select_all']").change(function () {
		$(this).parent().parent().parent().find("tr").toggleClass("current");
	});

  $('form.node-file-create-form input[name="__file_mode"]').change(function () { bebop_fix_file_mode_selection($(this).val()); });
  bebop_fix_file_mode_selection('local');

  /***
   * Выбор файла из архива.
   **/
  $('tbody.picker a.picker').click(function () {
    var picker = $('tbody.picker').attr('id').replace('file-', '');
    var fid = $(this).parent().parent().attr('id').replace('file-', '');
    if (picker == fid) {
      alert('Именно этот файл сейчас и используется.');
    } else {
      var filename = $('.field-filename', $(this).parent().parent()).html();
      var j = window.opener.jQuery;
      j('#file-' + picker + '-replace').attr('value', fid);
      j('#file-' + picker + ' td *').removeClass('active');
      j('#file-' + picker + ' td input.info').addClass('active').attr('value', filename);
      window.close();
    }
    return false;
  });

  // Бэкап и восстановление.
	if ($('form#mod_exchange').length != 0) {
    $('form#mod_exchange :radio').change(fix_backup_mode);
    fix_backup_mode();
  }

	$('#top_menu_controls ul li.current').addClass('current_strong');

  	$('#top_menu_controls ul li').mouseover(function(){
		$('#top_menu_controls ul li').removeClass('current');
		$(this).addClass('current');
	});
	
	$('#top_menu_controls ul li ul li').mouseover(function(){
		$(this).parent().parent().addClass('current');
	});
	
	$('#top_menu_controls ul li ul').mouseout(function(){
		$('#top_menu_controls ul li').removeClass('current');
		$('#top_menu_controls ul li.current_strong').addClass('current');
	});

	$('#top_menu_controls_bottom').mouseout(function(){
		$('#top_menu_controls ul li').removeClass('current');
		$('#top_menu_controls ul li.current_strong').addClass('current');
	});
});

function fix_backup_mode()
{
  var mode = $('form#mod_exchange :radio:checked').val();

  $('form#mod_exchange :file').parent().css('display', mode == 'import' ? 'block' : 'none');
  $('form#mod_exchange [name="expprofiledescr"]').parent().css('display', mode == 'export' ? 'block' : 'none');
  $('form#mod_exchange .control-TextLineControl-wrapper').css('display', mode == 'upgradetoMySQL' ? 'block' : 'none');
  $('form#mod_exchange .control-PasswordControl-wrapper').css('display', mode == 'upgradetoMySQL' ? 'block' : 'none');
}

function bebop_fix_file_mode_selection(sel)
{
  var map = { local: "Attachment", remote: "URL", ftp: "Set" };

  for (i in map) {
    var id = 'form.node-file-create-form .control-'+map[i]+'Control-wrapper';
    if (sel == i)
      $(id).show();
    else
      $(id).hide();
  }
}
;// Массовые операции над объектами.
$(function () {
  /**
   * По умолчанию этот блок скрыт. Выводим его только при поддержке JS.
   */
  $('.massctl').show();
  
  if ($('.nodelist :checked').length) {
    $('.massctl .actions').css('display', 'inline');
  }

  $('.nodelist input').click(function () {
    $('.massctl .actions').css('display', $('.nodelist input:checked').length ? 'inline' : 'none');
  });

  // Выделение.
  $('.selink').click(function () {
    var c = $(this).attr('class').replace(/.* select-/, '');
    switch (c) {
    case 'all':
      $('.nodelist :checkbox').attr('checked', 'checked').parents('li').find('>ul').show().end().find('>span.expand-collapse').removeClass('collapsed');
      break;
    case 'none':
      $('.nodelist :checkbox').attr('checked', '');
      break;
    default:
      $('.nodelist :checkbox').removeAttr('checked');
      $('.nodelist li.' + c + '>span.container span.actions :checkbox').attr('checked', 'checked').parents('li').find('>ul').show().end().find('>span.expand-collapse').removeClass('collapsed');
      $('.nodelist tr.' + c + ' :checkbox').attr('checked', 'checked');
    }
    $('.nodelist :checkbox:first').change();
	$('.massctl .actions').css('display', $('.nodelist').find(':checked').length ? 'inline' : 'none');
  });

  // Действия.
  $('.actionlink').click(function () {
    if ($('.nodelist :checked').size()) {
      var action = $(this).attr('class').replace(/.*action-/, '');
      var form = $(this).parents('form:eq(0)');

      switch (action) {
      case 'edit':
        action = mcms_lp + 'admin/files/edit?redir=1&';
        break;
      default:
        action = mcms_lp + 'nodeapi/' + action + '?';
        break;
      }

      action += 'destination=' + escape(window.location.href);

      form.attr('action', action);
      form.submit();
    }
  });
});
;$(function () {
  $('body.mcms fieldset.tab:gt(0) > div').hide();
  $('body.mcms fieldset.tab > legend').click(function(){
    var tab = $(this).parents('fieldset');
    var frm = $(this).parents('form:eq(0)');
    var count = $('>.control:visible', tab).length;
    $('fieldset.tab > .controls', frm).hide();
    if (!count)
      $('> .controls', tab).show();
  });
});
;/**
 * Массовое переключение чекбоксов в таблице.
 *
 * Если первая ячейка (td) первой строки (tr) заголовка (thead) таблицы с
 * классом toggle пуста, в неё добавляется чекбокс для переключения всех
 * остальных чекбоксов в теле (tbody) этой таблицы. Если же в теле таблицы
 * чекбоксов нет, ничего не добавляется.
 *
 * justin.forest@gmail.com, 2009-09-09
 */
$(function(){
  $('table.toggle thead tr:first th:first').each(function () {
    if (!$(this).html() && $(this).parents('table:first').find('tbody :checkbox').length > 1) {
      $(this).html('<input type="checkbox"/>').find(':checkbox').click(function () {
        var tb = $(this).parents('table:first').find('tbody');
        tb.find(':checkbox').attr('checked', $(this).attr('checked') ? 'checked' : '');
		$('.massctl .actions').css('display', $('.nodelist tbody:first').find(':checked').length ? 'inline' : 'none');
        // По цепочке событие почему-то не передаётся, поэтому вызываем его
        // принудительно, чтобы сработали другие обработчики (например,
        // в админке так скрываются и отображаются массовые операции).
        //tb.find('tr:first :checkbox').click();
      });
    }
  });
});$(function(){
  $('a.node-popup-controls').click(function(){
    try {
      var o = $(this).offset();
      $.getJSON(mcms_path + mcms_lp + 'api/node/actions.json', {
        id: 'search',
        url: $(this).attr('href'),
        from: location.href
      }, function (response) {
        $('#mcms-nawr').remove();
        var html = '<div id="mcms-nawr"><ul>';
        for (k in response) {
          c = response[k];
          html += '<li class="'+ c.icon +'"><a href="'+ c.href +'">'+ c.title +'</a></li>';
        }
        html += '</li></ul></div>';
        $('body').prepend(html);
        $('#mcms-nawr').css({
          'position': 'absolute',
          'z-index': 500,
          'left': o.left + 4 + 'px',
          'top': o.top + 4 + 'px'
        });
      });
    } catch (e) {
      alert(e);
    }

    return false;
  });

  // Удаление списка при клике куда-нибудь.
  $().click(function(){
    $('#mcms-nawr').remove();
  });
});
;/**
 * @class
 */
var mcms = mcms || {};

/**
 * Отображение произвольной информации во всплывающих блоках
 * @requires jQuery 1.2
 * @author <a href="mailto:d.chekanov@gmail.com">Dmitriy Chekanov</a>
 * @param {String|jQuery object} content Строка или jQuery-объект для вывода в блоке. HTML в строке поддерживается.
 * @param {Object} [event] Сведения о событии, для автоматического позиционирования блока
 * @param {Object} [config] Настройки
 * @param {jQuery object} [config.box] Произвольный элемент, который будет отпозиционирован, в него будет выведена информация, при клике будет скрыт (при соот. настройках).
 * @param {Boolean} [config.unique="false"] По умолчанию для вывода используется один и тот же блок. Это позволяет не захламлять DOM, но не позволяет выводить несколько блоков одновременно.
 * @param {String} [config.classes="standard"] Классы, которые нужно добавить к блоку.
 * @param {Array} [config.position] Координаты блока (x, y).
 * @param {Array} [config.offset] Cмещение относительно координат (x, y).
 * @param {Boolean} [config.permanent="false"] Определяет, будет ли блок скрываться при клике по элементам вне блока (false) или нет (true).
 * @returns {jQuery object} Созданный или использованный блок.
 * @example
 * // Минимальные настройки
 * mcms.infobox('Hello world');
 * @example
 * // Появление в месте клика
 * $('body').click(function(e) {
 *   mcms.infobox('Hello world', e);
 *   e.stopPropagation();
 * });
 * @example
 * // С настройками и манипуляцией после отображения
 * $('body').click(function(e) {
 *   mcms.infobox('Hello world', null, {
 *     unique: true,
 *     classes: 'standard class1 class2',
 *     position: [250, 300]
 *   }).animate({
 *     left: Math.floor( (700-199)*Math.random() ) + 200,
 *     top: Math.floor( (500-99)*Math.random() ) + 100
 *   }, 2000, function() {
 *   	$(this).fadeOut();
 *   });
 *   e.stopPropagation();
 * });
 * 
 */
mcms.infobox = function(content, event, config) {
	// настройки по умолчанию
	var defaultConfig = {
		'classes': 'standard',
		'position': [100, 100]
	};
	config = $.extend(true, defaultConfig, config);
	// определяем блок, в который будет выводиться информация
	if (!config.box) {
		if (!config.unique && mcms.infobox.sharedBox) {
			config.box = mcms.infobox.sharedBox;
		} else {
			config.box = $('<div class="mcms-infobox" />').appendTo('body').hide();
			if (!config.unique) {
				mcms.infobox.sharedBox = config.box;
			}
		}
	}
	// определяем положение блока
	if (event) {
		config.position[0] = event.pageX;
		config.position[1] = event.pageY;
	}
	if (config.offset) {
		config.position[0] += config.offset[0];
		config.position[1] += config.offset[1];
	}
	config.box.css({
		left: config.position[0],
		top: config.position[1]
	});
	// классы
	config.box.addClass(config.classes);
	// скрываем при клике вне блока
	if (!config.permanent) {
		$(function() {
			$('html').click(function() {
				config.box.hide();
			});
		});
	}
	config.box.empty().append(content).show();
	return config.box;
};if (jQuery) {
  $(document).ready(function(){
    $('.jsonly').show();
    $('.nojs').hide();
  });
}
;$(function() {
	// календарь
	$('input.mode-datetime, input.mode-date').datepicker({
		dateFormat: 'yy-mm-dd',
		constrainInput: false,
		duration: 0,
		beforeShow: function() {
			var splittedVal = $(this).val().split(' ');
			if (splittedVal[1]) {
				$(this).attr('time', splittedVal[1]);
			}	
		},
		onSelect: function(dateText) {
			var val = dateText;
			if ($(this).attr('time') ) {
				val += ' ' + $(this).attr('time');
			}
			$(this).val(val);
		}
	});
});
;/*
 * jQuery UI 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {
	version: "1.7.1",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	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 || !instance.element[0].parentNode) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		return document.compareDocumentPosition
			? a.compareDocumentPosition(b) & 16
			: a !== b && a.contains(b);
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	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
	}
};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({
	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


//Additional selectors
$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			// the element and all of its ancestors must be visible
			// the browser may report that the area is hidden
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
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];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		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(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	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' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if (event.originalEvent) {
			for (var i = $.event.props.length, prop; i;) {
				prop = $.event.props[--i];
				event[prop] = event.originalEvent[prop];
			}
		}

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
;/* Russian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Andrew Stromnov (stromnov@gmail.com). */
jQuery(function($){
	$.datepicker.regional['ru'] = {
		closeText: 'Закрыть',
		prevText: '&#x3c;Пред',
		nextText: 'След&#x3e;',
		currentText: 'Сегодня',
		monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
		'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
		'Июл','Авг','Сен','Окт','Ноя','Дек'],
		dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
		dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
		dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
		dateFormat: 'dd.mm.yy', firstDay: 1,
		isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['ru']);
});/*
 * jQuery UI Datepicker 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */

(function($) { // hide the namespace

$.extend($.ui, { datepicker: { version: "1.7.1" } });

var PROP_NAME = 'datepicker';

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		closeText: 'Done', // Display text for close link
		prevText: 'Prev', // Display text for previous month link
		nextText: 'Next', // Display text for next month link
		currentText: 'Today', // Display text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false // True if right-to-left language, false if left-to-right
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'show', // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearRange: '-10:+10', // Range of years to display in drop-down,
			// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with '+' for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: 'normal', // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: '', // Selector for an alternate field to store selected dates into
		altFormat: '', // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false // True to show button panel, false to not show it
	};
	$.extend(this._defaults, this.regional['']);
	this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: 'hasDatepicker',

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},

	/* Override the default settings for all instances of the date picker.
	   @param  settings  object - the new settings to use as defaults (anonymous object)
	   @return the manager object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span
	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
	_attachDatepicker: function(target, settings) {
		// check for settings on the control itself - in namespace 'date:'
		var inlineSettings = null;
		for (var attrName in this._defaults) {
			var attrValue = target.getAttribute('date:' + attrName);
			if (attrValue) {
				inlineSettings = inlineSettings || {};
				try {
					inlineSettings[attrName] = eval(attrValue);
				} catch (err) {
					inlineSettings[attrName] = attrValue;
				}
			}
		}
		var nodeName = target.nodeName.toLowerCase();
		var inline = (nodeName == 'div' || nodeName == 'span');
		if (!target.id)
			target.id = 'dp' + (++this.uuid);
		var inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {}, inlineSettings || {});
		if (nodeName == 'input') {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName))
			return;
		var appendText = this._get(inst, 'appendText');
		var isRTL = this._get(inst, 'isRTL');
		if (appendText)
			input[isRTL ? 'before' : 'after']('<span class="' + this._appendClass + '">' + appendText + '</span>');
		var showOn = this._get(inst, 'showOn');
		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
			var buttonText = this._get(inst, 'buttonText');
			var buttonImage = this._get(inst, 'buttonImage');
			inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
				$('<img/>').addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$('<button type="button"></button>').addClass(this._triggerClass).
					html(buttonImage == '' ? buttonText : $('<img/>').attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? 'before' : 'after'](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
					$.datepicker._hideDatepicker();
				else
					$.datepicker._showDatepicker(target);
				return false;
			});
		}
		input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
			bind("setData.datepicker", function(event, key, value) {
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key) {
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName))
			return;
		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
			bind("setData.datepicker", function(event, key, value){
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
		this._setDate(inst, this._getDefaultDate(inst));
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
	},

	/* Pop-up the date picker in a "dialog" box.
	   @param  input     element - ignored
	   @param  dateText  string - the initial date to display (in the current format)
	   @param  onSelect  function - the function(dateText) to call when a date is selected
	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
	                     event - with x/y coordinates or
	                     leave empty for default (screen centre)
	   @return the manager object */
	_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
		var inst = this._dialogInst; // internal instance
		if (!inst) {
			var id = 'dp' + (++this.uuid);
			this._dialogInput = $('<input type="text" id="' + id +
				'" size="1" style="position: absolute; top: -100px;"/>');
			this._dialogInput.keydown(this._doKeyDown);
			$('body').append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		extendRemove(inst.settings, settings || {});
		this._dialogInput.val(dateText);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			var browserWidth = window.innerWidth || document.documentElement.clientWidth ||	document.body.clientWidth;
			var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI)
			$.blockUI(this.dpDiv);
		$.data(this._dialogInput[0], PROP_NAME, inst);
		return this;
	},

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName == 'input') {
			inst.trigger.remove();
			$target.siblings('.' + this._appendClass).remove().end().
				removeClass(this.markerClassName).
				unbind('focus', this._showDatepicker).
				unbind('keydown', this._doKeyDown).
				unbind('keypress', this._doKeyPress);
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = false;
			inst.trigger.filter("button").
			each(function() { this.disabled = false; }).end().
				filter("img").
				css({opacity: '1.0', cursor: ''});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().removeClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = true;
			inst.trigger.filter("button").
			each(function() { this.disabled = true; }).end().
				filter("img").
				css({opacity: '0.5', cursor: 'default'});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().addClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	   @param  target    element - the target input field or division or span
	   @return boolean - true if disabled, false if enabled */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] == target)
				return true;
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	   @param  target  element - the target input field or division or span
	   @return  object - the associated instance data
	   @throws  error if a jQuery problem getting data */
	_getInst: function(target) {
		try {
			return $.data(target, PROP_NAME);
		}
		catch (err) {
			throw 'Missing instance data for this datepicker';
		}
	},

	/* Update the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    object - the new settings to update or
	                   string - the name of the setting to change or
	   @param  value   any - the new value for the setting (omit if above is an object) */
	_optionDatepicker: function(target, name, value) {
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		var inst = this._getInst(target);
		if (inst) {
			if (this._curInst == inst) {
				this._hideDatepicker(null);
			}
			extendRemove(inst.settings, settings);
			var date = new Date();
			extendRemove(inst, {rangeStart: null, // start of range
				endDay: null, endMonth: null, endYear: null, // end of range
				selectedDay: date.getDate(), selectedMonth: date.getMonth(),
				selectedYear: date.getFullYear(), // starting point
				currentDay: date.getDate(), currentMonth: date.getMonth(),
				currentYear: date.getFullYear(), // current selection
				drawMonth: date.getMonth(), drawYear: date.getFullYear()}); // month being drawn
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	   @param  target   element - the target input field or division or span
	   @param  date     Date - the new date
	   @param  endDate  Date - the new end date for a range (optional) */
	_setDateDatepicker: function(target, date, endDate) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date, endDate);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	   @param  target  element - the target input field or division or span
	   @return Date - the current date or
	           Date[2] - the current dates for a range */
	_getDateDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst && !inst.inline)
			this._setDateFromField(inst);
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var inst = $.datepicker._getInst(event.target);
		var handled = true;
		var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing)
			switch (event.keyCode) {
				case 9:  $.datepicker._hideDatepicker(null, '');
						break; // hide on tab out
				case 13: var sel = $('td.' + $.datepicker._dayOverClass +
							', td.' + $.datepicker._currentClass, inst.dpDiv);
						if (sel[0])
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						else
							$.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, 'stepBigMonths') :
							-$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, 'stepBigMonths') :
							+$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									-$.datepicker._get(inst, 'stepBigMonths') :
									-$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									+$.datepicker._get(inst, 'stepBigMonths') :
									+$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		else {
			handled = false;
		}
		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if ($.datepicker._get(inst, 'constrainInput')) {
			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
			return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
			input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input);
		var beforeShow = $.datepicker._get(inst, 'beforeShow');
		extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		$.datepicker._hideDatepicker(null, '');
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
			return !isFixed;
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		inst.rangeStart = null;
		// determine sizing offscreen
		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
			left: offset.left + 'px', top: offset.top + 'px'});
		if (!inst.inline) {
			var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
			var duration = $.datepicker._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
					$('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
						height: inst.dpDiv.height() + 4});
			};
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[showAnim](duration, postProcess);
			if (duration == '')
				postProcess();
			if (inst.input[0].type != 'hidden')
				inst.input[0].focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		var dims = {width: inst.dpDiv.width() + 4,
			height: inst.dpDiv.height() + 4};
		var self = this;
		inst.dpDiv.empty().append(this._generateHTML(inst))
			.find('iframe.ui-datepicker-cover').
				css({width: dims.width, height: dims.height})
			.end()
			.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
				.bind('mouseout', function(){
					$(this).removeClass('ui-state-hover');
					if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
					if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
				})
				.bind('mouseover', function(){
					if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
						$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
						$(this).addClass('ui-state-hover');
						if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
						if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
					}
				})
			.end()
			.find('.' + this._dayOverClass + ' a')
				.trigger('mouseover')
			.end();
		var numMonths = this._getNumberOfMonths(inst);
		var cols = numMonths[1];
		var width = 17;
		if (cols > 1) {
			inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
		} else {
			inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
		}
		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
			'Class']('ui-datepicker-multi');
		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
			'Class']('ui-datepicker-rtl');
		if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
			$(inst.input[0]).focus();
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth();
		var dpHeight = inst.dpDiv.outerHeight();
		var inputWidth = inst.input ? inst.input.outerWidth() : 0;
		var inputHeight = inst.input ? inst.input.outerHeight() : 0;
		var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft();
		var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop();

		offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
		offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            obj = obj.nextSibling;
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker
	   @param  duration  string - the duration over which to close the date picker */
	_hideDatepicker: function(input, duration) {
		var inst = this._curInst;
		if (!inst || (input && inst != $.data(input, PROP_NAME)))
			return;
		if (inst.stayOpen)
			this._selectDate('#' + inst.id, this._formatDate(inst,
				inst.currentDay, inst.currentMonth, inst.currentYear));
		inst.stayOpen = false;
		if (this._datepickerShowing) {
			duration = (duration != null ? duration : this._get(inst, 'duration'));
			var showAnim = this._get(inst, 'showAnim');
			var postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};
			if (duration != '' && $.effects && $.effects[showAnim])
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
					duration, postProcess);
			else
				inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
			if (duration == '')
				this._tidyDialog(inst);
			var onClose = this._get(inst, 'onClose');
			if (onClose)
				onClose.apply((inst.input ? inst.input[0] : null),
					[(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
			this._datepickerShowing = false;
			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
		this._curInst = null;
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst)
			return;
		var $target = $(event.target);
		if (($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.hasClass($.datepicker._triggerClass) &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
			$.datepicker._hideDatepicker(null, '');
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		}
		else {
		var date = new Date();
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst._selectingMonthYear = false;
		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
			parseInt(select.options[select.selectedIndex].value,10);
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Restore input focus after not changing month/year. */
	_clickMonthYear: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (inst.input && inst._selectingMonthYear && !$.browser.msie)
			inst.input[0].focus();
		inst._selectingMonthYear = !inst._selectingMonthYear;
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var target = $(id);
		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}
		var inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $('a', td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		if (inst.stayOpen) {
			inst.endDay = inst.endMonth = inst.endYear = null;
		}
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
		if (inst.stayOpen) {
			inst.rangeStart = this._daylightSavingAdjust(
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
			this._updateDatepicker(inst);
		}
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst.stayOpen = false;
		inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
		this._selectDate(target, '');
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input)
			inst.input.val(dateStr);
		this._updateAlternate(inst);
		var onSelect = this._get(inst, 'onSelect');
		if (onSelect)
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		else if (inst.input)
			inst.input.trigger('change'); // fire the change event
		if (inst.inline)
			this._updateDatepicker(inst);
		else if (!inst.stayOpen) {
			this._hideDatepicker(null, this._get(inst, 'duration'));
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) != 'object')
				inst.input[0].focus(); // restore focus
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altField = this._get(inst, 'altField');
		if (altField) { // update alternate field too
			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
			var date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
		var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
		var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
		firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
		if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
			checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
			return $.datepicker.iso8601Week(checkDate);
		} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
			firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
			if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
				return 1;
			}
		}
		return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
	},

	/* Parse a string value into a date object.
	   See formatDate below for the possible formats.

	   @param  format    string - the expected format of the date
	   @param  value     string - the date in the above format
	   @param  settings  Object - attributes include:
	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  Date - the extracted date value or null if value is blank */
	parseDate: function (format, value, settings) {
		if (format == null || value == null)
			throw 'Invalid arguments';
		value = (typeof value == 'object' ? value.toString() : value + '');
		if (value == '')
			return null;
		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		var year = -1;
		var month = -1;
		var day = -1;
		var doy = -1;
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Extract a number from the string value
		var getNumber = function(match) {
			lookAhead(match);
			var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
			var size = origSize;
			var num = 0;
			while (size > 0 && iValue < value.length &&
					value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
				num = num * 10 + parseInt(value.charAt(iValue++),10);
				size--;
			}
			if (size == origSize)
				throw 'Missing number at position ' + iValue;
			return num;
		};
		// Extract a name from the string value and convert to an index
		var getName = function(match, shortNames, longNames) {
			var names = (lookAhead(match) ? longNames : shortNames);
			var size = 0;
			for (var j = 0; j < names.length; j++)
				size = Math.max(size, names[j].length);
			var name = '';
			var iInit = iValue;
			while (size > 0 && iValue < value.length) {
				name += value.charAt(iValue++);
				for (var i = 0; i < names.length; i++)
					if (name == names[i])
						return i + 1;
				size--;
			}
			throw 'Unknown name at position ' + iInit;
		};
		// Confirm that a literal character matches the string value
		var checkLiteral = function() {
			if (value.charAt(iValue) != format.charAt(iFormat))
				throw 'Unexpected literal at position ' + iValue;
			iValue++;
		};
		var iValue = 0;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					checkLiteral();
			else
				switch (format.charAt(iFormat)) {
					case 'd':
						day = getNumber('d');
						break;
					case 'D':
						getName('D', dayNamesShort, dayNames);
						break;
					case 'o':
						doy = getNumber('o');
						break;
					case 'm':
						month = getNumber('m');
						break;
					case 'M':
						month = getName('M', monthNamesShort, monthNames);
						break;
					case 'y':
						year = getNumber('y');
						break;
					case '@':
						var date = new Date(getNumber('@'));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'"))
							checkLiteral();
						else
							literal = true;
						break;
					default:
						checkLiteral();
				}
		}
		if (year == -1)
			year = new Date().getFullYear();
		else if (year < 100)
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				var dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim)
					break;
				month++;
				day -= dim;
			} while (true);
		}
		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
			throw 'Invalid date'; // E.g. 31/02/*
		return date;
	},

	/* Standard date formats. */
	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
	COOKIE: 'D, dd M yy',
	ISO_8601: 'yy-mm-dd',
	RFC_822: 'D, d M y',
	RFC_850: 'DD, dd-M-y',
	RFC_1036: 'D, d M y',
	RFC_1123: 'D, d M yy',
	RFC_2822: 'D, d M yy',
	RSS: 'D, d M y', // RFC 822
	TIMESTAMP: '@',
	W3C: 'yy-mm-dd', // ISO 8601

	/* Format a date object into a string value.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   o  - day of year (no leading zeros)
	   oo - day of year (three digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   @ - Unix timestamp (ms since 01/01/1970)
	   '...' - literal text
	   '' - single quote

	   @param  format    string - the desired format of the date
	   @param  date      Date - the date value to format
	   @param  settings  Object - attributes include:
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  string - the date in the above format */
	formatDate: function (format, date, settings) {
		if (!date)
			return '';
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							break;
						case 'o':
							var doy = date.getDate();
							for (var m = date.getMonth() - 1; m >= 0; m--)
								doy += this._getDaysInMonth(date.getFullYear(), m);
							output += formatNumber('o', doy, 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case '@':
							output += date.getTime();
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var chars = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++)
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					chars += format.charAt(iFormat);
			else
				switch (format.charAt(iFormat)) {
					case 'd': case 'm': case 'y': case '@':
						chars += '0123456789';
						break;
					case 'D': case 'M':
						return null; // Accept anything
					case "'":
						if (lookAhead("'"))
							chars += "'";
						else
							literal = true;
						break;
					default:
						chars += format.charAt(iFormat);
				}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst) {
		var dateFormat = this._get(inst, 'dateFormat');
		var dates = inst.input ? inst.input.val() : null;
		inst.endDay = inst.endMonth = inst.endYear = null;
		var date = defaultDate = this._getDefaultDate(inst);
		var settings = this._getFormatConfig(inst);
		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			this.log(event);
			date = defaultDate;
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		return date;
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(date, defaultDate) {
		var offsetNumeric = function(offset) {
			var date = new Date();
			date.setDate(date.getDate() + offset);
			return date;
		};
		var offsetString = function(offset, getDaysInMonth) {
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 'd') {
					case 'd' : case 'D' :
						day += parseInt(matches[1],10); break;
					case 'w' : case 'W' :
						day += parseInt(matches[1],10) * 7; break;
					case 'm' : case 'M' :
						month += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
					case 'y': case 'Y' :
						year += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day);
		};
		date = (date == null ? defaultDate :
			(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
		date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
		if (date) {
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(date);
	},

	/* Handle switch to/from daylight saving.
	   Hours may be non-zero on daylight saving cut-over:
	   > 12 when midnight changeover, but then cannot generate
	   midnight datetime, so jump to 1AM, otherwise reset.
	   @param  date  (Date) the date to check
	   @return  (Date) the corrected date */
	_daylightSavingAdjust: function(date) {
		if (!date) return null;
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, endDate) {
		var clear = !(date);
		var origMonth = inst.selectedMonth;
		var origYear = inst.selectedYear;
		date = this._determineDate(date, new Date());
		inst.selectedDay = inst.currentDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
		if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
			this._notifyChange(inst);
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? '' : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var isRTL = this._get(inst, 'isRTL');
		var showButtonPanel = this._get(inst, 'showButtonPanel');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var stepBigMonths = this._get(inst, 'stepBigMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var monthNamesShort = this._get(inst, 'monthNamesShort');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var endDate = inst.endDay ? this._daylightSavingAdjust(
			new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
		var defaultDate = this._getDefaultDate(inst);
		var html = '';
		for (var row = 0; row < numMonths[0]; row++) {
			var group = '';
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				var cornerClass = ' ui-corner-all';
				var calender = '';
				if (isMultiMonth) {
					calender += '<div class="ui-datepicker-group ui-datepicker-group-';
					switch (col) {
						case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
						case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
						default: calender += 'middle'; cornerClass = ''; break;
					}
					calender += '">';
				}
				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					'</div><table class="ui-datepicker-calendar"><thead>' +
					'<tr>';
				var thead = '';
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
				}
				calender += thead + '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += '<tr>';
					var tbody = '';
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += '<td class="' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + this._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' +
							inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ui-state-active' : '') + // highlight selected day
							'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += '</tbody></table>' + (isMultiMonth ? '</div>' + 
							((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
				group += calender;
			}
			html += group;
		}
		html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			selectedDate, secondary, monthNames, monthNamesShort) {
		minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
		var changeMonth = this._get(inst, 'changeMonth');
		var changeYear = this._get(inst, 'changeYear');
		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
		var html = '<div class="ui-datepicker-title">';
		var monthHtml = '';
		// month selection
		if (secondary || !changeMonth)
			monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> ';
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			monthHtml += '<select class="ui-datepicker-month" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
			 	'>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth()))
					monthHtml += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNamesShort[month] + '</option>';
			}
			monthHtml += '</select>';
		}
		if (!showMonthAfterYear)
			html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : '');
		// year selection
		if (secondary || !changeYear)
			html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
		else {
			// determine range of years to display
			var years = this._get(inst, 'yearRange').split(':');
			var year = 0;
			var endYear = 0;
			if (years.length != 2) {
				year = drawYear - 10;
				endYear = drawYear + 10;
			} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
				year = drawYear + parseInt(years[0], 10);
				endYear = drawYear + parseInt(years[1], 10);
			} else {
				year = parseInt(years[0], 10);
				endYear = parseInt(years[1], 10);
			}
			year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
			endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
			html += '<select class="ui-datepicker-year" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
				'>';
			for (; year <= endYear; year++) {
				html += '<option value="' + year + '"' +
					(year == drawYear ? ' selected="selected"' : '') +
					'>' + year + '</option>';
			}
			html += '</select>';
		}
		if (showMonthAfterYear)
			html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml;
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period == 'Y' ? offset : 0);
		var month = inst.drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = this._daylightSavingAdjust(new Date(year, month, day));
		// ensure it is within the bounds set
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period == 'M' || period == 'Y')
			this._notifyChange(inst);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, 'onChangeMonthYear');
		if (onChange)
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, 'numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
	_getMinMaxDate: function(inst, minMax, checkRange) {
		var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
		return (!checkRange || !inst.rangeStart ? date :
			(!date || inst.rangeStart > date ? inst.rangeStart : date));
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst);
		var date = this._daylightSavingAdjust(new Date(
			curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
		if (offset < 0)
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		// during range selection, use minimum of selected date and range start
		var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
			new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
		newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
		var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props)
		if (props[name] == null || props[name] == undefined)
			target[name] = props[name];
	return target;
};

/* Determine whether an object is an array. */
function isArray(a) {
	return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
		(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick).
			find('body').append($.datepicker.dpDiv);
		$.datepicker.initialized = true;
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	return this.each(function() {
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.7.1";

// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window.DP_jQuery = $;

})(jQuery);
;/**
 * Molinos CMS. Прозрачное добавление записей в справочник.
 *
 * @package Molinos CMS
 * @subpackage dictionary
 * @author Dmitry Chekanov <d.chekanov@gmail.com>
 */
$(function() {
	$('select.dictinfo').prepend('<option value="new">Новый элемент...</option><option disabled="disabled">-----</option>').change(function() {
		var select = $(this);
		if (select.val() == 'new') {
			var name = prompt('Имя элемента');
			if (name) {
				$.getJSON('api/dictionary/find.json?dictionary=' + select.attr('class').split(' ')[1] + '&name=' + name, function(response) {
					if (response.isnew) {
						select.append('<option value="' + response.id + '">' + name + '</option>').find('option:last').attr('selected', 'selected');
					} else {
						select.find('option[value="' + response.id + '"]').attr('selected', 'selected');
					}
					select.attr('data-selected', response.id);
				});
			} else {
				select.find('option[value = ' + select.attr('data-selected') + ']').attr('selected', 'selected');
			}
		} else {
			select.attr('data-selected', select.val() );
		}
	}).each(function() {
		$(this).attr('data-selected', $(this).val() );
	});
});
;$(document).ready(function(){
  $('a.external').attr('target', '_blank');
  $('a[href*="://"]').attr('target', '_blank');
});
;$(function () {
  $('#addfiles .add').click(function () {
    var tpl = $('#cloneme').html();
    for (i=0;i<5;i++) { $('#addfiles ol').append('<li>'+tpl+'</li>'); }
  });

  $('#addfiles.ftp input[name="all"]').change(function () {
    var t = $(this).parents('form:eq(0)').find('table input');
    if ($(this).attr('checked'))
      t.attr('checked', true);
    else
      t.attr('checked', false);
  });
  
  $('#page-admin-content-files span.transformations-selector').click(function() {
  	var that = $(this);
  	$('#page-admin-content-files span.transformations-selector.hovered').removeClass('hovered');
	that.toggleClass('hovered');
	$(document).click(function() {
		that.removeClass('hovered');
		$(document).unbind('click', arguments.callee);
	});
	return false;
  });
});
;// Returns localized strings by id.
// See http://code.google.com/p/molinos-cms/wiki/t_js_function
function t(id)
{
  if (i18n_strings[id])
    return i18n_strings[id];
  else
    return '@' + id;
}
;$(document).ready(function () {
  $('#indexes input').change(function () {
    $('#indexes input.' + $(this).attr('class')).attr('checked', $(this).attr('checked') ? 'checked' : '');
  });
});
;$(function() {
		
	function getFieldLabels(fieldValue) {
		var labels = {
			list: fieldValue.split(','),
			cleanList: [],
			positions: []
		}, startPosition = 0;
		$.each(labels.list, function(k, v) {
			var cleanLabel = $.trim(v);
			labels.list[k] = v;
			labels.positions[k] = {
				start: startPosition,
				end: startPosition + v.length
			};
			labels.cleanList[k] = cleanLabel;
			startPosition = startPosition + v.length + 1;
		});
		return labels;
	}
	
	function getCaretPosition(element) {
		var caretPosition;
		if (document.selection) {
			var r = document.selection.createRange().duplicate();
			r.moveEnd('character', element.value.length);
			if (r.text == '') {
				caretPosition = element.value.length;
			} else {
				caretPosition = element.value.lastIndexOf(r.text);
			}
		} else {
			caretPosition = element.selectionStart;
		}
		return caretPosition;
	}
	
	function getModifiedLabel(fieldValue, caretPosition) {
		var labels = getFieldLabels(fieldValue), label;
		$.each(labels.positions, function(k, v) {
			if (caretPosition >= v.start && caretPosition <= v.end) {
				label = labels.cleanList[k];
			}
		});
		return label;
	}
	
	$('input[name="labels"]').each(function() {
		var that = this, t, c;
		var listContainer =  $('<div class="suggestions" />').appendTo('body').click(function(e) {
			var target = $(e.target);
			if (target.is('span') ) {
				var labels = getFieldLabels(that.value);
				$.each(labels.positions, function(k, v) {
					if (c >= v.start && c <= v.end) {
						labels.cleanList[k] = $(e.target).text();
					}
				});
				$(that).val(labels.cleanList.join(', ') );
				$(this).empty().hide();
			}
		});
		var f = function() {
			var label = getModifiedLabel(that.value, c);
			$.get('./api/labels/suggest.xml', {
				search: label
			}, function(response) {
				response = $(response);
				var length = response.find('label').length;
				if (length > 0) {
					response.find('label').each(function(k) {
						var text = '<span class="fakelink">' + $(this).text() +  '</span>';
						if (k < length - 1) {
							text += ', '
						}
						listContainer.append(text);
					});
					listContainer.css({
						left: position.left,
						top: position.top,
						width: $(that).outerWidth() - 20
					}).show();
				}
			});
		};
		var position = {
			left: $(this).offset().left,
			top: $(this).offset().top + $(this).outerHeight() + 1
		};
		$(this).keyup(function(e) {
			if (e.which < 37 || e.which > 40) {
				c = getCaretPosition(that);
				clearTimeout(t);
				listContainer.empty().hide();
				var label = getModifiedLabel(that.value, c);
				if (label && label.length > 3) {
					t = setTimeout(f, 500);
				}
			}
		});
	});
	
});
;$(function(){
  $('.modules-control input').change(function(){
    $(this).parents('tr:first').toggleClass('highlight');
  });
});
;/**
 * Скрипт, управляющий переключением расширенных опций.
 */
$(document).ready(function(){
  $('#delete-nodes u').click(function (){
    var div = $('#delete-nodes');
    $('.nojs', div).show();
    $('.jsonly', div).hide();
  });
});
;$(function () {
  $('table#access tbody th').click(function () {
    crud_recheck($(this).parents('tr:eq(0)').find('input'));
  });
  $('table#access thead th.c').click(function () {
    crud_recheck($(this).parents('table:eq(0)').find('input[name$="[' + $(this).text().toLowerCase() + ']"]'));
  });
});

function crud_recheck($inputs)
{
  if ($inputs.filter(':checked').length != $inputs.length)
    $inputs.attr('checked', 'checked');
  else
    $inputs.removeAttr('checked');
  $inputs.parent().addClass('hl');
}
;$(document).ready(function(){
	var f = function (c) {
		var fs = c.parents('form:first').find('fieldset.nojs');
		if (c.attr('checked'))
			fs.show();
		else
			fs.hide();
	}
	var ctl = $('form.subscribe input[name="custom_sections"]');
	ctl.change(function(){f($(this));});
	f(ctl);
});

// vim: set ts=4 sts=4 sw=4 noet:
;/**
 * Анимация формы управления привязкой типа к разделам.
 *
 * @package Molinos CMS
 * @subpackage taxonomy
 * @author Justin Forest <justin.forest@gmail.com>
 */
$(document).ready(function(){
  // Управление видимостью филдсета при изменении чекбокса.
  $('form.classify input[name="all"]').change(function(){
    var fs = $(this).parents('form:first').find('fieldset');
    if ($(this).attr('checked')) {
	  fs.hide();
	} else {
	  fs.show();
	}
  });

  // Сокрытие чекбокса при загрузке.
  if ($('form.classify input[name="all"]').attr('checked')) {
  	$('form.classify fieldset').hide();
  }
});



$(function() {
	// сворачивание/разворачивание списка разделов
	$('ul.classify').click(function(e) {
		var target = $(e.target);
		if (target.is('span.expand-collapse') ) {
			target.toggleClass('collapsed').parents('li:eq(0)').find('>ul').toggle();
			e.preventDefault();
		}
	}).addClass('expand-collapse').find('li ul li span.expand-collapse').addClass('collapsed');
	
	$('<p class="classify-viewmode-selector"><span class="title">Разделы:</span><a href="#" class="linked active">выбранные</a><a href="#" class="tree">все</a></p>').insertBefore('.classify-viewmode-tree');
	$('<div class="classify-viewmode-linked"><p class="none">Этот документ не привязан ни к одному из разделов.</p></div>').insertAfter('.classify-viewmode-selector');
	$('div.classify-viewmode-tree').hide();
	
	// переключение между режимами
	$('a.linked, a.tree').click(function() {
		if (!$(this).is('.active') ) {
			$('div.classify-viewmode-linked, div.classify-viewmode-tree').toggle();
			$(this).siblings().andSelf().toggleClass('active');
		}
		return false;
	});
	
	// вывод путей к разделам
	var parents = {};
	
	parents['id' + $('ul.classify>li:eq(0)>span.container>input').val()] = {
		'title': $('ul.classify>li:eq(0)>span.container>span.name').text()
	};
	
	function parseChildren(name, elements) {
		elements.each(function() {
			parents['id' + $(this).find('input[name="sections[]"]').val()] = {
				'parent': name,
				'title': $(this).find('>span.container>span.name').text()
			};
			parseChildren('id' + $(this).find('input[name="sections[]"]').val(), $(this).find('>ul>li') );
		});
	}
	
	parseChildren('id' + $('ul.classify>li:eq(0)>span.container>input').val(), $('ul.classify>li>ul>li') );
	
	function getPath(id) {
		var path = [], html = '';
		function traverse(name) {
			var el = parents[name];
			if (el) {
				path.push(el.title);
				traverse(el.parent);
			}
		}
		traverse('id' + id);
		html = path.reverse().join(' / ');
		return html;
	}
	
	// выделение элементов в соседних режимах отображения
	var linkedList = $('<div class="classify-linked-list"></div>').appendTo('.classify-viewmode-linked');
	
	if ($('ul.classify input:checked').length) {
		$('ul.classify input:checked').each(function() {
			var path = getPath($(this).val() );
			$('<p><input type="checkbox" checked="checked" name="sections[]" value="' + $(this).val() + '">' + path + '</p>').appendTo(linkedList);
		});
		$('p.none').hide();
	}
	
	$('input:checkbox', linkedList).live('change', function() {
		$('ul.classify input:checkbox[value="' + $(this).val() + '"]').attr('checked', $(this).attr('checked') );
	});
	
	$('ul.classify input:checkbox').change(function() {
		
		var partner = linkedList.find('input:checkbox[value="' + $(this).val() + '"]');
		
		if (!partner.length && $(this).attr('checked') ) {
			var path = getPath($(this).val() );
			linkedList.append($('<p><input type="checkbox" checked="checked" name="sections[]" value="' + $(this).val() + '">' + path + '</p>') );
		}
		
		if ($(this).attr('checked') == 'checked') {
			partner.attr('checked', 'checked');
		} else {
			partner.parent().remove();
		}
		
		if (linkedList.find('input').length === 0) {
			$('p.none').show();
		} else {
			$('p.none').hide();
		}
	});
	
	// массовые операции
	$('<p class="classify-masscontrols"><a href="#" class="expand">раскрыть все дерево</a><a href="#" class="all">выбрать все</a><a href="#" class="none">снять все</a></p>').prependTo('div.classify-viewmode-tree');
	
	$('.classify-masscontrols .expand').click(function() {
		$('ul.classify ul').show();
		$('ul.classify ul li span.expand-collapse').removeClass('collapsed');
		return false;
	});
	
	$('.classify-masscontrols .all').click(function(e) {
		$('ul.classify input:checkbox').attr('checked', 'checked').change();
		e.preventDefault();
	});
	
	$('.classify-masscontrols .none').click(function(e) {
		$('ul.classify input:checkbox').removeAttr('checked').change();
		e.preventDefault();
	});
	
	// всплывающие блоки
	$('<span class="extra" />').insertAfter('li.with-children>span.container>span.name').click(function(e) {
		var content = $('<ul><li><a href="#" class="all">Отметить все</a></li><li><a href="#" class="none">Снять отметку</a></li></ul>');
		var box = mcms.infobox(content, e, { 'classes': 'classify' });
		var that = $(this);
		box.find('a.none').click(function(e) {
			that.parents('li:eq(0)').find('input:checkbox').removeAttr('checked').change();
			e.preventDefault();
		});
		box.find('a.all').click(function(e) {
			that.parents('li:eq(0)').find('input:checkbox').attr('checked', 'checked').change();
			e.preventDefault();
		});
		return false;
	});
	
});/**
 * Copyright (c) 2005 - 2009, James Auldridge
 * All rights reserved.
 *
 * Licensed under the BSD, MIT, and GPL (your choice!) Licenses:
 *  http://code.google.com/p/cookies/wiki/License
 *
 */
var jaaulde=window.jaaulde||{};jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function()
{var cookies=[];var defaultOptions={hoursToLive:null,path:'/',domain:null,secure:false};var resolveOptions=function(options)
{var returnValue;if(typeof options!=='object'||options===null)
{returnValue=defaultOptions;}
else
{returnValue={hoursToLive:(typeof options.hoursToLive==='number'&&options.hoursToLive!==0?options.hoursToLive:defaultOptions.hoursToLive),path:(typeof options.path==='string'&&options.path!==''?options.path:defaultOptions.path),domain:(typeof options.domain==='string'&&options.domain!==''?options.domain:defaultOptions.domain),secure:(typeof options.secure==='boolean'&&options.secure?options.secure:defaultOptions.secure)};}
return returnValue;};var expiresGMTString=function(hoursToLive)
{var dateObject=new Date();dateObject.setTime(dateObject.getTime()+(hoursToLive*60*60*1000));return dateObject.toGMTString();};var assembleOptionsString=function(options)
{options=resolveOptions(options);return((typeof options.hoursToLive==='number'?'; expires='+expiresGMTString(options.hoursToLive):'')+'; path='+options.path+
(typeof options.domain==='string'?'; domain='+options.domain:'')+
(options.secure===true?'; secure':''));};var splitCookies=function()
{cookies={};var pair,name,value,separated=document.cookie.split(';');for(var i=0;i<separated.length;i=i+1)
{pair=separated[i].split('=');name=pair[0].replace(/^\s*/,'').replace(/\s*$/,'');value=decodeURIComponent(pair[1]);cookies[name]=value;}
return cookies;};var constructor=function(){};constructor.prototype.get=function(cookieName)
{var returnValue;splitCookies();if(typeof cookieName==='string')
{returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null;}
else if(typeof cookieName==='object'&&cookieName!==null)
{returnValue={};for(var item in cookieName)
{if(typeof cookies[cookieName[item]]!=='undefined')
{returnValue[cookieName[item]]=cookies[cookieName[item]];}
else
{returnValue[cookieName[item]]=null;}}}
else
{returnValue=cookies;}
return returnValue;};constructor.prototype.filter=function(cookieNameRegExp)
{var returnValue={};splitCookies();if(typeof cookieNameRegExp==='string')
{cookieNameRegExp=new RegExp(cookieNameRegExp);}
for(var cookieName in cookies)
{if(cookieName.match(cookieNameRegExp))
{returnValue[cookieName]=cookies[cookieName];}}
return returnValue;};constructor.prototype.set=function(cookieName,value,options)
{if(typeof value==='undefined'||value===null)
{if(typeof options!=='object'||options===null)
{options={};}
value='';options.hoursToLive=-8760;}
var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString;};constructor.prototype.del=function(cookieName,options)
{var allCookies={};if(typeof options!=='object'||options===null)
{options={};}
if(typeof cookieName==='boolean'&&cookieName===true)
{allCookies=this.get();}
else if(typeof cookieName==='string')
{allCookies[cookieName]=true;}
for(var name in allCookies)
{if(typeof name==='string'&&name!=='')
{this.set(name,null,options);}}};constructor.prototype.test=function()
{var returnValue=false,testName='cT',testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue)
{this.del(testName);returnValue=true;}
return returnValue;};constructor.prototype.setOptions=function(options)
{if(typeof options!=='object')
{options=null;}
defaultOptions=resolveOptions(options);};return new constructor();})();(function()
{if(window.jQuery)
{(function($)
{$.cookies=jaaulde.utils.cookies;var extensions={cookify:function(options)
{return this.each(function()
{var i,resolvedName=false,resolvedValue=false,name='',value='',nameAttrs=['name','id'],nodeName,inputType;for(i in nameAttrs)
{if(!isNaN(i))
{name=$(this).attr(nameAttrs[i]);if(typeof name==='string'&&name!=='')
{resolvedName=true;break;}}}
if(resolvedName)
{nodeName=this.nodeName.toLowerCase();if(nodeName!=='input'&&nodeName!=='textarea'&&nodeName!=='select'&&nodeName!=='img')
{value=$(this).html();resolvedValue=true;}
else
{inputType=$(this).attr('type');if(typeof inputType==='string'&&inputType!=='')
{inputType=inputType.toLowerCase();}
if(inputType!=='radio'&&inputType!=='checkbox')
{value=$(this).val();resolvedValue=true;}}
if(resolvedValue)
{if(typeof value!=='string'||value==='')
{value=null;}
$.cookies.set(name,value,options);}}});},cookieFill:function()
{return this.each(function()
{var i,resolvedName=false,name='',value,nameAttrs=['name','id'],iteration=0,nodeName;for(i in nameAttrs)
{if(!isNaN(i))
{name=$(this).attr(nameAttrs[i]);if(typeof name==='string'&&name!=='')
{resolvedName=true;break;}}}
if(resolvedName)
{value=$.cookies.get(name);if(value!==null)
{nodeName=this.nodeName.toLowerCase();if(nodeName==='input'||nodeName==='textarea'||nodeName==='select')
{$(this).val(value);}
else
{$(this).html(value);}}}
iteration=0;});},cookieBind:function(options)
{return this.each(function()
{$(this).cookieFill().change(function()
{$(this).cookify(options);});});}};$.each(extensions,function(i)
{$.fn[i]=this;});})(window.jQuery);}})();$(function () {
  $('#nodesections .toggle').change(function () {
    $(this).parents('table:eq(0)').find('tbody input[@type="checkbox"]').attr('checked', $(this).attr('checked'));
  });
});
;$(function () {
	/* Сворачивание/разворачивание списка разделов
	------------------------------------------------------------------------------------------------------------------- */
	$('form ul.taxonomy').click(function(e) {
		var target = $(e.target);
		if (target.is('span.expand-collapse') ) {
			target.toggleClass('collapsed').parents('li:eq(0)').find('>ul').toggle();
			return false;
		}
	}).addClass('expand-collapse').find('li ul li span.expand-collapse').addClass('collapsed');
	if ($('form ul.taxonomy').length) {
		if ($.cookies.get('expandedTags') ) {
			var expandedTags = $.cookies.get('expandedTags').split('-');
			$.each(expandedTags, function(k, v) {
				$('form ul.taxonomy li>span.container a.picker[href*="node/' + v + '/"]').parents('li:eq(0)').find('>ul').show().end().find('>span.expand-collapse').removeClass('collapsed');
			});
		}
		$(window).unload(function() {
			var expandedTags = [];
			$('form ul.taxonomy li:has(>ul:visible)').each(function() {
				expandedTags.push($(this).find('>span.container a.picker').attr('href').match(/node\/(\d+)/)[1] );
			});
			$.cookies.set('expandedTags', expandedTags.join('-'), { path:'/admin/structure/', hoursToLive:8760 });
		});
	}
	/* ---------------------------------------------------------------------------------------------------------------- */
});
;/**
 * Если определена переменная tinyMcePicker, все клики по ссылкам
 * внутри таблицы расцениваются как попытка выбора картинки. В строке,
 * в которую кликнул пользователь, находится ссылка с картинкой (превью),
 * и ссылка на полную картинку возвращается в TinyMCE.
 */
$(function(){
  if (typeof tinyMcePicker != 'undefined' && typeof tinyMCEPopup != 'undefined') {
    $('td a').click(function () {
      try {
        var url = $(this).hasClass('return')
          ? $(this).attr('href')
          : $(this).parents('tr:first').find('a img').parent().attr('href');

        var win = tinyMCEPopup.getWindowArg("window");
        win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = url;

        if (win.ImageDialog) {
          // for image browsers: update image dimensions
          if (win.ImageDialog.getImageData)
            win.ImageDialog.getImageData();
          if (win.ImageDialog.showPreviewImage)
            win.ImageDialog.showPreviewImage(URL);
        }

        tinyMCEPopup.close();
      } catch (e) {
        alert(e);
      }
      return false;
    });
  }
});

function mcms_file_pick(field_name, url, type, win)
{
  var picker = mcms_path + mcms_lp + 'admin/content/files?bare=1&tinymcepicker=' + field_name +'&window='+ (win === undefined ? 'find' : win.name);

  if (type == 'image')
    picker += '&scope=image&mode=icons';

  // Параметр не определён только при нажатии в ссылку «подобрать»
  if (win === undefined) {
    window.open(picker);
    return;
  }

  else {
    tinyMCE.activeEditor.windowManager.open({
      file : picker,
      title : 'Файловый архив Molinos CMS',
      width : 720,
      height : 580,
      resizable : "yes",
      inline : "yes",  // This parameter only has an effect if you use the inlinepopups plugin!
      close_previous : "no",
      popup_css : false
    }, {
      window : win,
      input : field_name
    });

    return false;
  }
}

function mcms_tinymce_pick(fileid,picker)
{
  try {
    var wod = window.opener.document;
    var em = wod.getElementById(picker);

    if (em) {
      em.value = href;
    } else if (em = wod.getElementById('mce_0_ifr')) {
      var src = jQuery(em.contentDocument).find('#'+ picker);
      if (src.length == 0) {
        alert('Error accessing the parent dialog.');
      } else {
        src.val(href);
      }
    } else {
      alert('Target control not found');
    }
  } catch (e) {
    alert(e);
  }

  window.close();
}
;$(document).ready(function(){
  if (typeof mcmstbid != 'undefined') {
    $.getJSON(mcms_lp + 'api/toolbar/get.json?node=' + mcmstbid + '&from=' + escape(window.location.href), function (r) {
      if ('ok' == r.status) {
        $('body').prepend(r.html).find('.trigger').click(function(){
          var o = $(this).offset();
          $('#mcmstb .ulw').css({
            'position': 'absolute',
            'z-index': 500,
            'left': o.left - 20 + 'px',
            'top': o.top + 20 + 'px',
            'display': 'block'
          });
          // Подавляем дальнейшую обработку клика, чтобы меню тут же не скрылось.
          return false;
        });
      }
    });
    $().click(function(){
      $('#mcmstb .ulw').hide();
    });
  }
});
;(function($){
	
	var lang = location.pathname.match(/^\/(\w+)\//) ? location.pathname.match(/^\/(\w+)\//)[1] : 'ru';
	var local = {
		photo : 'фотография'
	};
	if (lang == 'en') {
		local.photo = 'image';
	}
	
    $.fn.popeye = function(options){
        var obj = $(this);
        var enPlaceholder = $('<div />');
        var opts = $.extend({}, $.fn.popeye.defaults, options);
        function debug(text){
            if (window.console && window.console.log) {
                window.console.log(text);
            }
        }
        return this.each(function(){
            function display(i, transition){
                transition = transition || false;
                var stageIm = {
                    backgroundImage: 'url(' + im.small[i] + ')',
                    backgroundPosition: 'center'
                };
                if (transition) {
                    ppyStage.fadeTo(100, 0, function(){
                        $(this).css(stageIm).fadeTo(100, 1);
                    });
                }
                else {
                    ppyStage.css(stageIm);
                }
                ppyStage.click(function(){
                    ppyStage.unbind();
                    enlarge(cur);
                });
                ppyCap.text(im.title[i]);
                ppyTotal.text(' ' + tot);
                ppyCur.text((cur + 1) + ' ');
            }
            function enlarge(i){
                var imHeight = obj.outerHeight();
                var imWidth = obj.outerWidth();
                var imTop = obj.offset().top - parseInt(obj.css('marginTop'), 10);
                var imLeft = obj.offset().left - parseInt(obj.css('marginLeft'), 10);
                var imRight = $(window).width() - (obj.offset().left + imWidth) - parseInt(obj.css('marginRight'), 10);
                var imFloat = obj.css('float');
                var imMarginTop = obj.css('margin-top');
                var imMarginRight = obj.css('margin-right');
                var imMarginBottom = obj.css('margin-bottom');
                var imMarginLeft = obj.css('margin-left');
                var cssEnlargedPpy = {
                    position: 'absolute',
                    top: imTop,
                    zIndex: '100'
                };
                if (opts.direction == 'left') {
                    cssEnlargedPpy.left = imLeft;
                }
                else 
                    if (opts.direction == 'right') {
                        cssEnlargedPpy.right = imRight;
                    }
                var cssPlaceholder = {
                    height: imHeight,
                    width: imWidth,
                    'float': imFloat,
                    marginTop: imMarginTop,
                    marginRight: imMarginRight,
                    marginBottom: imMarginBottom,
                    marginLeft: imMarginLeft
                };
                enPlaceholder.css(cssPlaceholder);
                obj.after(enPlaceholder);
                obj.prependTo($('body'));
                obj.css(cssEnlargedPpy);
                obj.addClass(opts.eclass);
                ppyTools.css('visibility', 'hidden');
                ppyStageWrap.addClass(opts.lclass);
                ppyStage.fadeTo((opts.duration / 2), 0);
                var preloader = new Image();
                preloader.onload = function(){
                    var imWidth = preloader.width;
                    var imHeight = preloader.height;
                    var cssStageIm = {
                        backgroundImage: 'url(' + im.large[i] + ')',
                        backgroundPosition: 'left top'
                    };
                    var cssStageTo = {
                        width: imWidth,
                        height: imHeight
                    };
                    ppyCap.css('visibility', 'hidden');
                    ppyStage.animate(cssStageTo, {
                        queue: false,
                        duration: opts.duration,
                        easing: opts.easing,
                        complete: function(){
                            ppyCap.data('width', ppyCap.css('width')).css('width', ppyCap.parent().width()).css('visibility', 'visible');
                            ppyStage.click(function(){
                                ppyStage.unbind();
                                ppyStage.removeAttr('title');
                                compact(cur);
                            });
                            ppyStage.attr('title', opts.clabel);
                            $(this).css(cssStageIm).fadeTo((opts.duration / 2), 1);
                        }
                    });
                };
                preloader.src = im.large[i];
            }
            function compact(i){
                ppyCap.css('visibility', 'hidden').css('width', ppyCap.data('width'));
                ppyStage.fadeTo((opts.duration / 2), 0).animate(cssCompactStage, {
                    queue: false,
                    duration: opts.duration,
                    easing: opts.easing,
                    complete: function(){
                        ppyCap.css('visibility', 'visible');
                        enPlaceholder.after(obj);
                        obj.css(cssCompactPpy);
                        ppyTools.css('visibility', 'visible');
                        obj.removeClass(opts.eclass);
                        enPlaceholder.remove();
                        display(cur);
                        $(this).fadeTo((opts.duration / 2), 1, function(){
                            ppyStageWrap.removeClass(opts.lclass);
                        });
                    }
                });
            }
            var im = {
                small: [],
                title: [],
                large: [],
                width: [],
                height: []
            };
            var maxWidth = 1000;
            var maxHeight = 1000;
            obj.find('li').each(function(i){
                im.small[i] = $(this).find('img').attr('src');
                im.title[i] = $(this).find('img').attr('alt');
                im.large[i] = $(this).find('a').attr('href');
                im.width[i] = $(this).find('img').width();
                im.height[i] = $(this).find('img').height();
                if (maxWidth > im.width[i]) {
                    maxWidth = im.width[i];
                }
                if (maxHeight > im.height[i]) {
                    maxHeight = im.height[i];
                }
            });
            if (opts.stageW) {
                maxWidth = opts.stageW;
            }
            if (opts.stageH) {
                maxHeight = opts.stageH;
            }
            var cur = 0;
            var tot = im.small.length;
            obj.find('ul').remove();
            var ppyStageWrap = $('<div class="popeye-stagewrap" />');
            var ppyStage = $('<div class="popeye-stage" />');
            var ppyToolsWrap = $('<div class="popeye-tools-wrap" />');
            var ppyTools = $('<div class="popeye-tools" />');
            var ppyCount = $('<span class="popeye-count">' + local.photo + ' </span>');
            var ppyCur = $('<em class="popeye-cur" />');
            var ppyTotal = $('<em class="popeye-total" />');
            var ppyPrev = $('<a href="#" class="popeye-prev">' + opts.plabel + '</a>');
            var ppyNext = $('<a href="#" class="popeye-next">' + opts.nlabel + '</a>');
            var ppyCap = $('<div class="popeye-cap" />');
            obj.append(ppyStageWrap);
            ppyStageWrap.append(ppyStage);
            ppyStageWrap.before(ppyTools);
            ppyStageWrap.after(ppyCap);
            ppyTools.append(ppyPrev);
            ppyTools.append(ppyCount);
            ppyCount.append(ppyCur);
            ppyCount.append(ppyTotal);
            ppyCur.after(opts.oflabel);
            ppyTools.append(ppyNext);
            var cssCompactPpy = {
                position: 'relative',
                overflow: 'hidden',
                height: 'auto',
                overflow: 'hidden',
                top: 0
            };
            if (opts.direction == 'left') {
                cssCompactPpy.left = 0;
            }
            else 
                if (opts.direction == 'right') {
                    cssCompactPpy.right = 0;
                }
            var cssCompactStage = {
                width: maxWidth,
                height: maxHeight
            };
            var cssPpyCap = {
                width: maxWidth
            };
            var ppyToolsWidth = parseInt(maxWidth, 10);
            if (!isNaN(parseInt(ppyTools.css('borderLeftWidth'), 10))) {
                ppyToolsWidth = ppyToolsWidth - parseInt(ppyTools.css('borderLeftWidth'), 10);
            }
            if (!isNaN(parseInt(ppyTools.css('borderRightWidth'), 10))) {
                ppyToolsWidth = ppyToolsWidth - parseInt(ppyTools.css('borderRightWidth'), 10);
            }
            ppyToolsWidth = ppyToolsWidth - parseInt(ppyTools.css('paddingLeft'), 10);
            ppyToolsWidth = ppyToolsWidth - parseInt(ppyTools.css('paddingRight'), 10);
            if (!isNaN(parseInt(ppyTools.css('marginLeft'), 10))) {
                ppyToolsWidth = ppyToolsWidth - parseInt(ppyTools.css('marginLeft'), 10);
            }
            if (!isNaN(parseInt(ppyTools.css('marginRight'), 10))) {
                ppyToolsWidth = ppyToolsWidth - parseInt(ppyTools.css('marginRight'), 10);
            }
            ppyToolsWidth = ppyToolsWidth + 'px';
            var cssPpyTools = {
                width: ppyToolsWidth
            };
            obj.css(cssCompactPpy);
            if (opts.jclass) {
                obj.addClass(opts.jclass);
            }
            ppyStage.css(cssCompactStage);
            ppyCap.css(cssPpyCap);
            ppyTools.css(cssPpyTools);
            display(cur);
            ppyPrev.click(function(){
                if (cur <= 0) {
                    cur = tot - 1;
                }
                else {
                    cur--;
                }
                display(cur, true);
                return false;
            });
            ppyNext.click(function(){
                if (cur < (tot - 1)) {
                    cur++;
                }
                else {
                    cur = 0;
                }
                display(cur, true);
                return false;
            });
        });
    };
    $.fn.popeye.defaults = {
        jclass: 'popeye-hasjs',
        eclass: 'popeye-haspopped',
        lclass: 'popeye-isloading',
        direction: 'left',
        duration: 400,
        easing: 'swing',
        nlabel: 'next',
        plabel: 'previous',
        oflabel: 'of',
        blabel: 'enlarge',
        clabel: 'Click to close'
    };
})(jQuery);
;/**
 * jQuery.Preload - Multifunctional preloader
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Dual licensed under MIT and GPL.
 * Date: 3/12/2008
 * @author Ariel Flesler
 * @version 1.0.7
 */
;(function($){var n=$.preload=function(c,d){if(c.split)c=$(c);d=$.extend({},n.defaults,d);var f=$.map(c,function(a){if(!a)return;if(a.split)return d.base+a+d.ext;var b=a.src||a.href;if(typeof d.placeholder=='string'&&a.src)a.src=d.placeholder;if(b&&d.find)b=b.replace(d.find,d.replace);return b||null}),g={loaded:0,failed:0,next:0,done:0,total:f.length};if(!g.total)return m();var h='<img/>',j=d.threshold;while(--j>0)h+='<img/>';h=$(h).load(k).error(k).bind('abort',k).each(l);function k(e){g.found=e.type=='load';g.image=this.src;var a=g.original=c[this.index];g[g.found?'loaded':'failed']++;g.done++;if(d.placeholder&&a.src)a.src=g.found?g.image:d.notFound||a.src;if(d.onComplete)d.onComplete(g);if(g.done<g.total)l(0,this);else{if(h.unbind)h.unbind('load').unbind('error').unbind('abort');h=null;m()}};function l(i,a,b){if($.browser.msie&&g.next&&g.next%n.gap==0&&!b){setTimeout(function(){l(i,a,1)},0);return!1}if(g.next==g.total)return!1;a.index=g.next;a.src=f[g.next++];if(d.onRequest){g.image=a.src;g.original=c[g.next-1];d.onRequest(g)}};function m(){if(d.onFinish)d.onFinish(g)}};n.gap=14;n.defaults={threshold:2,base:'',ext:'',replace:''};$.fn.preload=function(a){n(this,a);return this}})(jQuery);/**
 * jQuery mcms.tabber plugin
 * 
 * @projectDescription Lightweight plugin to create tabbed navigation
 * @requirements html structure must be smth like this: <div class="tabs">{<div class="tab"><h3>Header</h3>Content</div>}*n</div>. 
 * Elements and classes are customizable, see below.
 * @version 0.3.2(18/02/2009)
 * @copyright 2009 Molinos CMS Development Team, Dmitriy Chekanov
 * @example
 * 
 * with default options: 
	$('.tabbed').tabber(); 
 * 
 * custom options: 
	$('.tabbed').tabber({
		active: 0,
		selectors: {
			tabContainer: 'fieldset.tabable',
			tabTitle: '>legend'
		}
	});
 * 
 * Licensed under the GNU General Public License v2 :
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 */

 (function($) {
	
	$.extend({
		tabber: {
			defaults: {
				selectors: {
					tabContainer: 'div.t-me',
					tabTitle: '>h2'
				},
				removeTitles: true,
				active: 0,
				callbacks: {}
			}
		}
	});
	
	var showTab = function(tabs, idx) {
		tabs.each(function(i) {
			if (i != idx) {
				$(this).css({
					position: 'absolute',
					top: '-9999px'
				});
			} else {
				$(this).css({
					position: 'static',
					top: '0'
				});
			}
		});
	};
	
	$.fn.tabber = function(options) {
		// extending default params
		var o = $.extend({}, $.tabber.defaults, options);
		
		this.addClass('tabber-container');
	
		return this.each(function() {
			var tabs = $(o.selectors.tabContainer, this).addClass('tabber-tab');
			var titles = $(o.selectors.tabTitle, tabs);
			var navigation = $('<ul class="tabber-navigation" />');
			
			titles.each(function(i) {
				var element = $('<li><a href="#"><span class="outer"><span class="inner">' + $(this).text() + '</span></span></a></li>');
				element.find('a').click(o.callbacks.onBeforeShow);
				element.find('a').click(function() {
					showTab(tabs, i);
					$(this).parents('li:eq(0)').addClass('active').siblings().removeClass('active');
					return false;
				});
				if (i == o.active) {
					element.addClass('active');
				}
				navigation.append(element);
			});
			
			$(this).prepend(navigation);
			
			if (o.removeTitles === true) {
				titles.remove();
			}

			showTab(tabs, o.active);
		});
		
	};
	
})(jQuery);;(function($){$.ifixpng=function(customPixel){$.ifixpng.pixel=customPixel;};$.ifixpng.regexp={bg:/^url\(["']?(.*\.png([?].*)?)["']?\)$/i,img:/.*\.png([?].*)?$/i},$.ifixpng.getPixel=function(){return $.ifixpng.pixel||'sites/default/themes/lenexpo/images/pixel.png';};var hack={base:$('base').attr('href'),ltie7:$.browser.msie&&$.browser.version<7,filter:function(src){return"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";}};$.fn.ifixpng=hack.ltie7?function(){function fixImage(image,source,width,height,hidden){image.css({filter:hack.filter(source),width:width,height:height}).attr({src:$.ifixpng.getPixel()}).positionFix();}
return this.each(function(){var $$=$(this);if($$.is('img')||$$.is('input')){var source,img;if(this.src&&this.src.match($.ifixpng.regexp.img)){source=(hack.base&&this.src.substring(0,1)!='/'&&this.src.indexOf(hack.base)===-1)?hack.base+this.src:this.src;if(!this.width||!this.height){$(new Image()).one('load',function(){fixImage($$,source,this.width,this.height);$(this).remove();}).attr('src',source);}else fixImage($$,source,this.width,this.height);}}else if(this.style){var imageSrc=$$.css('backgroundImage');if(imageSrc&&imageSrc.match($.ifixpng.regexp.bg)&&this.currentStyle.backgroundRepeat=='no-repeat'){imageSrc=RegExp.$1;var x=this.currentStyle.backgroundPositionX||0,y=this.currentStyle.backgroundPositionY||0;if(x||y){var css={},img;if(typeof x!='undefined'){if(x=='left')css.left=0;else if(x=='right')css.right=$$.width()%2===1?-1:0;else css.left=x;}
if(typeof y!='undefined'){if(y=='bottom')css.bottom=$$.height()%2===1?-1:0;else if(y=='top')css.top=0;else css.top=y;}
img=new Image();$(img).one('load',function(){var x,y,expr={},prop;if(/center|%/.test(css.top)){expr.top="(this.parentNode.offsetHeight - this.offsetHeight) * "+(css.top=='center'?0.5:(parseInt(css.top)/100));delete css.top;}
if(/center|%/.test(css.left)){expr.left="(this.parentNode.offsetWidth - this.offsetWidth) * "+(css.left=='center'?0.5:(parseInt(css.left)/100));delete css.left;}
$$.positionFix().css({backgroundImage:'none'}).prepend($('<div></div>').css(css).css({width:this.width,height:this.height,position:'absolute',filter:hack.filter(imageSrc)}));if(expr.top||expr.left){var elem=$$.children(':first')[0];for(prop in expr)elem.style.setExpression(prop,expr[prop],'JavaScript');}
$(this).remove();});img.src=imageSrc;}else{$$.css({backgroundImage:'none',filter:hack.filter(imageSrc)});}}}});}:function(){return this;};$.fn.positionFix=function(){return this.each(function(){var $$=$(this);if($$.css('position')!='absolute')$$.css({position:'relative'});});};})(jQuery);/*	SWFObject v2.0 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var Z="undefined",P="object",B="Shockwave Flash",h="ShockwaveFlash.ShockwaveFlash",W="application/x-shockwave-flash",K="SWFObjectExprInst",G=window,g=document,N=navigator,f=[],H=[],Q=null,L=null,T=null,S=false,C=false;var a=function(){var l=typeof g.getElementById!=Z&&typeof g.getElementsByTagName!=Z&&typeof g.createElement!=Z&&typeof g.appendChild!=Z&&typeof g.replaceChild!=Z&&typeof g.removeChild!=Z&&typeof g.cloneNode!=Z,t=[0,0,0],n=null;if(typeof N.plugins!=Z&&typeof N.plugins[B]==P){n=N.plugins[B].description;if(n){n=n.replace(/^.*\s+(\S+\s+\S+$)/,"$1");t[0]=parseInt(n.replace(/^(.*)\..*$/,"$1"),10);t[1]=parseInt(n.replace(/^.*\.(.*)\s.*$/,"$1"),10);t[2]=/r/.test(n)?parseInt(n.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof G.ActiveXObject!=Z){var o=null,s=false;try{o=new ActiveXObject(h+".7")}catch(k){try{o=new ActiveXObject(h+".6");t=[6,0,21];o.AllowScriptAccess="always"}catch(k){if(t[0]==6){s=true}}if(!s){try{o=new ActiveXObject(h)}catch(k){}}}if(!s&&o){try{n=o.GetVariable("$version");if(n){n=n.split(" ")[1].split(",");t=[parseInt(n[0],10),parseInt(n[1],10),parseInt(n[2],10)]}}catch(k){}}}}var v=N.userAgent.toLowerCase(),j=N.platform.toLowerCase(),r=/webkit/.test(v)?parseFloat(v.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,i=false,q=j?/win/.test(j):/win/.test(v),m=j?/mac/.test(j):/mac/.test(v);/*@cc_on i=true;@if(@_win32)q=true;@elif(@_mac)m=true;@end@*/return{w3cdom:l,pv:t,webkit:r,ie:i,win:q,mac:m}}();var e=function(){if(!a.w3cdom){return }J(I);if(a.ie&&a.win){try{g.write("<script id=__ie_ondomload defer=true src=//:><\/script>");var i=c("__ie_ondomload");if(i){i.onreadystatechange=function(){if(this.readyState=="complete"){this.parentNode.removeChild(this);V()}}}}catch(j){}}if(a.webkit&&typeof g.readyState!=Z){Q=setInterval(function(){if(/loaded|complete/.test(g.readyState)){V()}},10)}if(typeof g.addEventListener!=Z){g.addEventListener("DOMContentLoaded",V,null)}M(V)}();function V(){if(S){return }if(a.ie&&a.win){var m=Y("span");try{var l=g.getElementsByTagName("body")[0].appendChild(m);l.parentNode.removeChild(l)}catch(n){return }}S=true;if(Q){clearInterval(Q);Q=null}var j=f.length;for(var k=0;k<j;k++){f[k]()}}function J(i){if(S){i()}else{f[f.length]=i}}function M(j){if(typeof G.addEventListener!=Z){G.addEventListener("load",j,false)}else{if(typeof g.addEventListener!=Z){g.addEventListener("load",j,false)}else{if(typeof G.attachEvent!=Z){G.attachEvent("onload",j)}else{if(typeof G.onload=="function"){var i=G.onload;G.onload=function(){i();j()}}else{G.onload=j}}}}}function I(){var l=H.length;for(var j=0;j<l;j++){var m=H[j].id;if(a.pv[0]>0){var k=c(m);if(k){H[j].width=k.getAttribute("width")?k.getAttribute("width"):"0";H[j].height=k.getAttribute("height")?k.getAttribute("height"):"0";if(O(H[j].swfVersion)){if(a.webkit&&a.webkit<312){U(k)}X(m,true)}else{if(H[j].expressInstall&&!C&&O("6.0.65")&&(a.win||a.mac)){D(H[j])}else{d(k)}}}}else{X(m,true)}}}function U(m){var k=m.getElementsByTagName(P)[0];if(k){var p=Y("embed"),r=k.attributes;if(r){var o=r.length;for(var n=0;n<o;n++){if(r[n].nodeName.toLowerCase()=="data"){p.setAttribute("src",r[n].nodeValue)}else{p.setAttribute(r[n].nodeName,r[n].nodeValue)}}}var q=k.childNodes;if(q){var s=q.length;for(var l=0;l<s;l++){if(q[l].nodeType==1&&q[l].nodeName.toLowerCase()=="param"){p.setAttribute(q[l].getAttribute("name"),q[l].getAttribute("value"))}}}m.parentNode.replaceChild(p,m)}}function F(i){if(a.ie&&a.win&&O("8.0.0")){G.attachEvent("onunload",function(){var k=c(i);if(k){for(var j in k){if(typeof k[j]=="function"){k[j]=function(){}}}k.parentNode.removeChild(k)}})}}function D(j){C=true;var o=c(j.id);if(o){if(j.altContentId){var l=c(j.altContentId);if(l){L=l;T=j.altContentId}}else{L=b(o)}if(!(/%$/.test(j.width))&&parseInt(j.width,10)<310){j.width="310"}if(!(/%$/.test(j.height))&&parseInt(j.height,10)<137){j.height="137"}g.title=g.title.slice(0,47)+" - Flash Player Installation";var n=a.ie&&a.win?"ActiveX":"PlugIn",k=g.title,m="MMredirectURL="+G.location+"&MMplayerType="+n+"&MMdoctitle="+k,p=j.id;if(a.ie&&a.win&&o.readyState!=4){var i=Y("div");p+="SWFObjectNew";i.setAttribute("id",p);o.parentNode.insertBefore(i,o);o.style.display="none";G.attachEvent("onload",function(){o.parentNode.removeChild(o)})}R({data:j.expressInstall,id:K,width:j.width,height:j.height},{flashvars:m},p)}}function d(j){if(a.ie&&a.win&&j.readyState!=4){var i=Y("div");j.parentNode.insertBefore(i,j);i.parentNode.replaceChild(b(j),i);j.style.display="none";G.attachEvent("onload",function(){j.parentNode.removeChild(j)})}else{j.parentNode.replaceChild(b(j),j)}}function b(n){var m=Y("div");if(a.win&&a.ie){m.innerHTML=n.innerHTML}else{var k=n.getElementsByTagName(P)[0];if(k){var o=k.childNodes;if(o){var j=o.length;for(var l=0;l<j;l++){if(!(o[l].nodeType==1&&o[l].nodeName.toLowerCase()=="param")&&!(o[l].nodeType==8)){m.appendChild(o[l].cloneNode(true))}}}}}return m}function R(AE,AC,q){var p,t=c(q);if(typeof AE.id==Z){AE.id=q}if(a.ie&&a.win){var AD="";for(var z in AE){if(AE[z]!=Object.prototype[z]){if(z=="data"){AC.movie=AE[z]}else{if(z.toLowerCase()=="styleclass"){AD+=' class="'+AE[z]+'"'}else{if(z!="classid"){AD+=" "+z+'="'+AE[z]+'"'}}}}}var AB="";for(var y in AC){if(AC[y]!=Object.prototype[y]){AB+='<param name="'+y+'" value="'+AC[y]+'" />'}}t.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AD+">"+AB+"</object>";F(AE.id);p=c(AE.id)}else{if(a.webkit&&a.webkit<312){var AA=Y("embed");AA.setAttribute("type",W);for(var x in AE){if(AE[x]!=Object.prototype[x]){if(x=="data"){AA.setAttribute("src",AE[x])}else{if(x.toLowerCase()=="styleclass"){AA.setAttribute("class",AE[x])}else{if(x!="classid"){AA.setAttribute(x,AE[x])}}}}}for(var w in AC){if(AC[w]!=Object.prototype[w]){if(w!="movie"){AA.setAttribute(w,AC[w])}}}t.parentNode.replaceChild(AA,t);p=AA}else{var s=Y(P);s.setAttribute("type",W);for(var v in AE){if(AE[v]!=Object.prototype[v]){if(v.toLowerCase()=="styleclass"){s.setAttribute("class",AE[v])}else{if(v!="classid"){s.setAttribute(v,AE[v])}}}}for(var u in AC){if(AC[u]!=Object.prototype[u]&&u!="movie"){E(s,u,AC[u])}}t.parentNode.replaceChild(s,t);p=s}}return p}function E(k,i,j){var l=Y("param");l.setAttribute("name",i);l.setAttribute("value",j);k.appendChild(l)}function c(i){return g.getElementById(i)}function Y(i){return g.createElement(i)}function O(k){var j=a.pv,i=k.split(".");i[0]=parseInt(i[0],10);i[1]=parseInt(i[1],10);i[2]=parseInt(i[2],10);return(j[0]>i[0]||(j[0]==i[0]&&j[1]>i[1])||(j[0]==i[0]&&j[1]==i[1]&&j[2]>=i[2]))?true:false}function A(m,j){if(a.ie&&a.mac){return }var l=g.getElementsByTagName("head")[0],k=Y("style");k.setAttribute("type","text/css");k.setAttribute("media","screen");if(!(a.ie&&a.win)&&typeof g.createTextNode!=Z){k.appendChild(g.createTextNode(m+" {"+j+"}"))}l.appendChild(k);if(a.ie&&a.win&&typeof g.styleSheets!=Z&&g.styleSheets.length>0){var i=g.styleSheets[g.styleSheets.length-1];if(typeof i.addRule==P){i.addRule(m,j)}}}function X(k,i){var j=i?"visible":"hidden";if(S){c(k).style.visibility=j}else{A("#"+k,"visibility:"+j)}}return{registerObject:function(l,i,k){if(!a.w3cdom||!l||!i){return }var j={};j.id=l;j.swfVersion=i;j.expressInstall=k?k:false;H[H.length]=j;X(l,false)},getObjectById:function(l){var i=null;if(a.w3cdom&&S){var j=c(l);if(j){var k=j.getElementsByTagName(P)[0];if(!k||(k&&typeof j.SetVariable!=Z)){i=j}else{if(typeof k.SetVariable!=Z){i=k}}}}return i},embedSWF:function(n,u,r,t,j,m,k,p,s){if(!a.w3cdom||!n||!u||!r||!t||!j){return }r+="";t+="";if(O(j)){X(u,false);var q=(typeof s==P)?s:{};q.data=n;q.width=r;q.height=t;var o=(typeof p==P)?p:{};if(typeof k==P){for(var l in k){if(k[l]!=Object.prototype[l]){if(typeof o.flashvars!=Z){o.flashvars+="&"+l+"="+k[l]}else{o.flashvars=l+"="+k[l]}}}}J(function(){R(q,o,u);if(q.id==u){X(u,true)}})}else{if(m&&!C&&O("6.0.65")&&(a.win||a.mac)){X(u,false);J(function(){var i={};i.id=i.altContentId=u;i.width=r;i.height=t;i.expressInstall=m;D(i)})}}},getFlashPlayerVersion:function(){return{major:a.pv[0],minor:a.pv[1],release:a.pv[2]}},hasFlashPlayerVersion:O,createSWF:function(k,j,i){if(a.w3cdom&&S){return R(k,j,i)}else{return undefined}},createCSS:function(j,i){if(a.w3cdom){A(j,i)}},addDomLoadEvent:J,addLoadEvent:M,getQueryParamValue:function(m){var l=g.location.search||g.location.hash;if(m==null){return l}if(l){var k=l.substring(1).split("&");for(var j=0;j<k.length;j++){if(k[j].substring(0,k[j].indexOf("="))==m){return k[j].substring((k[j].indexOf("=")+1))}}}return""},expressInstallCallback:function(){if(C&&L){var i=c(K);if(i){i.parentNode.replaceChild(L,i);if(T){X(T,true);if(a.ie&&a.win){L.style.display="block"}}L=null;T=null;C=false}}}}}();/* ------------------------------------------------------------------------
	Class: prettyPhoto
	Use: Lightbox clone for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 2.4.3
------------------------------------------------------------------------- */

var $pp_pic_holder;
var $ppt;

(function($) {
	$.fn.prettyPhoto = function(settings) {
		// global Variables
		var doresize = true;
		var percentBased = false;
		var imagesArray = [];
		var setPosition = 0; /* Position in the set */
		var pp_contentHeight;
		var pp_contentWidth;
		var pp_containerHeight;
		var pp_containerWidth;
		var pp_type = 'image';
	
		// Global elements
		var $caller;
		var $scrollPos = _getScroll();
	
		$(window).scroll(function(){ $scrollPos = _getScroll(); _centerPicture(); });
		$(window).resize(function(){ _centerPicture(); _resizeOverlay(); });
		
		$(document).keypress(function(e){
			switch(e.keyCode){
				/*
				case 37:
					if (setPosition == 1) return;
					changePicture('previous');
					break;
				case 39:
					if (setPosition == setCount) return;
					changePicture('next');
					break;
				*/
				case 27:
					close();
					break;
			};
	    });
	
		settings = jQuery.extend({
			animationSpeed: 'normal', /* fast/slow/normal */
			padding: 40, /* padding for each side of the picture */
			opacity: 0.80, /* Value between 0 and 1 */
			showTitle: true, /* true/false */
			allowresize: true, /* true/false */
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
			callback: function(){}
		}, settings);
		
		// Fallback to a supported theme for IE6
		if($.browser.msie && $.browser.version == 6){
			settings.theme = "light_square";
		}
	
		$(this).each(function(){
			var hasTitle = false;
			var isSet = false;
			var setCount = 0; /* Total images in the set */
			var arrayPosition = 0; /* Total position in the array */
			
			imagesArray[imagesArray.length] = this;
			$(this).bind('click',function(){
				open(this);
				return false;
			});
		});
	
		function open(el) {
			$caller = $(el);
		
			// Find out if the picture is part of a set
			theRel = $caller.attr('rel');
			galleryRegExp = /\[(?:.*)\]/;
			theGallery = galleryRegExp.exec(theRel);
		
			// Calculate the number of items in the set, and the position of the clicked picture.
			isSet = false;
			setCount = 0;
			
			_getFileType();
			
			for (i = 0; i < imagesArray.length; i++){
				if($(imagesArray[i]).attr('rel').indexOf(theGallery) != -1){
					setCount++;
					if(setCount > 1) isSet = true;

					if($(imagesArray[i]).attr('href') == $caller.attr('href')){
						setPosition = setCount;
						arrayPosition = i;
					};
				};
			};
		
			_buildOverlay();

			// Display the current position
			$pp_pic_holder.find('p.currentTextHolder').text(setPosition + settings.counter_separator_label + setCount);

			// Position the picture in the center of the viewing area
			_centerPicture();
		
			$('#pp_full_res').hide();
			$pp_pic_holder.find('.pp_loaderIcon').show();
		};
	
		showimage = function(width,height,containerWidth,containerHeight,contentHeight,contentWidth,resized){
			$('.pp_loaderIcon').hide();

			if($.browser.opera) {
				windowHeight = window.innerHeight;
				windowWidth = window.innerWidth;
			}else{
				windowHeight = $(window).height();
				windowWidth = $(window).width();
			};

			$pp_pic_holder.find('.pp_content').animate({'height':contentHeight},settings.animationSpeed);

			projectedTop = $scrollPos['scrollTop'] + ((windowHeight/2) - (containerHeight/2));
			if(projectedTop < 0) projectedTop = 0 + $pp_pic_holder.find('.ppt').height();

			// Resize the holder
			$pp_pic_holder.animate({
				'top': projectedTop,
				'left': ((windowWidth/2) - (containerWidth/2)),
				'width': containerWidth
			},settings.animationSpeed,function(){
				$pp_pic_holder.width(containerWidth);
				$pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(height).width(width);

				// Fade the new image
				$pp_pic_holder.find('#pp_full_res').fadeIn(settings.animationSpeed,function(){
					$(this).find('object,embed').css('visibility','visible');
				});

				// Show the nav elements
				_showContent();
			
				// Fade the resizing link if the image is resized
				if(resized) $('a.pp_expand,a.pp_contract').fadeIn(settings.animationSpeed);
			});
		};
		
		function _showContent(){
			// Show the nav
			if(isSet && pp_type=="image") { $pp_pic_holder.find('.pp_hoverContainer').fadeIn(settings.animationSpeed); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); }
			$pp_pic_holder.find('.pp_details').fadeIn(settings.animationSpeed);
			
			// Show the title
			if(settings.showTitle && hasTitle){
				$ppt.css({
					'top' : $pp_pic_holder.offset().top - 22,
					'left' : $pp_pic_holder.offset().left + (settings.padding/2),
					'display' : 'none'
				});
			
				$ppt.fadeIn(settings.animationSpeed);
			};
		}
		
		function _hideContent(){
			// Fade out the current picture
			$pp_pic_holder.find('.pp_hoverContainer,.pp_details').fadeOut(settings.animationSpeed);
			$pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');
			$pp_pic_holder.find('#pp_full_res').fadeOut(settings.animationSpeed,function(){
				$('.pp_loaderIcon').show();
			
				// Preload the image
				_preload();
			});
			
			// Hide the title
			$ppt.fadeOut(settings.animationSpeed);
		}
	
		function changePicture(direction){
			if(direction == 'previous') {
				arrayPosition--;
				setPosition--;
			}else{
				arrayPosition++;
				setPosition++;
			};

			// Allow the resizing of the images
			if(!doresize) doresize = true;

			_hideContent();
			$('a.pp_expand,a.pp_contract').fadeOut(settings.animationSpeed,function(){
				$(this).removeClass('pp_contract').addClass('pp_expand');
			});
		};
	
		function close(){
			$pp_pic_holder.find('object,embed').css('visibility','hidden');
			
			$('div.pp_pic_holder,div.ppt').fadeOut(settings.animationSpeed);
			
			$('div.pp_overlay').fadeOut(settings.animationSpeed, function(){
				$('div.pp_overlay,div.pp_pic_holder,div.ppt').remove();
			
				// To fix the bug with IE select boxes
				if($.browser.msie && $.browser.version == 6){
					$('select').css('visibility','visible');
				};
				
				settings.callback();
			});
			
			doresize = true;
		};
	
		function _checkPosition(){
			// If at the end, hide the next link
			if(setPosition == setCount) {
				$pp_pic_holder.find('a.pp_next').css('visibility','hidden');
				$pp_pic_holder.find('a.pp_arrow_next').addClass('disabled').unbind('click');
			}else{ 
				$pp_pic_holder.find('a.pp_next').css('visibility','visible');
				$pp_pic_holder.find('a.pp_arrow_next.disabled').removeClass('disabled').bind('click',function(){
					changePicture('next');
					return false;
				});
			};
		
			// If at the beginning, hide the previous link
			if(setPosition == 1) {
				$pp_pic_holder.find('a.pp_previous').css('visibility','hidden');
				$pp_pic_holder.find('a.pp_arrow_previous').addClass('disabled').unbind('click');
			}else{
				$pp_pic_holder.find('a.pp_previous').css('visibility','visible');
				$pp_pic_holder.find('a.pp_arrow_previous.disabled').removeClass('disabled').bind('click',function(){
					changePicture('previous');
					return false;
				});
			};
		
			// Change the current picture text
			$pp_pic_holder.find('p.currentTextHolder').text(setPosition + settings.counter_separator_label + setCount);
		
			$caller = (isSet) ? $(imagesArray[arrayPosition]) : $caller;
			_getFileType();

			if($caller.attr('title')){
				$pp_pic_holder.find('.pp_description').show().html(unescape($caller.attr('title')));
			}else{
				$pp_pic_holder.find('.pp_description').hide().text('');
			};
		
			if($caller.find('img').attr('alt') && settings.showTitle){
				hasTitle = true;
				$ppt.html(unescape($caller.find('img').attr('alt')));
			}else{
				hasTitle = false;
			};
		};
	
		function _fitToViewport(width,height){
			hasBeenResized = false;
		
			_getDimensions(width,height);
			
			// Define them in case there's no resize needed
			imageWidth = width;
			imageHeight = height;

			windowHeight = $(window).height();
			windowWidth = $(window).width();
		
			if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allowresize && !percentBased) {
				hasBeenResized = true;
				notFitting = true;
			
				while (notFitting){
					if((pp_containerWidth > windowWidth)){
						imageWidth = (windowWidth - 200);
						imageHeight = (height/width) * imageWidth;
					}else if((pp_containerHeight > windowHeight)){
						imageHeight = (windowHeight - 200);
						imageWidth = (width/height) * imageHeight;
					}else{
						notFitting = false;
					};

					pp_containerHeight = imageHeight;
					pp_containerWidth = imageWidth;
				};
			
				_getDimensions(imageWidth,imageHeight);
			};

			return {
				width:imageWidth,
				height:imageHeight,
				containerHeight:pp_containerHeight,
				containerWidth:pp_containerWidth,
				contentHeight:pp_contentHeight,
				contentWidth:pp_contentWidth,
				resized:hasBeenResized
			};
		};
		
		function _getDimensions(width,height){
			$pp_pic_holder.find('.pp_details').width(width).find('.pp_description').width(width - parseFloat($pp_pic_holder.find('a.pp_close').css('width'))); /* To have the correct height */
			
			// Get the container size, to resize the holder to the right dimensions
			pp_contentHeight = height + $pp_pic_holder.find('.pp_details').height() + parseFloat($pp_pic_holder.find('.pp_details').css('marginTop')) + parseFloat($pp_pic_holder.find('.pp_details').css('marginBottom'));
			pp_contentWidth = width;
			pp_containerHeight = pp_contentHeight + $pp_pic_holder.find('.ppt').height() + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height();
			pp_containerWidth = width + settings.padding;
		}
	
		function _getFileType(){
			if ($caller.attr('href').match(/youtube\.com\/watch/i)) {
				pp_type = 'youtube';
			}else if($caller.attr('href').indexOf('.mov') != -1){ 
				pp_type = 'quicktime';
			}else if($caller.attr('href').indexOf('.swf') != -1){
				pp_type = 'flash';
			}else if($caller.attr('href').indexOf('iframe') != -1){
				pp_type = 'iframe'
			}else{
				pp_type = 'image';
			}
		}
	
		function _centerPicture(){
			if ($pp_pic_holder){ if($pp_pic_holder.size() == 0){ return; }}else{ return; }; //Make sure the gallery is open

			if($.browser.opera) {
				windowHeight = window.innerHeight;
				windowWidth = window.innerWidth;
			}else{
				windowHeight = $(window).height();
				windowWidth = $(window).width();
			};
		
			if(doresize) {
				$pHeight = $pp_pic_holder.height();
				$pWidth = $pp_pic_holder.width();
				$tHeight = $ppt.height();
				
				projectedTop = (windowHeight/2) + $scrollPos['scrollTop'] - ($pHeight/2);
				if(projectedTop < 0) projectedTop = 0 + $tHeight;
				
				$pp_pic_holder.css({
					'top': projectedTop,
					'left': (windowWidth/2) + $scrollPos['scrollLeft'] - ($pWidth/2)
				});
		
				$ppt.css({
					'top' : projectedTop - $tHeight,
					'left' : (windowWidth/2) + $scrollPos['scrollLeft'] - ($pWidth/2) + (settings.padding/2)
				});
			};
		};
	
		function _preload(){
			// Hide the next/previous links if on first or last images.
			_checkPosition();
		
			if(pp_type == 'image'){
				// Set the new image
				imgPreloader = new Image();
		
				// Preload the neighbour images
				nextImage = new Image();
				if(isSet && setPosition > setCount) nextImage.src = $(imagesArray[arrayPosition + 1]).attr('href');
				prevImage = new Image();
				if(isSet && imagesArray[arrayPosition - 1]) prevImage.src = $(imagesArray[arrayPosition - 1]).attr('href');

				pp_typeMarkup = '<img id="fullResImage" src="" />';				
				$pp_pic_holder.find('#pp_full_res')[0].innerHTML = pp_typeMarkup;

				$pp_pic_holder.find('.pp_content').css('overflow','hidden');
				$pp_pic_holder.find('#fullResImage').attr('src',$caller.attr('href'));

				imgPreloader.onload = function(){
					var correctSizes = _fitToViewport(imgPreloader.width,imgPreloader.height);
					imgPreloader.width = correctSizes['width'];
					imgPreloader.height = correctSizes['height'];
					showimage(imgPreloader.width,imgPreloader.height,correctSizes["containerWidth"],correctSizes["containerHeight"],correctSizes["contentHeight"],correctSizes["contentWidth"],correctSizes["resized"]);
				};
		
				imgPreloader.src = $caller.attr('href');
			}else{
				// Get the dimensions
				movie_width = ( parseFloat(grab_param('width',$caller.attr('href'))) ) ? grab_param('width',$caller.attr('href')) : "425";
				movie_height = ( parseFloat(grab_param('height',$caller.attr('href'))) ) ? grab_param('height',$caller.attr('href')) : "344";

				// If the size is % based
				if(movie_width.indexOf('%') != -1 || movie_height.indexOf('%') != -1){
					movie_height = ($(window).height() * parseFloat(movie_height) / 100) - 100;
					movie_width = ($(window).width() * parseFloat(movie_width) / 100) - 100;
					parsentBased = true;
				}else{
					movie_height = parseFloat(movie_height);
					movie_width = parseFloat(movie_width);
				}
				
				if(pp_type == 'quicktime'){ movie_height+=13; }
				
				// Fit them to viewport
				correctSizes = _fitToViewport(movie_width,movie_height);
				
				if(pp_type == 'youtube'){
					pp_typeMarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.youtube.com/v/'+grab_param('v',$caller.attr('href'))+'" /><embed src="http://www.youtube.com/v/'+grab_param('v',$caller.attr('href'))+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"></embed></object>';
				}else if(pp_type == 'quicktime'){
					pp_typeMarkup = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="'+correctSizes['height']+'" width="'+correctSizes['width']+'"><param name="src" value="'+$caller.attr('href')+'"><param name="autoplay" value="true"><param name="type" value="video/quicktime"><embed src="'+$caller.attr('href')+'" height="'+correctSizes['height']+'" width="'+correctSizes['width']+'" autoplay="true" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>';
				}else if(pp_type == 'flash'){
					flash_vars = $caller.attr('href');
					flash_vars = flash_vars.substring($caller.attr('href').indexOf('flashvars') + 10,$caller.attr('href').length);

					filename = $caller.attr('href');
					filename = filename.substring(0,filename.indexOf('?'));

					pp_typeMarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="'+filename+'?'+flash_vars+'" /><embed src="'+filename+'?'+flash_vars+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"></embed></object>';
				}else if(pp_type == 'iframe'){
					movie_url = $caller.attr('href');
					movie_url = movie_url.substr(0,movie_url.indexOf('iframe')-1);

					pp_typeMarkup = '<iframe src ="'+movie_url+'" width="'+(correctSizes['width']-10)+'" height="'+(correctSizes['height']-10)+'" frameborder="no"></iframe>';
				}
				// Append HTML
				$pp_pic_holder.find('#pp_full_res')[0].innerHTML = pp_typeMarkup;
				
				// Show content
				showimage(correctSizes['width'],correctSizes['height'],correctSizes["containerWidth"],correctSizes["containerHeight"],correctSizes["contentHeight"],correctSizes["contentWidth"],correctSizes["resized"]);
			}
		};
	
		function _getScroll(){
			if (self.pageYOffset) {
				scrollTop = self.pageYOffset;
				scrollLeft = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				scrollTop = document.documentElement.scrollTop;
				scrollLeft = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				scrollTop = document.body.scrollTop;
				scrollLeft = document.body.scrollLeft;	
			}
			
			return {scrollTop:scrollTop,scrollLeft:scrollLeft};
		};
	
		function _resizeOverlay() {
			$('div.pp_overlay').css({
				'height':$(document).height(),
				'width':$(window).width()
			});
		};
	
		function _buildOverlay(){
			toInject = "";
			
			// Build the background overlay div
			toInject += "<div class='pp_overlay'></div>";
			
			// Define the markup to append, depending on the content type.
			if(pp_type == 'image'){
				pp_typeMarkup = '<img id="fullResImage" src="" />';
			}else{
				pp_typeMarkup = '';
			}
			
			// Basic HTML for the picture holder
			toInject += '<div class="pp_pic_holder"><div class="pp_top"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div><div class="pp_content"><a href="#" class="pp_expand" title="Expand the image">Expand</a><div class="pp_loaderIcon"></div><div class="pp_hoverContainer"><a class="pp_next" href="#">next</a><a class="pp_previous" href="#">previous</a></div><div id="pp_full_res">'+ pp_typeMarkup +'</div><div class="pp_details clearfix"><a class="pp_close" href="#">Close</a><p class="pp_description"></p><div class="pp_nav"><a href="#" class="pp_arrow_previous">Previous</a><p class="currentTextHolder">0'+settings.counter_separator_label+'0</p><a href="#" class="pp_arrow_next">Next</a></div></div></div><div class="pp_bottom"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div></div>';
			
			// Basic html for the title holder
			toInject += '<div class="ppt"></div>';
			
			$('body').append(toInject);
			
			// Set my global selectors
			$pp_pic_holder = $('.pp_pic_holder');
			$ppt = $('.ppt');
			
			$('div.pp_overlay').css('height',$(document).height()).bind('click',function(){
				close();
			});

			$pp_pic_holder.css({'opacity': 0}).addClass(settings.theme);

			$('a.pp_close').bind('click',function(){ close(); return false; });

			$('a.pp_expand').bind('click',function(){				
				$this = $(this);
				
				// Expand the image
				if($this.hasClass('pp_expand')){
					$this.removeClass('pp_expand').addClass('pp_contract');
					doresize = false;
				}else{
					$this.removeClass('pp_contract').addClass('pp_expand');
					doresize = true;
				};
			
				_hideContent();
				
				$pp_pic_holder.find('.pp_hoverContainer, #pp_full_res, .pp_details').fadeOut(settings.animationSpeed,function(){
					_preload();
				});
		
				return false;	
			});
		
			$pp_pic_holder.find('.pp_previous, .pp_arrow_previous').bind('click',function(){
				changePicture('previous');
				return false;
			});
		
			$pp_pic_holder.find('.pp_next, .pp_arrow_next').bind('click',function(){
				changePicture('next');
				return false;
			});

			$pp_pic_holder.find('.pp_hoverContainer').css({
				'margin-left': settings.padding/2
			});
		
			// If it's not a set, hide the links
			if(!isSet) {
				$pp_pic_holder.find('.pp_hoverContainer,.pp_nav').hide();
			};


			// To fix the bug with IE select boxes
			if($.browser.msie && $.browser.version == 6){
				$('body').addClass('ie6');
				$('select').css('visibility','hidden');
			};

			// Then fade it in
			$('div.pp_overlay').css('opacity',0).fadeTo(settings.animationSpeed,settings.opacity, function(){
				$pp_pic_holder.css('opacity',0).fadeIn(settings.animationSpeed,function(){
					$pp_pic_holder.attr('style','left:'+$pp_pic_holder.css('left')+';top:'+$pp_pic_holder.css('top')+';');
					_preload();
				});
			});
		};
	};
	
	function grab_param(name,url){
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( url );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}
})(jQuery);jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}
var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}
expires='; expires='+date.toUTCString();}
var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}
return cookieValue;}};/*
 * jQuery validation plug-in 1.5.5
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(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;});if(validator.settings.submitHandler){this.find("input, button").filter(":submit").click(function(){validator.submitButton=this;});}this.submit(function(event){if(validator.settings.debug)event.preventDefault();function handle(){if(validator.settings.submitHandler){if(validator.submitButton){var hidden=$("<input type='hidden'/>").attr("name",validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);}validator.settings.submitHandler.call(validator,validator.currentForm);if(validator.submitButton){hidden.remove();}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=true;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(index,value){result[value]=$element.attr(value);$element.removeAttr(value);});return result;},rules:function(command,argument){var element=this[0];if(command){var settings=$.data(element.form,'validator').settings;var staticRules=settings.rules;var existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));staticRules[element.name]=existingRules;if(argument.messages)settings.messages[element.name]=$.extend(settings.messages[element.name],argument.messages);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;}});$.extend($.expr[":"],{blank:function(a){return!$.trim(a.value);},filled:function(a){return!!$.trim(a.value);},unchecked:function(a){return!a.checked;}});$.validator=function(options,form){this.settings=$.extend({},$.validator.defaults,options);this.currentForm=form;this.init();};$.validator.format=function(source,params){if(arguments.length==1)return function(){var args=$.makeArray(arguments);args.unshift(source);return $.validator.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;};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:[],ignoreTitle:false,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.settings.validClass);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,validClass){$(element).addClass(errorClass).removeClass(validClass);},unhighlight:function(element,errorClass,validClass){$(element).removeClass(errorClass).addClass(validClass);}},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 number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:$.validator.format("Please enter no more than {0} characters."),minlength:$.validator.format("Please enter at least {0} characters."),rangelength:$.validator.format("Please enter a value between {0} and {1} characters long."),range:$.validator.format("Please enter a value between {0} and {1}."),max:$.validator.format("Please enter a value less than or equal to {0}."),min:$.validator.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);if(this.settings.invalidHandler)$(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler);},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid())$(this.currentForm).triggerHandler("invalid-form",[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=this.toHide.add(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().add(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,element.value.replace(/\r/g,""),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&&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),!this.settings.ignoreTitle&&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=toToggle.add(toToggle.parent(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.settings.validClass);this.showLabel(error.element,error.message);}if(this.errorList.length){this.toShow=this.toShow.add(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.settings.validClass);}}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=this.toShow.add(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();}else if(!valid&&this.pendingRequest==0&&this.formSubmitted){$(this.currentForm).triggerHandler("invalid-form",[this]);}},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}},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||$.validator.messages[name];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 $.trim(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;param=typeof param=="string"&&{url:param}||param;if(previous.old!==value){previous.old=value;var validator=this;this.startRequest(element);var data={};data[element.name]=value;$.ajax($.extend(true,{url:param,mode:"abort",port:"validate"+element.name,dataType:"json",data:data,success:function(response){var valid=response===true;if(valid){var submitted=validator.formSubmitted;validator.prepareElement(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.showErrors();}else{var errors={};errors[element.name]=previous.message=response||validator.defaultMessage(element,"remote");validator.showErrors(errors);}previous.valid=valid;validator.stopRequest(element,valid);}},param));return"pending";}else if(this.pending[element.name]){return"pending";}return previous.valid;},minlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)>=param;},maxlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)<=param;},rangelength:function(value,element,param){var length=this.getLength($.trim(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(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(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.replace(/,/g,'|'):"png|jpe?g|gif";return this.optional(element)||value.match(new RegExp(".("+param+")$","i"));},equalTo:function(value,element,param){return value==$(param).val();}}});$.format=$.validator.format;})(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);/* 
 * flowplayer.js 3.1.1. The Flowplayer API
 * 
 * Copyright 2009 Flowplayer Oy
 * 
 * This file is part of Flowplayer.
 * 
 * Flowplayer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Flowplayer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Flowplayer.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Date: 2009-02-25 16:24:29 -0500 (Wed, 25 Feb 2009)
 * Revision: 166 
 */
(function(){function g(o){console.log("$f.fireEvent",[].slice.call(o))}function k(q){if(!q||typeof q!="object"){return q}var o=new q.constructor();for(var p in q){if(q.hasOwnProperty(p)){o[p]=k(q[p])}}return o}function m(t,q){if(!t){return}var o,p=0,r=t.length;if(r===undefined){for(o in t){if(q.call(t[o],o,t[o])===false){break}}}else{for(var s=t[0];p<r&&q.call(s,p,s)!==false;s=t[++p]){}}return t}function c(o){return document.getElementById(o)}function i(q,p,o){if(typeof p!="object"){return q}if(q&&p){m(p,function(r,s){if(!o||typeof s!="function"){q[r]=s}})}return q}function n(s){var q=s.indexOf(".");if(q!=-1){var p=s.substring(0,q)||"*";var o=s.substring(q+1,s.length);var r=[];m(document.getElementsByTagName(p),function(){if(this.className&&this.className.indexOf(o)!=-1){r.push(this)}});return r}}function f(o){o=o||window.event;if(o.preventDefault){o.stopPropagation();o.preventDefault()}else{o.returnValue=false;o.cancelBubble=true}return false}function j(q,o,p){q[o]=q[o]||[];q[o].push(p)}function e(){return"_"+(""+Math.random()).substring(2,10)}var h=function(t,r,s){var q=this;var p={};var u={};q.index=r;if(typeof t=="string"){t={url:t}}i(this,t,true);m(("Begin*,Start,Pause*,Resume*,Seek*,Stop*,Finish*,LastSecond,Update,BufferFull,BufferEmpty,BufferStop").split(","),function(){var v="on"+this;if(v.indexOf("*")!=-1){v=v.substring(0,v.length-1);var w="onBefore"+v.substring(2);q[w]=function(x){j(u,w,x);return q}}q[v]=function(x){j(u,v,x);return q};if(r==-1){if(q[w]){s[w]=q[w]}if(q[v]){s[v]=q[v]}}});i(this,{onCuepoint:function(x,w){if(arguments.length==1){p.embedded=[null,x];return q}if(typeof x=="number"){x=[x]}var v=e();p[v]=[x,w];if(s.isLoaded()){s._api().fp_addCuepoints(x,r,v)}return q},update:function(w){i(q,w);if(s.isLoaded()){s._api().fp_updateClip(w,r)}var v=s.getConfig();var x=(r==-1)?v.clip:v.playlist[r];i(x,w,true)},_fireEvent:function(v,y,w,A){if(v=="onLoad"){m(p,function(B,C){if(C[0]){s._api().fp_addCuepoints(C[0],r,B)}});return false}A=A||q;if(v=="onCuepoint"){var z=p[y];if(z){return z[1].call(s,A,w)}}if(v=="onStart"||v=="onUpdate"||v=="onResume"){i(A,y);if(!A.duration){A.duration=y.metaData.duration}else{A.fullDuration=y.metaData.duration}}var x=true;m(u[v],function(){x=this.call(s,A,y,w)});return x}});if(t.onCuepoint){var o=t.onCuepoint;q.onCuepoint.apply(q,typeof o=="function"?[o]:o);delete t.onCuepoint}m(t,function(v,w){if(typeof w=="function"){j(u,v,w);delete t[v]}});if(r==-1){s.onCuepoint=this.onCuepoint}};var l=function(p,r,q,t){var s={};var o=this;var u=false;if(t){i(s,t)}m(r,function(v,w){if(typeof w=="function"){s[v]=w;delete r[v]}});i(this,{animate:function(y,z,x){if(!y){return o}if(typeof z=="function"){x=z;z=500}if(typeof y=="string"){var w=y;y={};y[w]=z;z=500}if(x){var v=e();s[v]=x}if(z===undefined){z=500}r=q._api().fp_animate(p,y,z,v);return o},css:function(w,x){if(x!==undefined){var v={};v[w]=x;w=v}r=q._api().fp_css(p,w);i(o,r);return o},show:function(){this.display="block";q._api().fp_showPlugin(p);return o},hide:function(){this.display="none";q._api().fp_hidePlugin(p);return o},toggle:function(){this.display=q._api().fp_togglePlugin(p);return o},fadeTo:function(y,x,w){if(typeof x=="function"){w=x;x=500}if(w){var v=e();s[v]=w}this.display=q._api().fp_fadeTo(p,y,x,v);this.opacity=y;return o},fadeIn:function(w,v){return o.fadeTo(1,w,v)},fadeOut:function(w,v){return o.fadeTo(0,w,v)},getName:function(){return p},getPlayer:function(){return q},_fireEvent:function(w,v,x){if(w=="onUpdate"){var y=q._api().fp_getPlugin(p);if(!y){return}i(o,y);delete o.methods;if(!u){m(y.methods,function(){var A=""+this;o[A]=function(){var B=[].slice.call(arguments);var C=q._api().fp_invoke(p,A,B);return C=="undefined"?o:C}});u=true}}var z=s[w];if(z){z.apply(o,v);if(w.substring(0,1)=="_"){delete s[w]}}}})};function b(o,t,z){var E=this,y=null,x,u,p=[],s={},B={},r,v,w,D,A,q;i(E,{id:function(){return r},isLoaded:function(){return(y!==null)},getParent:function(){return o},hide:function(F){if(F){o.style.height="0px"}if(y){y.style.height="0px"}return E},show:function(){o.style.height=q+"px";if(y){y.style.height=A+"px"}return E},isHidden:function(){return y&&parseInt(y.style.height,10)===0},load:function(F){if(!y&&E._fireEvent("onBeforeLoad")!==false){m(a,function(){this.unload()});x=o.innerHTML;if(x&&!flashembed.isSupported(t.version)){o.innerHTML=""}flashembed(o,t,{config:z});if(F){F.cached=true;j(B,"onLoad",F)}}return E},unload:function(){try{if(!y||y.fp_isFullscreen()){return E}}catch(F){return E}if(x.replace(/\s/g,"")!==""){if(E._fireEvent("onBeforeUnload")===false){return E}y.fp_close();y=null;o.innerHTML=x;E._fireEvent("onUnload")}return E},getClip:function(F){if(F===undefined){F=D}return p[F]},getCommonClip:function(){return u},getPlaylist:function(){return p},getPlugin:function(F){var H=s[F];if(!H&&E.isLoaded()){var G=E._api().fp_getPlugin(F);if(G){H=new l(F,G,E);s[F]=H}}return H},getScreen:function(){return E.getPlugin("screen")},getControls:function(){return E.getPlugin("controls")},getConfig:function(F){return F?k(z):z},getFlashParams:function(){return t},loadPlugin:function(I,H,K,J){if(typeof K=="function"){J=K;K={}}var G=J?e():"_";E._api().fp_loadPlugin(I,H,K,G);var F={};F[G]=J;var L=new l(I,null,E,F);s[I]=L;return L},getState:function(){return y?y.fp_getState():-1},play:function(G,F){function H(){if(G!==undefined){E._api().fp_play(G,F)}else{E._api().fp_play()}}if(y){H()}else{E.load(function(){H()})}return E},getVersion:function(){var G="flowplayer.js 3.1.1";if(y){var F=y.fp_getVersion();F.push(G);return F}return G},_api:function(){if(!y){throw"Flowplayer "+E.id()+" not loaded when calling an API method"}return y},setClip:function(F){E.setPlaylist([F]);return E},getIndex:function(){return w}});m(("Click*,Load*,Unload*,Keypress*,Volume*,Mute*,Unmute*,PlaylistReplace,ClipAdd,Fullscreen*,FullscreenExit,Error").split(","),function(){var F="on"+this;if(F.indexOf("*")!=-1){F=F.substring(0,F.length-1);var G="onBefore"+F.substring(2);E[G]=function(H){j(B,G,H);return E}}E[F]=function(H){j(B,F,H);return E}});m(("pause,resume,mute,unmute,stop,toggle,seek,getStatus,getVolume,setVolume,getTime,isPaused,isPlaying,startBuffering,stopBuffering,isFullscreen,toggleFullscreen,reset,close,setPlaylist,addClip").split(","),function(){var F=this;E[F]=function(H,G){if(!y){return E}var I=null;if(H!==undefined&&G!==undefined){I=y["fp_"+F](H,G)}else{I=(H===undefined)?y["fp_"+F]():y["fp_"+F](H)}return I=="undefined"?E:I}});E._fireEvent=function(O){if(typeof O=="string"){O=[O]}var P=O[0],M=O[1],K=O[2],J=O[3],I=0;if(z.debug){g(O)}if(!y&&P=="onLoad"&&M=="player"){y=y||c(v);A=y.clientHeight;m(p,function(){this._fireEvent("onLoad")});m(s,function(Q,R){R._fireEvent("onUpdate")});u._fireEvent("onLoad")}if(P=="onLoad"&&M!="player"){return}if(P=="onError"){if(typeof M=="string"||(typeof M=="number"&&typeof K=="number")){M=K;K=J}}if(P=="onContextMenu"){m(z.contextMenu[M],function(Q,R){R.call(E)});return}if(P=="onPluginEvent"){var F=M.name||M;var G=s[F];if(G){G._fireEvent("onUpdate",M);G._fireEvent(K,O.slice(3))}return}if(P=="onPlaylistReplace"){p=[];var L=0;m(M,function(){p.push(new h(this,L++,E))})}if(P=="onClipAdd"){if(M.isInStream){return}M=new h(M,K,E);p.splice(K,0,M);for(I=K+1;I<p.length;I++){p[I].index++}}var N=true;if(typeof M=="number"&&M<p.length){D=M;var H=p[M];if(H){N=H._fireEvent(P,K,J)}if(!H||N!==false){N=u._fireEvent(P,K,J,H)}}m(B[P],function(){N=this.call(E,M,K);if(this.cached){B[P].splice(I,1)}if(N===false){return false}I++});return N};function C(){if($f(o)){$f(o).getParent().innerHTML="";w=$f(o).getIndex();a[w]=E}else{a.push(E);w=a.length-1}q=parseInt(o.style.height,10)||o.clientHeight;if(typeof t=="string"){t={src:t}}r=o.id||"fp"+e();v=t.id||r+"_api";t.id=v;z.playerId=r;if(typeof z=="string"){z={clip:{url:z}}}if(typeof z.clip=="string"){z.clip={url:z.clip}}z.clip=z.clip||{};if(o.getAttribute("href",2)&&!z.clip.url){z.clip.url=o.getAttribute("href",2)}u=new h(z.clip,-1,E);z.playlist=z.playlist||[z.clip];var F=0;m(z.playlist,function(){var H=this;if(typeof H=="object"&&H.length){H={url:""+H}}m(z.clip,function(I,J){if(J!==undefined&&H[I]===undefined&&typeof J!="function"){H[I]=J}});z.playlist[F]=H;H=new h(H,F,E);p.push(H);F++});m(z,function(H,I){if(typeof I=="function"){j(B,H,I);delete z[H]}});m(z.plugins,function(H,I){if(I){s[H]=new l(H,I,E)}});if(!z.plugins||z.plugins.controls===undefined){s.controls=new l("controls",null,E)}s.canvas=new l("canvas",null,E);t.bgcolor=t.bgcolor||"#000000";t.version=t.version||[9,0];t.expressInstall="http://www.flowplayer.org/swf/expressinstall.swf";function G(H){if(!E.isLoaded()&&E._fireEvent("onBeforeClick")!==false){E.load()}return f(H)}x=o.innerHTML;if(x.replace(/\s/g,"")!==""){if(o.addEventListener){o.addEventListener("click",G,false)}else{if(o.attachEvent){o.attachEvent("onclick",G)}}}else{if(o.addEventListener){o.addEventListener("click",f,false)}E.load()}}if(typeof o=="string"){flashembed.domReady(function(){var F=c(o);if(!F){throw"Flowplayer cannot access element: "+o}else{o=F;C()}})}else{C()}}var a=[];function d(o){this.length=o.length;this.each=function(p){m(o,p)};this.size=function(){return o.length}}window.flowplayer=window.$f=function(){var p=null;var o=arguments[0];if(!arguments.length){m(a,function(){if(this.isLoaded()){p=this;return false}});return p||a[0]}if(arguments.length==1){if(typeof o=="number"){return a[o]}else{if(o=="*"){return new d(a)}m(a,function(){if(this.id()==o.id||this.id()==o||this.getParent()==o){p=this;return false}});return p}}if(arguments.length>1){var r=arguments[1];var q=(arguments.length==3)?arguments[2]:{};if(typeof o=="string"){if(o.indexOf(".")!=-1){var t=[];m(n(o),function(){t.push(new b(this,k(r),k(q)))});return new d(t)}else{var s=c(o);return new b(s!==null?s:o,r,q)}}else{if(o){return new b(o,r,q)}}}return null};i(window.$f,{fireEvent:function(){var o=[].slice.call(arguments);var q=$f(o[0]);return q?q._fireEvent(o.slice(1)):null},addPlugin:function(o,p){b.prototype[o]=p;return $f},each:m,extend:i});if(typeof jQuery=="function"){jQuery.prototype.flowplayer=function(q,p){if(!arguments.length||typeof arguments[0]=="number"){var o=[];this.each(function(){var r=$f(this);if(r){o.push(r)}});return arguments.length?o[arguments[0]]:new d(o)}return this.each(function(){$f(this,k(q),p?k(p):{})})}}})();(function(){var e=typeof jQuery=="function";function i(){if(c.done){return false}var k=document;if(k&&k.getElementsByTagName&&k.getElementById&&k.body){clearInterval(c.timer);c.timer=null;for(var j=0;j<c.ready.length;j++){c.ready[j].call()}c.ready=null;c.done=true}}var c=e?jQuery:function(j){if(c.done){return j()}if(c.timer){c.ready.push(j)}else{c.ready=[j];c.timer=setInterval(i,13)}};function f(k,j){if(j){for(key in j){if(j.hasOwnProperty(key)){k[key]=j[key]}}}return k}function g(j){switch(h(j)){case"string":j=j.replace(new RegExp('(["\\\\])',"g"),"\\$1");j=j.replace(/^\s?(\d+)%/,"$1pct");return'"'+j+'"';case"array":return"["+b(j,function(m){return g(m)}).join(",")+"]";case"function":return'"function()"';case"object":var k=[];for(var l in j){if(j.hasOwnProperty(l)){k.push('"'+l+'":'+g(j[l]))}}return"{"+k.join(",")+"}"}return String(j).replace(/\s/g," ").replace(/\'/g,'"')}function h(k){if(k===null||k===undefined){return false}var j=typeof k;return(j=="object"&&k.push)?"array":j}if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}})}function b(j,m){var l=[];for(var k in j){if(j.hasOwnProperty(k)){l[k]=m(j[k])}}return l}function a(q,s){var o=f({},q);var r=document.all;var m='<object width="'+o.width+'" height="'+o.height+'"';if(r&&!o.id){o.id="_"+(""+Math.random()).substring(9)}if(o.id){m+=' id="'+o.id+'"'}o.src+=((o.src.indexOf("?")!=-1?"&":"?")+Math.random());if(o.w3c||!r){m+=' data="'+o.src+'" type="application/x-shockwave-flash"'}else{m+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'}m+=">";if(o.w3c||r){m+='<param name="movie" value="'+o.src+'" />'}o.width=o.height=o.id=o.w3c=o.src=null;for(var j in o){if(o[j]!==null){m+='<param name="'+j+'" value="'+o[j]+'" />'}}var n="";if(s){for(var l in s){if(s[l]!==null){n+=l+"="+(typeof s[l]=="object"?g(s[l]):s[l])+"&"}}n=n.substring(0,n.length-1);m+='<param name="flashvars" value=\''+n+"' />"}m+="</object>";return m}function d(l,o,k){var j=flashembed.getVersion();f(this,{getContainer:function(){return l},getConf:function(){return o},getVersion:function(){return j},getFlashvars:function(){return k},getApi:function(){return l.firstChild},getHTML:function(){return a(o,k)}});var p=o.version;var q=o.expressInstall;var n=!p||flashembed.isSupported(p);if(n){o.onFail=o.version=o.expressInstall=null;l.innerHTML=a(o,k)}else{if(p&&q&&flashembed.isSupported([6,65])){f(o,{src:q});k={MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title};l.innerHTML=a(o,k)}else{if(l.innerHTML.replace(/\s/g,"")!==""){}else{l.innerHTML="<h2>Flash version "+p+" or greater is required</h2><h3>"+(j[0]>0?"Your version is "+j:"You have no flash plugin installed")+"</h3>"+(l.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='http://www.adobe.com/go/getflashplayer'>here</a></p>");if(l.tagName=="A"){l.onclick=function(){location.href="http://www.adobe.com/go/getflashplayer"}}}}}if(!n&&o.onFail){var m=o.onFail.call(this);if(typeof m=="string"){l.innerHTML=m}}if(document.all){window[o.id]=document.getElementById(o.id)}}window.flashembed=function(k,l,j){if(typeof k=="string"){var m=document.getElementById(k);if(m){k=m}else{c(function(){flashembed(k,l,j)});return}}if(!k){return}var n={width:"100%",height:"100%",allowfullscreen:true,allowscriptaccess:"always",quality:"high",version:null,onFail:null,expressInstall:null,w3c:false};if(typeof l=="string"){l={src:l}}f(n,l);return new d(k,n,j)};f(window.flashembed,{getVersion:function(){var l=[0,0];if(navigator.plugins&&typeof navigator.plugins["Shockwave Flash"]=="object"){var k=navigator.plugins["Shockwave Flash"].description;if(typeof k!="undefined"){k=k.replace(/^.*\s+(\S+\s+\S+$)/,"$1");var m=parseInt(k.replace(/^(.*)\..*$/,"$1"),10);var q=/r/.test(k)?parseInt(k.replace(/^.*r(.*)$/,"$1"),10):0;l=[m,q]}}else{if(window.ActiveXObject){try{var o=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")}catch(p){try{o=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");l=[6,0];o.AllowScriptAccess="always"}catch(j){if(l[0]==6){return}}try{o=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(n){}}if(typeof o=="object"){k=o.GetVariable("$version");if(typeof k!="undefined"){k=k.replace(/^\S+\s+(.*)$/,"$1").split(",");l=[parseInt(k[0],10),parseInt(k[2],10)]}}}}return l},isSupported:function(j){var l=flashembed.getVersion();var k=(l[0]>j[0])||(l[0]==j[0]&&l[1]>=j[1]);return k},domReady:c,asString:g,getHTML:a});if(e){jQuery.tools=jQuery.tools||{version:{}};jQuery.tools.version.flashembed="1.0.2";jQuery.fn.flashembed=function(k,j){var l=null;this.each(function(){l=flashembed(this,k,j)});return k.api===false?this:l}}})();/* ===========================================================================
 *
 * JQuery URL Parser
 * Version 1.0
 * Parses URLs and provides easy access to information within them.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 *
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_url_parser/
 *
 * ---------------------------------------------------------------------------
 *
 * CREDITS:
 *
 * Parser based on the Regex-based URI parser by Steven Levithan.
 * For more information (including a detailed explaination of the differences
 * between the 'loose' and 'strict' pasing modes) visit http://blog.stevenlevithan.com/archives/parseuri
 *
 * ---------------------------------------------------------------------------
 *
 * LICENCE:
 *
 * Released under a MIT Licence. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_url_parser/licence.txt
 *
 * ---------------------------------------------------------------------------
 * 
 * EXAMPLES OF USE:
 *
 * Get the domain name (host) from the current page URL
 * jQuery.url.attr("host")
 *
 * Get the query string value for 'item' for the current page
 * jQuery.url.param("item") // null if it doesn't exist
 *
 * Get the second segment of the URI of the current page
 * jQuery.url.segment(2) // null if it doesn't exist
 *
 * Get the protocol of a manually passed in URL
 * jQuery.url.setUrl("http://allmarkedup.com/").attr("protocol") // returns 'http'
 *
 */

jQuery.url = function()
{
	var segments = {};
	
	var parsed = {};
	
	/**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
  	var options = {
	
		url : window.location, // default URI is the page in which the script is running
		
		strictMode: false, // 'loose' parsing by default
	
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query 
		
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
		}
		
	};
	
    /**
     * Deals with the parsing of the URI according to the regex above.
 	 * Written by Steven Levithan - see credits at top.
     */		
	var parseUri = function()
	{
		str = decodeURI( options.url );
		
		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
		var uri = {};
		var i = 14;

		while ( i-- ) {
			uri[ options.key[i] ] = m[i] || "";
		}

		uri[ options.q.name ] = {};
		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
			if ($1) {
				uri[options.q.name][$1] = $2;
			}
		});

		return uri;
	};

    /**
     * Returns the value of the passed in key from the parsed URI.
  	 * 
	 * @param string key The key whose value is required
     */		
	var key = function( key )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		} 
		if ( key == "base" )
		{
			if ( parsed.port !== null && parsed.port !== "" )
			{
				return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";	
			}
			else
			{
				return parsed.protocol+"://"+parsed.host+"/";
			}
		}
	
		return ( parsed[key] === "" ) ? null : parsed[key];
	};
	
	/**
     * Returns the value of the required query string parameter.
  	 * 
	 * @param string item The parameter whose value is required
     */		
	var param = function( item )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		}
		return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
	};

    /**
     * 'Constructor' (not really!) function.
     *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
     */	
	var setUp = function()
	{
		parsed = parseUri();
		
		getSegments();	
	};
	
    /**
     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
     */
	var getSegments = function()
	{
		var p = parsed.path;
		segments = []; // clear out segments array
		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
	};
	
	return {
		
	    /**
	     * Sets the parsing mode - either strict or loose. Set to loose by default.
	     *
	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
	     */
		setMode : function( mode )
		{
			strictMode = mode == "strict" ? true : false;
			return this;
		},
		
		/**
	     * Sets URI to parse if you don't want to to parse the current page's URI.
		 * Calling the function with no value for newUri resets it to the current page's URI.
	     *
	     * @param string newUri The URI to parse.
	     */		
		setUrl : function( newUri )
		{
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},		
		
		/**
	     * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
		 *
		 * If no integer is passed into the function it returns the number of segments in the URI.
	     *
	     * @param int pos The position of the segment to return. Can be empty.
	     */	
		segment : function( pos )
		{
			if ( ! parsed.length )
			{
				setUp(); // if the URI has not been parsed yet then do this first...	
			} 
			if ( pos === undefined )
			{
				return segments.length;
			}
			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
		},
		
		attr : key, // provides public access to private 'key' function - see above
		
		param : param // provides public access to private 'param' function - see above
		
	};
	
}();log=(function(){return(window.console&&console.firebug)?console.log:function(){};})();jQuery(function($){$('body').removeClass('js-disabled').addClass('js-enabled');$('.with-js').show();$('.without-js').hide();$('a.not-a-link-without-js').attr('href','/');});﻿// namespace
var p = p || {};

var mark;
var t = function() {
	mark = new Date();
};
var te =  function() {
	alert(new Date().getTime() - mark.getTime() );
};

mcms_lp = (mcms_lang == 'ru') ? '' : mcms_lang + '/';

// on DOM ready
$(function() {
	
	$.datepicker.regional['en'] = $.datepicker.regional[''];
	$.datepicker.setDefaults($.datepicker.regional[mcms_lang]);
	
	flowplayer("a.gallery-video-player", "./sites/default/themes/lenexpo/media/flowplayer-3.1.1.swf");
	
	$.validator.messages.required = "Это поле нужно заполнить";
	$.validator.messages.email = "Некорректный формат электронной почты";
	
	$('.light-section form span.t:has(em)').siblings('input, select, textarea').addClass('required');
	
	$('.light-section form:has(em)').validate();
	
	
	
	$('a[rel="external"]').attr('target', '_blank');
	
	$('#header-secondary ul.associations li a').attr('target', '_blank');
	
	$('a:has(img.illustration-left), a:has(img.illustration-right)').prettyPhoto({
		showTitle: false
	});
	
	/*
	$(document).click(function(e) {
		$('body').prepend($(e.target).height());
		return false;
	});
	*/
	
	$("a[rel^='prettyPhoto']").prettyPhoto({
		showTitle: false
	});
	
	$('.light-section .column-secondary p.call-calendar a').click(function(e) {
		var that = this;
		$.get('./' + mcms_lp + 'api/lenexpo/eventsdata.xml&random=' + new Date().getTime(), function(response) {
			var events = {};
			$(response).find('event').each(function() {
				events[$(this).attr('id')] = new Date($(this).attr('date').replace(/-/g, '/') ).setHours(0,0,0);
			});
			$('#events-calendar').datepicker('dialog', new Date(), function(date) {
				var dateObj = new Date(date);
				var nextDateObj = new Date(new Date(date).setDate(dateObj.getDate() + 1) );
				var day = dateObj.getDate(), month = dateObj.getMonth() + 1, nextDay = nextDateObj.getDate(), nextMonth = nextDateObj.getMonth() + 1;
				if (day < 10) {
					day = '0' + day;
				}
				if (nextDay < 10) {
					nextDay = '0' + nextDay;
				}
				if (month < 10) {
					month = '0' + month;
				}
				if (nextMonth < 10) {
					nextMonth = '0' + nextMonth;
				}
				$.each(events, function(key) {
					if (this == dateObj.getTime() ) {
						location.href = './' + mcms_lp + 'node/42?date=' + dateObj.getFullYear() + '-' + month + '-' + day;
						return false;
					}
				});
			}, {
				dateFormat: 'yy/mm/dd',
				firstDay: 1,
				beforeShowDay: function(date) {
					var match = false;
					$.each(events, function() {
						if (this == date.getTime() ) {
							match = true;
							return false;
						}
					});
					if (match) {
						return [true, 'available'];
					} else {
						return [false, ''];
					}
				}
			}, [$(that).offset().left, $(that).offset().top]);
		}, 'xml');
		return false;
	});
	
	
	$('.illustration-left, .illustration-right').each(function() {
		if ($(this).attr('alt') !== '') {
			$(this).parent().wrap('<span class="' + $(this).attr('class') + '" style="width:' + $(this).width() +  'px;" />').after('<span>' + $(this).attr('alt') + '</span>').end().removeAttr('class');
		}
	});
	
	// правка "click to activate"
	$('object').each(function() {
		this.outerHTML = this.outerHTML;
	});
    
	// категории в разбивке списка котировок по тематике
	$('#events ul.events-categories li').removeClass('active');
	$('#events ul.events-categories h4 a').live('click', function() {
		$('#events ul.events-categories li').removeClass('active');
		$(this).parents('li:eq(0)').toggleClass('active');
		return false;
	});
	
	// форма поиска
	$('#header-secondary ul.utilitary a.search').click(function() {
		$(this).toggleClass('active');
		$('#header-primary .pup-form.auth').hide();
		$('#header-secondary ul.utilitary a.auth').removeClass('active');
		$('#header-primary .pup-form.search').toggle();
		return false;
	});
	
	// форма авторизации
	$('#header-secondary ul.utilitary a.auth').click(function() {
		$(this).toggleClass('active');
		$('#header-primary .pup-form.search').hide();
		$('#header-secondary ul.utilitary a.search').removeClass('active');
		$('#header-primary .pup-form.auth').toggle();
		return false;
	});
	
	// форма подписки
	$('.light-section p.additional.news a').click(function() {
		$(this).toggleClass('active').parent().siblings('.subscribe.pup-form').toggle();
		return false;
	});
	
	var initialData = $('.light-section .subscribe.pup-form input.text').val();
	if (initialData && initialData.indexOf('@') == -1) {
		$('.light-section .subscribe.pup-form input.text').focus(function() {
			if ($(this).val() == initialData ) {
				$(this).val('');
			}
		}).blur(function() {
			if ($(this).val() === '') {
				$(this).val(initialData);
			}
		});
	}
	
	var subheaderBannerHeight = $('#bn-subheader object, #bn-subheader img').attr('height');
	var topmostBannerHeight = $('#bn-topmost object, #bn-topmost img').attr('height');
	
	// баннер под шапкой
	/*
	setTimeout(function() {
		$('#bn-subheader, #bn-topmost').stop().animate({
			height: 20
		}, 350);
	}, 1500);
	*/
	
	var t1, t2;
	$('#bn-topmost').hover(function() {
		var that = this;
		t1 = setTimeout(function() {
			$(that).stop().animate({
				height: topmostBannerHeight
			}, 350);
		}, 500);
	}, function() {
		clearTimeout(t1);
		$(this).stop().animate({
			height: 20
		}, 350);
	});
	
	$('#bn-subheader').hover(function() {
		var that = this;
		t2 = setTimeout(function() {
			$(that).stop().animate({
				height: subheaderBannerHeight
			}, 350);
		}, 500);
	}, function() {
		clearTimeout(t2);
		$(this).stop().animate({
			height: 20
		}, 350);
	});
	
});$(function() {
	$('ul.gallery-video li a.gallery-video-player img, #complex h2.viewmode-control img, #complex .history a.expand img, #complex .history, #complex .misc ul.coordinates img, #complex h2.viewmode-control img, #complex .section-header img.viewmode-control, #complex .map .column-secondary, #complex .map .column-primary').ifixpng();
});

if ($.browser.msie && $.browser.version == 6 && location.href.indexOf('bare') == -1) {
	var p = p || {};
	
	p.ieWidthFixer = function() {
		var affectedElements = $('#wrapper');
		var bodyWidth = $('body').width();
		
		if (bodyWidth > 990 && bodyWidth < 1280) {
			affectedElements.css('width', 'auto');
		} else if (bodyWidth > 1280) {
			affectedElements.css('width', '1280px');
		} else {
			affectedElements.css('width', '990px');
		}
	};
	
	/*
	 * @todo сделать обработку большинства эл-ов через css
	 */
	
	$(function() {
		$('body.content #events .column-primary table.event-navigation td').hover(function() {
			$(this).addClass('hovered');
		}, function() {
			$(this).removeClass('hovered');
		});
		p.ieWidthFixer();
	});
	
	$(window).resize(function () {
		p.ieWidthFixer();
	});
};﻿// on DOM ready
$(function() {
	
	p.flashmap = $('#complex-flash-map');
	
	if (p.flashmap.length) {
		$('html, body').animate({
			scrollTop: p.flashmap.offset().top
		}, 750);
	}
	
	
	$('#events .column-primary form.event-search p.extended a').click(function() {
		$('body.content #events .column-primary form.event-search div.extended').toggle();
		$(this).toggleClass('active');
		return false;
	});
	
	/*
	 * Форма поиска выставок
	 * Тематики не обрабатываются в массиве, приходится склеивать в строку
	 */
	p.eventsSearchForm = $('form.event-search');
	if (p.eventsSearchForm.length) {
		var tagged = $.url.param('tagged'), inputs;
		if (tagged) {
			inputs = p.eventsSearchForm.find('input[name *= "tagged"]');
			if (tagged.indexOf('%2C') != -1) {
				tagged = tagged.split('%2C');
			} else {
				tagged = tagged.split(',');
			}
			$.each(tagged, function(k, v) {
				inputs.filter('[value = ' + v + ']').attr('checked', 'checked');
			});
			$('#events .column-primary form.event-search p.extended a').click();
		}
		p.eventsSearchForm.find('input.submit').click(function() {
			var tags = [];
			inputs = p.eventsSearchForm.find('input[name *= "tagged"]:checked');
			if (inputs.length) {
				inputs.each(function(){
					tags.push($(this).val() );
				});
				inputs.removeAttr('name');
				p.eventsSearchForm.append('<input type="hidden" name="tagged" value="' + tags.join(',') + '" />');
			}
		});
	}
	
	
	
	$('ul.gallery-video li h3').wrapInner('<a href="#" class="samepage"></a>').not(':eq(0)').parent().addClass('collapsed');
	$('ul.gallery-video li h3 a').click(function() {
		$(this).parent().parent().toggleClass('collapsed');
		return false;
	});
	
	$('input[name="qty"], td.amount input').keypress(function(e) {
		e.keyCode = e.keyCode || e.which;
		if ( (e.keyCode < 37 || e.keyCode > 40) && (e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 8 && e.keyCode != 13 && e.keyCode != 46) {
			return false;
		}
	});
	
	/*
	$('select[name="orderdesignation"]').change(function() {
		if ($(this).find('option:selected').text() == 'Выставка') {
			$('label.events').show();
		} else {
			$('label.events').hide();
		}
	});
	*/
	
	$('label:has(select[name = "event"])').hide();
	
	$('select[name="orderdesignation"]').change(function() {
		if ($(this).find('option:selected').text() == 'Выставка') {
			$('label:has(select[name = "event"])').show();
		} else {
			$('label:has(select[name = "event"])').hide();
		}
	});
	
	$('#complex .column-primary .imagebox ul.gallery-photos li:gt(0)').hide();
	$('#complex .column-primary .imagebox ul.gallery-pager li a').click(function() {
		var idx = $('#complex .column-primary .imagebox ul.gallery-pager li a').index(this);
		$('#complex .column-primary .imagebox ul.gallery-photos li').hide();
		$('#complex .column-primary .imagebox ul.gallery-photos li:eq(' + idx + ')').show();
		$(this).parent().addClass('current').siblings().removeClass('current');
		return false;
	});
	
	
	$('form.event-search input.date').datepicker({
		dateFormat: 'yy-mm-dd'
	});
	
	if ($('form.event-search input.date.start').val() ) {
		var val = $('form.event-search input.date.start').val();
		var date = new Date(val.substr(0, 4), parseInt(val.substr(5, 2), 10) - 1, val.substr(8, 2) );
		$('form.event-search input.date.end').datepicker('option', 'minDate', date);
	}
	if ($('form.event-search input.date.end').val() ) {
		var val = $('form.event-search input.date.end').val();
		var date = new Date(val.substr(0, 4), parseInt(val.substr(5, 2), 10) - 1, val.substr(8, 2) );
		$('form.event-search input.date.start').datepicker('option', 'maxDate', date);
	}
	
	
	
	$('form.event-search input.date').change(function() {
		var val = $(this).val();
		var date = new Date(val.substr(0, 4), parseInt(val.substr(5, 2), 10) - 1, val.substr(8, 2) );
		if ($(this).is('.start') ) {
			$('form.event-search input.date.end').datepicker('option', 'minDate', date);
		} else {
			$('form.event-search input.date.start').datepicker('option', 'maxDate', date);
		}
	});
	
	$('.cart-actions.finalize input[type=checkbox]').removeAttr('checked').click(function() {
		if ($(this).is(':checked') ) {
			$('.cart-actions.finalize input.submit').removeAttr('disabled');
		} else {
			$('.cart-actions.finalize input.submit').attr('disabled', 'disabled');
		}
	});
	$('.cart-actions.finalize input.submit').attr('disabled', 'disabled');
	
	$('#events .column-primary p.viewmode-selector a').click(function() {
		if ($(this).is('.mode-list') ) {
			$('#events .column-primary .cart-viewmode-table').hide();
			$('#events .column-primary .cart-viewmode-list').show();
			$.cookie('cart-viewmode', 'list', {expires: 365, path: '/'});
		} else {
			$('#events .column-primary .cart-viewmode-list').hide();
			$('#events .column-primary .cart-viewmode-table').show();
			$.cookie('cart-viewmode', 'table', {expires: 365, path: '/'});
		}
		$(this).addClass('active').siblings('a').removeClass('active');
		return false;
	});
	
	if ($.fn.tabber) {
		$('#complex .columns-container .tabs').tabber({
			active: 0,
			selectors: {
				tabContainer: '>div.tab',
				tabTitle: '>h3'
			}
		});
	}
	
	if (typeof swfobject != 'undefined' && $('#complex-flash-map').length) {
		var flashvars = {
			xml_link: encodeURIComponent('./' + mcms_lang + '/api/lenexpo/mapdata.xml?random=' + new Date().getTime() ),
			style_link: './sites/default/themes/lenexpo/styles/msc/map.css'
		};
		var params = {
			//bgcolor: '#000000'
		};
		var attributes = {};
		swfobject.embedSWF("./sites/default/themes/lenexpo/media/lenexpo-" + mcms_lang + ".swf", "complex-flash-map", "100%", "650", "8.0.0", "./sites/default/themes/lenexpo/media/expressInstall.swf", flashvars, params, attributes);
	}
	
});
;var p = p || {};

if (location.pathname == '/') {
	$.preload(['sites/default/themes/lenexpo/images/misc/events-expanded-' + mcms_lang + '.png', 'sites/default/themes/lenexpo/images/misc/complex-expanded-' + mcms_lang + '.png']);
}

p.showNearestEvents = function(startDate) {
	$('.events-soon').empty();
	var month = startDate.getMonth() + 1;
	var day = startDate.getDate();
	if (month < 10) {
		month = '0' + month;
	}
	if (day < 10) {
		day = '0' + day;
	}
	var date = startDate.getFullYear() + '-' + month + '-' + day;
	$.get('./' + mcms_lp + '?ajax=1&w=eventsClosest&startdate=' + date + '&random=' + new Date().getTime(), function(response) {
		$('.events-soon').replaceWith(response);
	});
	if (!$('.events-mode-expanded').is(':visible') ) {
		$('#events h2.viewmode-control').click();
	}
};

// on DOM ready
$(function() {
	
	$('p.additional.events a').click(function() {
		$('#events h2.viewmode-control').click();
		return false;
	});
	
	// подгружает блок с выставками различного способа отображения
	$('#events .events-formats-container ul.tabber-navigation li a[href]').live('click', function() {
		var mode = $(this).attr('href').match(/eventsviewmode=(.*)/)[1];
		var url = './' + mcms_lp + '?ajax=1&w=eventsMain&eventsviewmode=' + mode;
		$.get(url, function(response) {
			$('#events .events-formats-container').replaceWith(response);
			if (mode == 'date') {
				p.eTInit();
			} else if (mode == 'subject') {
				$('#events ul.events-categories li').removeClass('active').find('h4 a').attr('href', './');
			}
			if (mode == 'date') {
				if (screen.height > 768) {
					$('#bn-events').show();
				}
				$('.events-with-important, .light-section .column-primary .events-soon, #events h2.viewmode-control').show();
			} else {
				$('#bn-events').hide();
				$('.events-with-important, .light-section .column-primary .events-soon, #events h2.viewmode-control').hide();
				if ($('.light-section .column-secondary .events-mode-expanded').is(':hidden') ) {
					$('#events h2.viewmode-control').click();
				}
			}
		});
		return false;
	});
	
	/* 200мс - втф?*/
	// галерея в блоке О компании
	$('.popeye').popeye({
		oflabel: '/'
	});
	
	
	// скрытие/раскрытие основных блоков
	$('#events h2.viewmode-control').toggle(function() {
		$('p.additional.events').hide();
		$('#bn-events').css('visibility', 'hidden');
		$('.events-mode-expanded').slideDown(function() {
			$('#bn-events').css('visibility', 'visible');
		});
		$(this).removeClass('collapsed').addClass('expanded');
		$(this).find('img').attr('src', 'sites/default/themes/lenexpo/images/misc/events-expanded-' + mcms_lang + '.png');
		return false;
	}, function() {
		$('p.additional.events').show();
		$('#bn-events').css('visibility', 'hidden');
		$('.events-mode-expanded').slideUp(function() {
			if (screen.height > 768) {
				$('#bn-events').show();
				$('#bn-events').css('visibility', 'visible');
			} else {
				$('#bn-events').hide();
			}
		});
		$(this).removeClass('expanded').addClass('collapsed');
		$(this).find('img').attr('src', 'sites/default/themes/lenexpo/images/misc/events-collapsed-' + mcms_lang + '.png');
		return false;
	});
	
	$('#complex h2.viewmode-control').toggle(function() {
		$('#complex').toggleClass('collapsed').toggleClass('expanded');
		$(this).removeClass('collapsed').addClass('expanded');
		$('.complex-mode-expanded').animate({
			height: $('.complex-mode-expanded').data('height')
		}, function() {
			$(this).css('height', 'auto');
		});
		$(this).find('img').attr('src', 'sites/default/themes/lenexpo/images/misc/complex-expanded-' + mcms_lang + '.png');
		if ($.fn.ifixpng) {
			$(this).find('img').ifixpng();
		}
		return false;
	}, function() {
		$('#complex').toggleClass('collapsed').toggleClass('expanded');
		$(this).removeClass('expanded').addClass('collapsed');
		$('.complex-mode-expanded').data('height', $('.complex-mode-expanded').height() );
		$('.complex-mode-expanded').animate({
			height: 0
		});
		$('#complex .container').animate({
			paddingBottom: '1.334em'
		});
		$(this).find('img').attr('src', 'sites/default/themes/lenexpo/images/misc/complex-collapsed-' + mcms_lang + '.png');
		if ($.fn.ifixpng) {
			$(this).find('img').ifixpng();
		}
		return false;
	});

});/*
 * Хронология событий
 */
var p = p || {};
p.eTInit = function() {
	
	var request = $.get('http://' + location.host + '/' + mcms_lang + '/api/lenexpo/timeline.xml?random=' + new Date().getTime(), function(response) {
		response = $(response);
		
		var currentDate = new Date(request.getResponseHeader('Date') ) || new Date();
		currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() );
		
		// исп. для вывода подписей в блоках-месяцах
		var monthNames;
		if (mcms_lang == 'ru') {
			monthNames =  ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'];
		} else {
			monthNames =  ['January','February','March','April','May','June','July','August','September','October','November','December'];
		}
		// namespace, все что связано с компонентой
		var eT = {
			events: response.find('event'),
			normalizedEvents: [],
			startDate: new Date('01/01/2050'),
			endDate: new Date('01/01/1980'),
			handlePos: function() {
				return parseInt(eT.handle.css('left'), 10) || 0;
			},
			selectedDate: new Date()
		};
		
		// преобразуем инф. из xml в более удобное представление
		$.each(eT.events, function() {
			var event = {};
			event.startDate = new Date($(this).attr('startdate').replace(/-/g, '/') );
			event.endDate = new Date($(this).attr('startdate').replace(/-/g, '/') );
			event.own = $(this).attr('own') ? true : false;
			event.name = $(this).attr('name');
			eT.normalizedEvents.push(event);
		});
		
		// собираем структуру, сохраняем ссылки на эл-ты для послед. исп.
		eT.container = $('#events-timeline');
		eT.scrollLeft = $('<img id="et-scrollleft" class="unavailable" src="sites/default/themes/lenexpo/images/pixel.png" width="13" height="11" alt="Раньше" />').appendTo(eT.container);
		eT.scrollRight = $('<img id="et-scrollright" src="sites/default/themes/lenexpo/images/pixel.png" width="13" height="11" alt="Позднее" />').appendTo(eT.container);
		eT.viewport = $('<div class="et-viewport" />').appendTo(eT.container);
		eT.timelineContainer = $('<div class="et-timeline" />').appendTo(eT.viewport);
		eT.handle = $('<span class="et-handle" />').appendTo(eT.timelineContainer);
		eT.flagsContainer = $('<ul class="et-flags" />').appendTo(eT.timelineContainer);
		eT.pastLine = $('<div class="et-past" />').appendTo(eT.timelineContainer);
		eT.futureLine = $('<div class="et-future" />').appendTo(eT.timelineContainer);
		eT.monthsContainer = $('<ul class="et-months" />').appendTo(eT.timelineContainer);
		
		// speed-ups
		eT.viewportWidth = eT.viewport.width();
		eT.handleWidth = 17;
		
		// находим самую раннюю и позднюю из дат событий
		$.each(eT.normalizedEvents, function() {
			if (this.startDate < eT.startDate) {
				eT.startDate = new Date(this.startDate);
			}
			if (this.startDate > eT.endDate) {
				eT.endDate = new Date(this.startDate);
			}
		});
		
		// начало - 1 месяц, 1 день; конец + 1 месяц, последнее число
		// что-то явно не то с eT.endDate. вроде была проблема с проставлением флажка последней выставки. временно решалась комментированием строк с мод. eT.endDate, но это рушило определение тек. даты
		eT.startDate.setMonth(eT.startDate.getMonth() - 1);
		eT.endDate.setMonth(eT.endDate.getMonth() + 1);
		eT.startDate.setDate(1);
		eT.endDate.setDate(new Date(eT.endDate.getFullYear(), eT.endDate.getMonth() + 1, 0).getDate() );
		
		/* передвигает бегунок на указанную позицию, вычисляет и заменяет число */
		function moveHandle(x, month, callback) {
			function animate() {
				eT.handle.animate({
					left: Math.round(x - eT.handleWidth / 2)
				}, function() {
					var month = month || findMonthAtPosition(x);
					var day = (x - $(month).data('props').left + 5) / 5;
					eT.selectedDate = new Date($(month).data('props').year, $(month).data('props').month, day);
					eT.handle.text(parseInt(day, 10) || 1);
					if (callback) {
						callback();
					}
				});
			}
			
			// если бегунок хочет убежать за пределы видимости - перемещаем шкалу
			if (-eT.timelineContainerPos >  x - eT.handleWidth / 2 || -eT.timelineContainerPos + eT.viewportWidth <  x - eT.handleWidth / 2) {
				var month = findMonthAtPosition(x - eT.handleWidth / 2);
				var newPos;
				if (eT.timelineContainer.width() + -$(month).data('props').left < eT.viewportWidth) {
					newPos = -(eT.timelineContainer.width() - eT.viewportWidth) + 1;
				} else {
					newPos = -$(month).data('props').left
				}
				eT.timelineContainer.animate({
					left: newPos
				}, function() {
					eT.timelineContainerPos = newPos;
					colorizeScrollers();
					animate();
				});
			} else {
				animate();
			}
		}
		
		/* возвращает элемент списка, нах. по ук. координатам */
		function findMonthAtPosition(x) {
			var month;
			eT.months.each(function() {
				if (x > $(this).data('props').left && x < $(this).data('props').left + $(this).data('props').width + 1) {
					month = this;
					return false;
				}
			});
			return month;
		}
		
		/* возвращает информацию о ближайшем к коорд. флажке */
		function findNearestFlag(x) {
			var leftFlag = {}, rightFlag = {}, targetFlag;
			
			for (var i = 0; i < eT.flags.length; i++) {
				var flagPosition = eT.flags[i].style.left.match(/\d+/)[0];
				if (flagPosition < x) {
					leftFlag = {
						el: eT.flags[i],
						pos: flagPosition
					};
				} else {
					rightFlag = {
						el: eT.flags[i],
						pos: flagPosition
					};
					break;
				}
			}
			
			if (leftFlag && !rightFlag.el || leftFlag && x - leftFlag.pos < rightFlag.pos - x) {
				targetFlag = leftFlag;
			} else {
				targetFlag = rightFlag;
			}
			return targetFlag;
		}
		
	
		// проходим по каждому месяцу из диапазона дат
		var month = '-1', totalWidth = 0;
		var date = new Date(eT.startDate), end = new Date(eT.endDate);
		//end.setDate(new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate() );
		for (; date <= end; date.setMonth(date.getMonth() + 1) ) {
			// кол-во дней в месяце
			var d = new Date(date.getFullYear(), date.getMonth() + 1, 0);
			// каждый день занимает 5px
			var monthWidth = d.getDate() * 5;
			// собираем эл-т списка, запоминаем его хар-ки
			var monthIdx = date.getMonth() + 1;
			if (monthIdx < 10) {
				monthIdx = '0' + monthIdx;
			}
			var text = monthNames[date.getMonth()];
			if (currentDate.getFullYear() != date.getFullYear() ) {
				text +=  ' ' + date.getFullYear();
			}
			var el = $('<li />').text(text).addClass('month-' + monthIdx + '-bg').css('width', monthWidth).data('props', {
				month: date.getMonth(),
				year: date.getFullYear(),
				left: totalWidth,
				width: monthWidth
			}).click(function(e) {
				moveHandle(-eT.timelineContainerPos + e.clientX - eT.container.offset().left, this, function() {
					moveHandle(findNearestFlag(eT.handlePos() + eT.handleWidth / 2).pos, undefined, function() {
						p.showNearestEvents(eT.selectedDate);
					});
				});
			});
			
			eT.monthsContainer.append(el);
			
			totalWidth += monthWidth + 1;
			
			// добавляем флажки событий в этом месяце
			var firstEvent = null, latestEvent = eT.normalizedEvents[0], eventsNum = 1, name = latestEvent.name, compositeName = latestEvent.name + ', ';
			for (var i = 0, ilen = eT.normalizedEvents.length; i < ilen; i++) {
				name = eT.normalizedEvents[i].name;
				if (i + 1 < ilen && eT.normalizedEvents[i+1].startDate.getTime() - latestEvent.startDate.getTime() <= 432000000) {
					if (!firstEvent) {
						firstEvent = eT.normalizedEvents[i];
					}
					compositeName += eT.normalizedEvents[i+1].name + ', ';
					eventsNum++;
					continue;
				}
				if (eT.normalizedEvents[i].startDate.getFullYear() == date.getFullYear() && eT.normalizedEvents[i].startDate.getMonth() == date.getMonth() ) {
					var el, flag;
					if (eventsNum > 1) {
						//el = $('<li />').css('left', totalWidth - monthWidth + (eT.normalizedEvents[i].startDate.getDate() - 1) * 5 - eventsNum * 5 / 2);
						el = $('<li />').css('left', totalWidth - monthWidth + (firstEvent.startDate.getDate() - 1) * 5);
						flag = $('<span>' + eventsNum + '</span><img src="sites/default/themes/lenexpo/images/pixel.png" class="group" width="21" height="25" title="' + compositeName.replace(/, $/, '').replace(/ ,/gi,',') + '" alt="" />');
					} else {
						el = $('<li />').css('left', totalWidth - monthWidth + (eT.normalizedEvents[i].startDate.getDate() - 1) * 5);
						flag = $('<img src="sites/default/themes/lenexpo/images/pixel.png" class="normal" width="10" height="11" title="' + name + '" alt="" />');
					}
					el.append(flag);
					el.appendTo(eT.flagsContainer);
				}
				firstEvent = null;
				latestEvent = eT.normalizedEvents[i+1] ||  eT.normalizedEvents[i];
				compositeName = eT.normalizedEvents[i+1] && eT.normalizedEvents[i+1].name + ', ' || eT.normalizedEvents[i].name + ', ';
				eventsNum = 1;
			}
		}
		
		eT.flags = eT.flagsContainer.find('li');
		eT.months = eT.monthsContainer.find('li');
		eT.timelineContainer.css('width', totalWidth);
		
		// показываем переход между прошлым и будущим
		
		var range = eT.endDate - eT.startDate;
		var diff = eT.endDate - currentDate;
		
		var future = diff * 100 / range;
		var past = 100 - future;
		
		eT.pastLine.css('width', Math.round(totalWidth / 100 * past) - 2 + 'px');
		eT.futureLine.css('width', Math.round(totalWidth / 100 * future) + 'px');
		
		// перемещаем бегунок на текущую дату
		eT.handle.css('left', totalWidth / 100 * past - Math.round(eT.handleWidth / 2) - 1 + 'px').text(currentDate.getDate() );
		if (totalWidth / 100 * past - eT.handleWidth / 2 > eT.viewportWidth / 2) {
			eT.timelineContainerPos = -totalWidth / 100 * past - eT.handleWidth / 2 + eT.viewportWidth / 2;
			eT.timelineContainer.css('left', eT.timelineContainerPos);
		}
		
		function colorizeScrollers() {
			if (eT.futureLine.position().left + eT.timelineContainerPos > eT.viewportWidth) {
				eT.scrollRight.addClass('unavailable');
			} else {
				eT.scrollRight.removeClass('unavailable');
			}
			if (eT.futureLine.position().left + eT.timelineContainerPos < 0) {
				eT.scrollLeft.removeClass('unavailable');
			} else {
				eT.scrollLeft.addClass('unavailable');
			}
		}
		
		// пролистывание влево
		eT.scrollLeft.click(function() {
			scrollLeft();
			return false;
		});
		
		if ('\v'=='v') {
			eT.scrollLeft.dblclick(function() {
				scrollLeft();
				return false;
			});
		}
		
		function scrollLeft() {
			eT.months.each(function(key) {
				if (eT.timelineContainerPos + $(this).position().left < 0 && eT.timelineContainerPos + eT.months.eq(key + 1).data('props').left > -1) {
					var target = $(this);
					if (eT.timelineContainer.queue('fx').length != 0 && $(this).prev().length ) {
						var length = eT.timelineContainer.queue('fx').length - 1;
						if ($(this).prevAll().length < eT.timelineContainer.queue('fx').length) {
							length = $(this).prevAll().length - 1;
						}
						target = $(this).prevAll().eq(length);
					}
					if (target.position().left === 0) {
						eT.timelineContainerPos = 0;
					} else {
						eT.timelineContainerPos = -target.position().left + 1;
					}
					eT.timelineContainer.animate({
						left: eT.timelineContainerPos
					}, colorizeScrollers);
					return false;
				}
			});
		}
			
		// пролистывание вправо
		eT.scrollRight.click(function() {
			scrollRight();
			return false;
		});
		
		if ('\v'=='v') {
			eT.scrollRight.dblclick(function() {
				scrollRight();
				return false;
			});
		}
		
		function scrollRight() {
			eT.months.each(function(key) {
				if ($(this).width() + $(this).data('props').left + eT.timelineContainerPos > eT.container.width() + 1 ) {
					var target = $(this);
					if (eT.timelineContainer.queue('fx').length != 0 && $(this).next().length) {
						var length = eT.timelineContainer.queue('fx').length - 1;
						if ($(this).nextAll().length < eT.timelineContainer.queue('fx').length) {
							length = $(this).nextAll().length - 1;
						}
						target = $(this).nextAll().eq(length);
					}
					eT.timelineContainerPos = eT.container.width() - (target.position().left + target.width() );
					eT.timelineContainer.animate({
						left: eT.timelineContainerPos
					}, colorizeScrollers);
					return false;
				}
			});
		}
		
	
		
		// перемещение бегунка
		var oldX, trigger;
		eT.handle.mousedown(function(e) {
			oldX = e.clientX;
			trigger = e.clientX;
			$(document).mousemove(mmhandler);
			$(document).mouseup(muphandler);
			return false;
		});
		
		function muphandler() {
			moveHandle(findNearestFlag(eT.handlePos() + eT.handleWidth / 2).pos, undefined, function() {
				p.showNearestEvents(eT.selectedDate);
			});
			$(document).unbind('mousemove', mmhandler);
			$(document).unbind('mouseup', arguments.callee);
		}
		
		function mmhandler(e) {
			var delta = e.clientX - oldX;		
			var newPos = (parseInt(eT.handle.css('left'), 10) || 0) + e.clientX - oldX;
			
			// вправо
			if (delta >= 0) {
				if (newPos + eT.handleWidth + eT.timelineContainerPos >= eT.viewportWidth) {
					newPos = eT.viewportWidth - eT.timelineContainerPos - eT.handleWidth;
				}
			} 
			// влево
			else {
				if (newPos + eT.timelineContainerPos <= 0) {
					newPos = -eT.timelineContainerPos;
				}
			}
			
			eT.handle.css({
				left: newPos
			});

			if (trigger - e.clientX > 5 || trigger - e.clientX < 5) {
				var pointer = eT.handle.position().left + eT.handleWidth / 2;
				eT.months.each(function() {
					// текущий месяц
					if (pointer > $(this).data('props').left && pointer < $(this).data('props').left + $(this).data('props').width) {
						var day = (pointer - $(this).data('props').left + 5) / 5;
						eT.handle.text(parseInt(day, 10) || 1);
						return false;
					}
				});
				trigger = e.clientX;
			}
			
			oldX = e.clientX;
			return false;
		}
		
		
		$(window).resize(function() {
			eT.viewportWidth = eT.viewport.width();
			if (eT.timelineContainer.width() + eT.timelineContainerPos < eT.viewportWidth) {
				eT.timelineContainer.css('left', '-' + (eT.timelineContainer.width() - eT.viewportWidth) + 'px');
			}
		});
	}, 'xml');
};

$(function() {
	if ($('#events-timeline').length) {
		p.eTInit();
	}
});