// page init
jQuery(function(){
	initCufon();
	initInputs();
	jcf.customForms.replaceAll();
	initTwitGallery();
	initGalleries();
	initLightbox();
	initMainNav();
	initNavFix();
	fixTrans();
	initTabs();
});

// clear inputs
function initInputs(){
	jQuery('input:text, input:password, textarea').each(function(){
		var _el = jQuery(this);
		var _val = _el.val();
		_el.bind('focus', function(){
			if(this.value == _val) this.value = '';
		}).bind('blur', function(){
			if(this.value == '') this.value = _val;
		});
	});
};

// cufon init
function _refresh (x,y) {$(x).mouseout(function(){setTimeout(function(){Cufon.refresh(y)}, 10);});}
function initCufon() {
		Cufon.replace('#nav>li>a', { hover:true, fontFamily: 'Droid Sans'});
		Cufon.replace('.nav-bar .btn-live-chat', { textShadow: '#4b6322 -1px -1px, #4b6322 1px 1px', fontFamily: 'Droid Sans'});	
		Cufon.replace('.header-section .gallery h2', { textShadow: '#1f5071 1px 2px', fontFamily: 'Droid Sans'});	
		Cufon.replace('.header-section .visual-block h1', { textShadow: '#1f5071 1px 1px', fontFamily: 'Droid Sans'});	
		Cufon.replace('#main .ads-container .columns h2', { textShadow: '#879e55 1px 1px', fontFamily: 'Droid Sans'});	
		Cufon.replace('#main .ads-container .ads-column h3', { fontFamily: 'Droid Sans'});	
		Cufon.replace('#sidebar .box q', { fontFamily: 'Droid Sans'});	
		Cufon.replace('#sidebar .box-4 p', { fontFamily: 'Droid Sans'});	
		Cufon.replace('#content h2', { fontFamily: 'Droid Sans'});	
		Cufon.replace('#content h3', { fontFamily: 'Droid Sans'});	
		Cufon.replace('#content strong.mark', { fontFamily: 'Droid Sans'});	
		Cufon.replace('.header-section .gallery .btn-free-trial span', { textShadow: '#9c0b0b 1px 1px', fontFamily: 'Droid Sans'});	
		Cufon.replace('#sidebar .box .btn-red strong', { textShadow: '#9c0b0b 1px 1px', fontFamily: 'Droid Sans'});	
		Cufon.replace('.header-section .visual-block .btn-free-trial span', { textShadow: '#9c0b0b 1px 1px', fontFamily: 'Droid Sans'});	
		Cufon.replace('#sidebar .box .btn-green', { textShadow: '#709711 -1px 1px', fontFamily: 'Droid Sans'});	
		Cufon.replace('.header-section .gallery .text-holder', {fontFamily: 'Droid Sans'});
		Cufon.replace('#main .promo-box .heading a', { hover:true, fontFamily: 'Droid Sans'});
		Cufon.replace('#main .promo-section .column .text-holder .mark', { fontFamily: 'Droid Sans'});
		Cufon.replace('#main .promo-box .btn-green span', { fontFamily: 'Droid Sans'});
		Cufon.replace('#main .social-section .news-list .date', { fontFamily: 'Droid Sans'});
		Cufon.replace('#footer .contacts-block .btn-live-chat span', { textShadow: '#8e0101 -1px -1px', fontFamily: 'Droid Sans'});
		Cufon.replace('#main .slider-column .gallery h1', { fontFamily: 'Droid Sans'});
		Cufon.replace('#main .row-section .column h3', { fontFamily: 'Droid Sans'});
		Cufon.replace('#main .service-box .serice-list li span', { fontFamily: 'Droid Sans'});
		Cufon.replace('#main .social-section .btn-more span', { fontFamily: 'Droid Sans'});
		Cufon.replace('#content .quote-box blockquote q', { fontFamily: 'Droid Sans'});
		Cufon.replace('#sidebar .box h3', { fontFamily: 'Droid Sans'});
		Cufon.replace('#main .row-section-add .btn-more span', { fontFamily: 'Droid Sans'});
		Cufon.replace('#sidebar .box-4 h3', { fontFamily: 'Droid Sans'});	
		Cufon.replace('.header-section .visual-block .text p', { fontFamily: 'Droid Sans'});	
		Cufon.replace('#main .row-section-add .column h3', { fontFamily: 'Droid Sans'});	
		Cufon.replace('#sidebar .box-5 h3', { fontFamily: 'Droid Sans'});	
		Cufon.replace('#sidebar .box-6 h3', { fontFamily: 'Droid Sans'});	
		_refresh('#nav>li','#nav>li>a','#main .promo-box .heading a');
}

// nav fix
function initNavFix() {
	new touchNav({
		navBlock: 'nav'
	});
};

// main nav init
function initMainNav(){
	initAutoScalingNav({
		menuId: "nav",
		minPaddings: 5,
		sideClasses: true,
		spacing: 2
	});
};

// init tabs
function initTabs() {
	if(typeof ContentTabs !== 'undefined') {
		ContentTabs.init();
	}
}

// galleries init
function initGalleries(){
	// homepage main slideshow
	jQuery('div.carousel').scrollGallery({
		autoRotation:true,
		switchTime:10000, //ms
		duration:650 //ms
	});
	// homepage text slideshow
	jQuery('div.slideshow').fadeGallery({
		autoRotation:true,
		autoHeight:false,
		switchTime:10000,
		duration:(jQuery.browser.msie && jQuery.browser.version < 9) ? 0 : 650 //ms
	});
};

// lightbox init
function initLightbox(){
	$('a.video, a.open-popup').jmodalBox({
		animSpeed: 300,
		overlayShow: true,
		overlayBg: '#000',
		overlayOpacity: 0.7,
		transition: 'fade'
	});
};

// country selector in footer
function goto(form) {
	 var index=form.countryselect.selectedIndex;
 	 if (form.countryselect.options[index].value != "0") {
		location=form.countryselect.options[index].value;
	 }
};

// twitter gallery init
function initTwitGallery(){
	var gallery = jQuery('#twitter');
	if (gallery.length) {
		var set = '';
		twitterHelper.loadTweets('StratoGen', 9, function(data) {
			for(var i = 0; i < data.length; i++) {
				set += '<li><span class="post"><span class="text"><strong class="name">@'+twitterHelper.parseText(data[i].user.name)+'</strong>'+twitterHelper.parseText(data[i].text)+'</span><span class="by"><em class="time"> - '+twitterHelper.relativeTime(data[i].created_at)+'</em></span></span></li>';
			}
			gallery.html('<ul class="news-list feed-list">'+set+'</ul>');
			// gallery settings
			jQuery('div.twitter-gallery').scrollGallery({
				sliderHolder: 'div.mask',
				btnPrev:'a.btn-up',
				btnNext:'a.btn-down',
				pagerLinks:false,
				generatePagination:false,
				autoRotation:true,
				vertical:true,
				switchTime:10000, //ms
				duration:650, //ms
				step:1
			});
		});
	} 
};

// jmodalBox module
;(function(window, $, undefined){

// utility functions for older jQuery versions
var proxy = $.proxy || function(f, scope) {
	return function(){ return f.apply(scope,arguments) };
}
var detach = function(obj) {
	if($.fn.detach) {
		obj.detach();
	} else {
		obj.each(function(){ this.parentNode.removeChild(this) });
	}
}

// jmodalBox instance
var jmodalBox = {
	namespace: 'jmodalbox',
	defaultOptions: {
		// structure options
		overlayStructure: '<div class="jmodalbox-overlay"><div class="jmodalbox-cover"></div></div>',
		modalStructure: '<div class="jmodalbox-modal"><div class="jmodalbox-lt"></div><div class="jmodalbox-t"></div><div class="jmodalbox-rt"></div><div class="jmodalbox-r"></div><div class="jmodalbox-rb"></div><div class="jmodalbox-b"></div><div class="jmodalbox-lb"></div><div class="jmodalbox-l"></div><a href="#" class="jmodalbox-close"><span>x</span></a><a href="#" class="jmodalbox-prev">&lt;</a><div class="jmodalbox-content"></div><a href="#" class="jmodalbox-next">&gt;</a></div>',
		modalHolder: '.jmodalbox-content',
		modalBtnPrev: '.jmodalbox-prev',
		modalBtnNext: '.jmodalbox-next',
		modalBtnClose: '.jmodalbox-close',
		closeButton: 'a.close, a.btn-close, a.cancel',
		groupClass: 'jmodalbox-groupactive',
		loadingClass: 'jmodalbox-loading',
		groupAttribute: 'rel',
		zIndex: 1000,
		
		// string constants and callbacks
		contentUnavailableText: 'The requested content cannot be loaded.<br />Please try again later.',
		onBeforeClose: null,
		onAfterClose: null,
		onBeforeShow: null,
		onAfterShow: null,
		
		// overlay options
		overlayOpacity: 0.65,
		overlayShow: true,
		overlayBg: '#000',
		
		// lightbox settings
		cycleRotation: false,
		animSpeed: 300,
		resizeSpeed: 300,
		changeSpeed: 150,
		event: 'click',
		boxWidth: 800,
		boxHeight: 480,
		easing: 'swing',
		easingIn: 'swing',
		easingOut: 'swing',
		
		// misc options
		theme: 'jm-default',
		currentSet: [],
		currentIndex: 0,
		handleEsc: true,
		handleArrows: true,
		overlayClose: true,
		repositionOnScroll: false,
		alwaysPreventScrolling: false,
		
		// content players and effects settings
		player: 'auto',
		transition: 'fade',
		changeTransition: 'fade'
	},
	showTransitions: {
		'none': {
			show: function(inst, callback) {
				inst.overlay.show();
				inst.modal.show();
				inst._makeCallback(callback);
			},
			hide: function(inst, callback) {
				inst.overlay.hide();
				inst.modal.hide();
				inst._makeCallback(callback);
			}
		}
	},
	changeTransitions: {
		'none': {
			animIn: function(inst, callback) {
				inst.modalContent.css({visibility:'visible'});
				inst._makeCallback(callback);
			},
			animOut: function(inst, callback) {
				inst.modalContent.css({visibility:'hidden'});
				inst._makeCallback(callback);
			}
		},
		'fade': {
			animIn: function(inst, callback) {
				inst.modalContent.css({opacity:0,visibility:'visible'}).animate({opacity:1},{duration:inst.currentOptions.changeSpeed,easing:'linear',complete:function(){
					inst.modalContent.css({opacity:''});
					inst._makeCallback(callback);
				}});
			},
			animOut: function(inst, callback) {
				inst.modalContent.animate({opacity:0},{duration:inst.currentOptions.changeSpeed,easing:'linear',complete:function(){
					inst.modalContent.css({opacity:'',visibility:'hidden'});
					inst._makeCallback(callback);
				}});
			}
		}
	},
	players: {
		'flash': {
			canPlay: function(opt) {
				return typeof opt.target === 'string' && /\.(swf)(.*)?$/i.test(opt.target);
			},
			prepareContent: function(inst, callback) {
				var flashObject = $('<object type="application/x-shockwave-flash" data="'+inst.currentOptions.target+'">').css({verticalAlign:'top'});
				flashObject.attr('width',inst.currentOptions.boxWidth).attr('height', inst.currentOptions.boxHeight);
				flashObject.html('<param name="movie" value="'+inst.currentOptions.target+'" /><param value="transparent" name="wmode" />');
				inst.tmpPlayer = $('<div>').css({verticalAlign:'top', width:inst.currentOptions.boxWidth, height:inst.currentOptions.boxHeight }).append(flashObject);
				inst.tmpPlayer.appendTo(inst.modalContent);
				inst._makeCallback(callback);
			},
			restoreContent: function(inst, callback) {
				inst.tmpPlayer.remove();
				inst._makeCallback(callback);
			}
		},
		'iframe': {
			canPlay: function(opt) {
				return typeof opt.target === 'string' && opt.target.indexOf('http') === 0;
			},
			prepareContent: function(inst, callback) {
				// old jquery version compatible syntax
				inst.tmpPlayer = $('<iframe>').attr('src', inst.currentOptions.target).attr('frameBorder',0);
				inst.tmpPlayer.attr('width', inst.currentOptions.boxWidth);
				inst.tmpPlayer.attr('height', inst.currentOptions.boxHeight);
				inst.tmpPlayer.css({verticalAlign:'top'}).appendTo(inst.modalContent).show();
				inst._makeCallback(callback);
			},
			restoreContent: function(inst, callback) {
				inst.tmpPlayer.remove();
				inst._makeCallback(callback);
			}
		},
		'inline': {
			canPlay: function(opt) {
				return typeof opt.target === 'string' && opt.target.charAt(0) == '#';
			},
			prepareContent: function(inst, callback) {
				var lbox = $(inst.currentOptions.target);
				inst.tmpPlayer = $('<div>').addClass('jmodalbox-tmp').insertBefore(lbox);
				lbox.appendTo(inst.modalContent).show();
				inst._makeCallback(callback);
			},
			restoreContent: function(inst, callback) {
				$(inst.currentOptions.target).insertBefore(inst.tmpPlayer).hide();
				inst.tmpPlayer.remove();
				inst._makeCallback(callback);
			}
		},
		'ajax': {
			canPlay: function(opt) {
				return typeof opt.target === 'string' && /\.(html|htm|php|asp|aspx)(.*)?$/i.test(opt.target);
			},
			prepareContent: function(inst, callback) {
				setTimeout(function(){
					// default ajax options
					var ajaxOptions = {
						type:'get',
						dataType:'text',
						url:inst.currentOptions.target,
						success: function(msg){
							inst.tmpPlayer = $('<div>').html(msg).children().appendTo(inst.modalContent).show();
							inst._makeCallback(callback);
						},
						error: function(){
							// error callback
							if(typeof inst.currentOptions.onError === 'function') {
								inst.currentOptions.onError();
							}

							// lightbox callback
							inst.tmpPlayer = $('<div>').html(inst.currentOptions.contentUnavailableText).appendTo(inst.modalContent).show();
							inst._makeCallback(callback);
						}
					}
					// if custom ajax parameters passed (optional)
					if(typeof inst.currentOptions.ajax === 'object') {
						$.extend(ajaxOptions, inst.currentOptions.ajax);
					}
					$.ajax(ajaxOptions);
				},300);
			},
			restoreContent: function(inst, callback) {
				inst.tmpPlayer.remove();
				inst._makeCallback(callback);
			}
		},
		'image': {
			canPlay: function(opt) {
				return typeof opt.target === 'string' && /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i.test(opt.target)
			},
			prepareContent: function(inst, callback) {
				setTimeout(function(){
					inst.tmpPlayer = $('<img>').css({verticalAlign: 'top'}).appendTo(inst.modalContent).bind('load', function(){
						inst._makeCallback(callback);
					}).bind('error',function(){
						// error callback
						inst.tmpPlayer.remove();
						if(typeof inst.currentOptions.onError === 'function') {
							inst.currentOptions.onError();
						}

						// default callback
						inst.tmpPlayer = $('<div>').html(inst.currentOptions.contentUnavailableText).appendTo(inst.modalContent);
						inst._makeCallback(callback);
					}).attr('src',inst.currentOptions.target);
				},100);
			},
			restoreContent: function(inst, callback) {
				inst.tmpPlayer.remove();
				inst._makeCallback(callback);
			}
		}
	},
	init: function() {
		if(!this.isInit) {
			this.isInit = true;
			this._createCurrentOptions();
			this._createElements();
			this._addEventHandlers();
		}
		return this;
	},
	isTouchDevice: (function() {
		try {
			document.createEvent("TouchEvent");
			return true;
		} catch (e) {
			return false;
		}
	}()),
	_initOpeners: function(elems, elemOptions) {
		elems.each(proxy(function(ind,obj){
			var curEl = $(obj);
			curEl.unbind('.'+this.namespace).bind(this.defaultOptions.event+'.'+this.namespace, proxy(function(){
				this.openLink(curEl, elemOptions);
				return false;
			},this));
		},this));
	},
	_createElements: function() {
		// create overlay
		this.win = $(window);
		this.doc = $(document);
		this.overlay = $(this.defaultOptions.overlayStructure).css({
			overflow: 'hidden',
			zIndex: this.defaultOptions.zIndex,
			position: 'absolute', top:0, left:0,
			background: this.defaultOptions.overlayBg,
			opacity: this.defaultOptions.overlayOpacity,
			webkitTapHighlightColor: 'rgba(255,255,255,0)' // mobile webkit specific
		}).hide();

		// IE6 fix: put iframe in overlay to cover underlying selects
		if($.browser.msie && $.browser.version < 7) {
			var frame = $('<iframe>').prependTo(this.overlay);
			this.overlay.children().css({position:'absolute',width:'100%',height:'100%',background:'#000',opacity:0,zIndex:1});
		}

		// create modal div structure
		this.modal = $(this.defaultOptions.modalStructure).css({
			zIndex: this.defaultOptions.zIndex + 1,
			position:'absolute'
		})
		this.modalOrigClassName = this.modal.attr('class');
		this.modal.addClass(this.defaultOptions.theme).hide();
		this.modalContent = this.modal.find(this.defaultOptions.modalHolder).css({'float':'left'}); // IE fix
		
		// get elements
		this.modalPrev = this.modal.find(this.defaultOptions.modalBtnPrev);
		this.modalNext = this.modal.find(this.defaultOptions.modalBtnNext);
		this.modalClose = this.modal.find(this.defaultOptions.modalBtnClose);
	},
	_addEventHandlers: function() {
		// positioning events
		this.win.bind('resize.'+this.namespace,proxy(this._handleResize,this));
		if(this.isTouchDevice) {
			this.win.bind('orientationchange.'+this.namespace,proxy(this._handleResize,this));	
		} else {
			this.win.bind('scroll.'+this.namespace,proxy(this._handleScroll,this));
		}
		
		// lightbox events
		this.overlay.bind('click.'+this.namespace,proxy(function(){
			if(this.currentOptions.overlayClose) {
				this.close();
			}
		},this));
		this.doc.bind('keydown.'+this.namespace,proxy(function(e){
			// prevent scrolling if needed
			this._preventScrolling(e, e.keyCode == 39 ? -1 : e.keyCode == 37 ? 1 : 0);
		
			// analize keycodes
			switch (e.keyCode) {
				case 27: this.currentOptions.handleEsc && this.close(); break;
				case 37: this.currentOptions.handleArrows && this.prev(); break;
				case 39: this.currentOptions.handleArrows && this.next(); break;
			}
		},this));
		
		// handling mousewheel
		if(!this.isTouchDevice) {
			this.modal.bind('mousewheel',proxy(function(e, delta){
				// prevent scrolling if needed
				this._preventScrolling(e, delta);
			
				// change 
				if(delta < 0) this.next();
				else this.prev();
			},this));
		}
		
		// control buttons handlers
		this.modalPrev.bind(this.defaultOptions.event, proxy(this.prev, this));
		this.modalNext.bind(this.defaultOptions.event, proxy(this.next, this));
		this.modalClose.bind(this.defaultOptions.event, proxy(this.close, this));
	},
	_preventScrolling: function(e, direction) {
		if(this.currentOptions.currentSet.length) {
			if(this.currentOptions.cycleRotation || this.currentOptions.alwaysPreventScrolling) {
				e.preventDefault();
			} else {
				if(direction < 0 && this.currentOptions.currentIndex < this.currentOptions.currentSet.length - 1) {
					e.preventDefault();
				} else if(direction > 0 && this.currentOptions.currentIndex > 0) {
					e.preventDefault();
				}
			}
		}
	},
	_handleScroll: function() {
		// only for desktop browsers
		if(this.currentOptions.repositionOnScroll) {
			clearTimeout(this.eventDelayTimer);
			this.eventDelayTimer = setTimeout(proxy(function(){
				this.repositionLightbox();
			},this), 100);
		}
	},
	_handleResize: function() {
		clearTimeout(this.eventDelayTimer);
		this.repositionLightbox();
	},
	_attachElements: function() {
		if(!this.elementsInPage) {
			this.elementsInPage = true;
			this.body = $(document.body);
			this.overlay.appendTo(this.body);
			this.modal.appendTo(this.body);
		}
	},
	_detachElements: function() {
		if(this.elementsInPage) {
			this.elementsInPage = false;
			detach(this.overlay);
			detach(this.modal);
			this.modalContent.css({width:'',height:'',visibility:''});
		}
	},
	_createCurrentOptions: function(opt) {
		this.currentOptions = $.extend({},this.defaultOptions,opt);
		
		// autodetect lightbox content player if needed
		if(this.currentOptions.player === 'auto') {
			this.currentOptions.player = this._getPossiblePlayer(this.currentOptions);
		}
		
		// apply option changes
		if(this.overlay) {
			this.overlay.css({background:this.currentOptions.overlayBg,opacity:this.currentOptions.overlayOpacity});
		}
		
		// change theme if needed
		if(this.modal) {
			this.modal.attr('class',this.modalOrigClassName).addClass(this.currentOptions.theme);
		}
	},
	_makeCallback: function(func, args) {
		if(typeof func === 'function') {
			func.apply(this, args || arguments)
		}
	},
	_getPossiblePlayer: function(options) {
		for(var p in this.players) {
			if(this.players[p].canPlay(options)) {
				return p;
			}
		}
	},
	_changeAnimation: function(show, callback) {
		this.changeTransitions[this.currentOptions.changeTransition][show ? 'animIn' : 'animOut'](this, callback);
	},
	_prepareContent: function(callback) {
		this.lightboxContentActive = true;
		this.modal.addClass(this.currentOptions.loadingClass);
		this.players[this.currentOptions.player].prepareContent(this, function(){
			this.modal.removeClass(this.currentOptions.loadingClass);
			callback.apply(this,arguments);
		});
	},
	_restoreContent: function(callback) {
		this.lightboxContentActive = false;
		this._changeAnimation(false, function(){
			this.players[this.currentOptions.player].restoreContent(this, callback);
		})
	},
	_postProcessContent: function() {
		// close button
		this.modalContent.find(this.currentOptions.closeButton).unbind('.'+this.namespace).bind(this.currentOptions.event+'.'+this.namespace, proxy(this.close,this));
	},
	_refreshModalState: function() {
		// update modal classes
		if(this.currentOptions.currentSet.length > 1) {
			this.modal.addClass(this.currentOptions.groupClass);
			if(this.currentOptions.cycleRotation) {
				this.modalPrev.show(); this.modalNext.show();
			} else {
				this.modalPrev.hide(); this.modalNext.hide();
				if(this.currentOptions.currentIndex > 0) this.modalPrev.show();
				if(this.currentOptions.currentIndex < this.currentOptions.currentSet.length-1) this.modalNext.show();
			}
		}
		else {
			this.modal.removeClass(this.currentOptions.groupClass);
			this.modalPrev.hide(); this.modalNext.hide();
		}
	},
	addShowTransition: function(obj) {
		if(obj && typeof obj.name === 'string') {
			this.showTransitions[obj.name] = {};
			for(var p in obj) {
				this.showTransitions[obj.name][p] = obj[p];
			}
		}
	},
	_getPageWidth: function() {
		if(!document.body) return 0;
		return Math.max(
			Math.max(document.body.clientWidth, document.documentElement.clientWidth),
			Math.max(document.body.offsetWidth, document.body.scrollWidth, document.documentElement.scrollWidth)
		);
	},
	_getPageHeight: function() {
		if(!document.body) return 0;
		return Math.max(
			Math.max(document.body.clientHeight, document.documentElement.clientHeight),
			Math.max(document.body.offsetHeight, document.body.scrollHeight, document.documentElement.scrollHeight)
		);
	},
	_recalculateDimensions: function() {
		// calculate dimensions
		var d = {
			pageWidth: this._getPageWidth(),
			pageHeight: this._getPageHeight(),
			modalWidth: this.modal.outerWidth(true),
			modalHeight: this.modal.outerHeight(true),
			winWidth: this.win.width(),
			winHeight: this.win.height(),
			scrollTop: this.isTouchDevice && this._lightboxShown ? this.dimensions.scrollTop : this.win.scrollTop(), // freeze scrollTop and scrollLeft for mobile devices
			scrollLeft: this.isTouchDevice && this._lightboxShown ? this.dimensions.scrollLeft : this.win.scrollLeft(),
			contentWidth: this.modalContent.children().outerWidth(true),
			contentHeight: this.modalContent.children().outerHeight(true)
		}
		
		// handle min width
		var diffWidth = Math.abs(document.documentElement.offsetWidth - document.documentElement.scrollWidth);
		if(diffWidth > 0) {
			d.winWidth = d.winWidth + diffWidth;
		}
		
		// calculate offset
		d.diffWidth = d.modalWidth - this.modalContent.outerWidth(true);
		d.diffHeight = d.modalHeight - this.modalContent.outerHeight(true);
		d.modalTop = d.scrollTop + (d.winHeight - (d.diffHeight+d.contentHeight)) / 2;
		d.modalLeft = d.scrollLeft + (d.winWidth - (d.diffWidth+d.contentWidth)) / 2;
		
		// check dimensions
		d.modalTop = Math.max(d.modalTop, 0);
		d.modalLeft = Math.max(d.modalLeft, 0);
		this.dimensions = d;
	},
	repositionLightbox: function() {
		// don't do anything while animating lightbox
		if(this._lightboxAnimating || !this.elementsInPage) return;
	
		// resize overlay
		this.overlay.hide();
		
		// lightbox target coordinates
		this._recalculateDimensions();
		
		this.overlay.css({
			top:0, left:0,
			width: this.dimensions.pageWidth,
			height: this.dimensions.pageHeight
		}).show();

		this.desiredProporties = {
			top: this.dimensions.modalTop,
			left: this.dimensions.modalLeft
		}
		
		// position lightbox when switching between slides
		if(this._lightboxContentSwitch || this._lightboxShown) {
			this.modal.stop().animate(this.desiredProporties,{duration:this.currentOptions.resizeSpeed,easing:'linear'})
		}
		// initial lightbox position
		else {
			this.modal.css(this.desiredProporties);
		}
	},
	_freezeLightbox: function() {
		// freeze lightbox size when removing content
		this._lightboxContentSwitch = true;
		this.modalContent.css({width: this.modalContent.width()});
		this.modalContent.css({height: this.modalContent.height()});
	},
	_unfreezeLightbox: function() {
		// resize lightbox when content changed
		var animSettings = {duration:this.currentOptions.resizeSpeed,easing:'linear'};
		this._lightboxContentSwitch = false;
		this._recalculateDimensions();
		
		// resize animations
		this.modalContent.animate({
			width:this.dimensions.contentWidth,
			height:this.dimensions.contentHeight
		},$.extend({},animSettings));
		this.modal.animate({
			top:this.dimensions.modalTop,
			left:this.dimensions.modalLeft
		},$.extend({},animSettings));
		setTimeout(proxy(function(){
			this._changeAnimation(true);
		},this),this.currentOptions.resizeSpeed);
	},
	_preparePosition: function() {
		this._lightboxAnimating = false;
		this.modal.show();
		this.repositionLightbox();
		this.modal.hide();
		this.overlay.hide();
		this._lightboxAnimating = true;
	},
	_preprocessOptions: function(opt) {
		// handle transition
		opt.transition = opt.transition || this.defaultOptions.transition;
		if(!opt.transitionIn) opt.transitionIn = opt.transition;
		if(!opt.transitionOut) opt.transitionOut = opt.transition;
		
		// handle easing
		opt.easing = opt.easing || this.defaultOptions.easing;
		if(!opt.easingIn) opt.easingIn = opt.easing;
		if(!opt.easingOut) opt.easingOut = opt.easing;
		
		// handle manual call
		if(opt.currentSet && !opt.target) {
			opt.target = opt.currentSet[0];
		}
		
		// handle percent dimensions
		if(typeof opt.width === 'string' && opt.width.indexOf('%') > 0) {
			opt.boxWidth = parseInt(opt.width,10) * this.win.width() / 100;
		} else if(typeof opt.width === 'number'){
			opt.boxWidth = opt.width;
		}
		if(typeof opt.height === 'string' && opt.height.indexOf('%') > 0) {
			opt.boxHeight = parseInt(opt.height,10) * this.win.height() / 100;
		} else if(typeof opt.height === 'number'){
			opt.boxHeight = opt.height;
		}
		return opt;
	},
	_getTarget: function(data) {
		if(typeof data === 'string') {
			return data;
		} else if(typeof data === 'object') {
			return data.href;
		}
	},
	switchContent: function(opt) {
		this._createCurrentOptions(opt);
		this._refreshModalState();
		this._attachElements();
		this._prepareContent(function(){
			this._postProcessContent();
			
			if(this._lightboxContentSwitch) {
				// unfreeze lightbox when changing content
				this._unfreezeLightbox();
			} else {
				// prepare lightbox positions before reveal
				this._preparePosition();
				this.showTransitions[this.currentOptions.transitionIn].show(this,function(){
					this._lightboxAnimating = false;
					this.repositionLightbox();
					this._lightboxShown = true;
					
					// after show callback
					if(typeof opt.onAfterShow === 'function') {
						opt.onAfterShow();
					}
				});
			}
		});
	},
	prev: function(e) {
		if(!this._lightboxContentSwitch && this.currentOptions.currentSet.length) {
			this.cycleFlag = false;
			if(this.currentOptions.currentIndex > 0) {
				this.currentOptions.currentIndex--;
				this.cycleFlag = true;
			} else if(this.currentOptions.cycleRotation){
				this.currentOptions.currentIndex = this.currentOptions.currentSet.length-1;
				this.cycleFlag = true;
			}
			if(this.cycleFlag) {
				this.open($.extend(this.currentOptions, {target: this._getTarget(this.currentOptions.currentSet[this.currentOptions.currentIndex]) }));
				this._refreshModalState();
			}
		}
		if(e && e.preventDefault) e.preventDefault();
	},
	next: function(e) {
		if(!this._lightboxContentSwitch && this.currentOptions.currentSet.length) {
			this.cycleFlag = false;
			if(this.currentOptions.currentIndex < this.currentOptions.currentSet.length-1) {
				this.currentOptions.currentIndex++;
				this.cycleFlag = true;
			} else if(this.currentOptions.cycleRotation){
				this.currentOptions.currentIndex = 0;
				this.cycleFlag = true;
			}
			if(this.cycleFlag) {
				this.open($.extend(this.currentOptions, {target: this._getTarget(this.currentOptions.currentSet[this.currentOptions.currentIndex]) }));
				this._refreshModalState();
			}
		}
		if(e && e.preventDefault) e.preventDefault();
	},
	close: function(e) {
		// before close callback
		if(e && e.preventDefault) e.preventDefault();
		if(typeof this.currentOptions.onBeforeClose === 'function') {
			if(this.currentOptions.onBeforeClose() === false) return;
		}
		
		// lightbox close animation
		this._lightboxAnimating = true;
		this.showTransitions[this.currentOptions.transitionOut].hide(this,function(){
			this._restoreContent(function(){
				this._lightboxAnimating = false;
				this._lightboxShown = false;
				this._detachElements();
				
				// callback after closing lightbox
				if(typeof this.currentOptions.onAfterClose === 'function') {
					this.currentOptions.onAfterClose();
				}
				
				// callback by arguments
				if(typeof e === 'function') {
					e();
				}
			});
		});
	},
	open: function(opt) {
		if(!this._lightboxAnimating) {
			// preprocess options
			opt = this._preprocessOptions(opt);
			
			// before show callback (cancel if return false)
			if(typeof opt.onBeforeShow === 'function') {
				if(opt.onBeforeShow() === false) return;
			}
			// show lightbox
			if(this.lightboxContentActive) {
				this._freezeLightbox();
				this._restoreContent(function(){
					this.switchContent(opt);
				});
			} else {
				this.switchContent(opt);
			}
		}
	},
	openLink: function(link, elemOptions, switching) {
		elemOptions = elemOptions || {};
		var groupAttribute = elemOptions.groupAttribute || this.defaultOptions.groupAttribute;
		var groupElements = link.attr(groupAttribute) ? $('['+groupAttribute+'="'+link.attr(groupAttribute)+'"]') : $();
		this.open($.extend(elemOptions, {target:link.attr('href'), targetOpener:link, currentSet:groupElements, currentIndex: groupElements.index(link)}));
	}
}.init();

// jquery public methods
$.jmodalBox = {};
for(var p in jmodalBox) {
	if(jmodalBox.hasOwnProperty(p) && typeof jmodalBox[p] === 'function' && p.charAt(0) != '_') {
		(function(p){
			$.jmodalBox[p] = function() {
				return jmodalBox[p].apply(jmodalBox,arguments);
			}
		}(p));
	}
}

// jquery plugin interface
$.fn.jmodalBox = function(opts){
	jmodalBox._initOpeners(this,opts);
	return this;
}

}(this,jQuery));


// transition effect - fade
$.jmodalBox.addShowTransition({
	name:'fade',
	show: function(instance, callback) {
		instance.overlay.fadeIn(instance.currentOptions.animSpeed,function(){
			instance.modal.hide().fadeIn(instance.currentOptions.animSpeed, function(){
				instance._makeCallback(callback);
			});
		});
	},
	hide: function(instance, callback) {
		instance.modal.fadeOut(instance.currentOptions.animSpeed,function(){
			instance.overlay.fadeOut(instance.currentOptions.animSpeed, function(){
				instance._makeCallback(callback);
			});
		});
	}
});

// transition effect - slide from top
$.jmodalBox.addShowTransition({
	name:'slide',
	show: function(instance, callback) {
		instance.overlay.show().css({marginLeft:-instance.win.width()});
		instance.overlay.animate({marginLeft:0},{duration:instance.currentOptions.animSpeed,complete:function(){
			instance.modal.css({marginTop:-instance.dimensions.modalTop-instance.dimensions.modalHeight,display:'block'}).animate({marginTop:0},{duration:instance.currentOptions.animSpeed,complete:function(){
				instance._makeCallback(callback);
			}});
		}});
	},
	hide: function(instance, callback) {
		instance.modal.animate({marginLeft:-instance.dimensions.modalLeft-instance.dimensions.modalWidth},{duration:instance.currentOptions.animSpeed,complete:function(){
			instance.modal.hide().css({marginLeft:''});
			instance.overlay.animate({marginTop:-instance.overlay.height()},{duration:instance.currentOptions.animSpeed,complete:function(){
				instance.overlay.hide().css({marginTop:'',marginLeft:''});
				instance._makeCallback(callback);
			}});
		}});
	}
});

// transition effect - elastic
$.jmodalBox.addShowTransition({
	name:'elastic',
	show: function(instance, callback) {
		var opener = instance.currentOptions.targetOpener;
		var openerOffset = opener.offset();
		instance.modal.css({top: openerOffset.top, left: openerOffset.left}).show();
		instance.modalContent.css({width:opener.outerWidth(), height: opener.outerHeight()});
		
		// if image player set image width
		if(instance.currentOptions.player === 'image' && instance.tmpPlayer) {
			instance.tmpPlayer.css({width:'100%'});
		}
		
		// animate modal box and content
		instance.modal.animate({top: instance.dimensions.modalTop, left: instance.dimensions.modalLeft}, {duration:instance.currentOptions.animSpeed, easing:instance.currentOptions.easingIn });
		instance.modalContent.animate({width: instance.dimensions.contentWidth, height: instance.dimensions.contentHeight}, {duration:instance.currentOptions.animSpeed, easing:instance.currentOptions.easingIn, complete: function(){
			instance.overlay.show();
			instance._makeCallback(callback);
		}});
	},
	hide: function(instance, callback) {
		// animate modal box and content
		var opener = instance.currentOptions.targetOpener;
		var openerOffset = opener.offset();

		instance.overlay.hide()
		instance.modal.animate({top: openerOffset.top, left: openerOffset.left}, {duration:instance.currentOptions.animSpeed, easing: instance.currentOptions.easingOut });
		instance.modalContent.animate({width:opener.outerWidth(), height: opener.outerHeight()}, {duration:instance.currentOptions.animSpeed, easing: instance.currentOptions.easingOut, complete:function(){
			instance.modal.hide();
			instance._makeCallback(callback);
		}});
	}
});

// twitter helper module
twitterHelper = {
	uid: 0,
	funcPrefix: 'activeFunc',
	loadTweets: function(account, count, callback) {
		var rand = ++twitterHelper.uid;
		var callbackFunc = 'twitterHelper.'+twitterHelper.funcPrefix+rand;
		var apiURL = 'http://www.twitter.com/statuses/user_timeline/'+account+'.json?include_rts=true&callback='+callbackFunc+'&count='+count;
		twitterHelper[twitterHelper.funcPrefix+rand] = function() {
			delete twitterHelper[twitterHelper.funcPrefix+rand];
			callback.apply(twitterHelper, arguments);
		}
		twitterHelper.attachJS(apiURL);
	},
	attachJS: function(src, code) {
		var s = document.createElement('script');
		s.setAttribute('type','text/javascript');
		if(!code) s.setAttribute('src',src);
		else s.innerHTML = code;
		document.getElementsByTagName('head')[0].appendChild(s);
	},
	relativeTime: function(time_value) {
		var values = time_value.split(" ");
		time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		var parsed_date = Date.parse(time_value);
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		delta = delta + (relative_to.getTimezoneOffset() * 60);
		if (delta < 60) {
			return 'less than a minute ago';
		} else if(delta < 120) {
			return 'about a minute ago';
		} else if(delta < (45*60)) {
			return (parseInt(delta / 60)).toString() + ' minutes ago';
		} else if(delta < (90*60)) {
			return 'about an hour ago';
		} else if(delta < (24*60*60)) {
			return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
		} else if(delta < (48*60*60)) {
			return '1 day ago';
		} else {
			return (parseInt(delta / 86400)).toString() + ' days ago';
		}
	},
	parseURL: function(s) {
		return s.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
			return url.link(url);
		});
	},
	parseUsername: function(s) {
		return s.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
			var username = u.replace("@","")
			return u.link("http://twitter.com/"+username);
		});
	},
	parseHashtag: function(s) {
		return s.replace(/[#]+[A-Za-z0-9-_]+/, function(t) {
			var tag = t.replace("#","%23")
			return t.link("http://search.twitter.com/search?q="+tag);
		});
	},
	parseText: function(text) {
		return twitterHelper.parseHashtag(twitterHelper.parseUsername(twitterHelper.parseURL(text)));
	}
};

// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
	var _options = jQuery.extend({
		slideElements:'div.frame > ul > li',
		pagerGener: true,
		pagerHold: 'div.switcher',
		pagerLinks:'div.switcher li',
		btnNext:'a.link-next',
		btnPrev:'a.link-prev',
		btnPlayPause:'a.play-pause',
		btnPlay:'a.play',
		btnPause:'a.pause',
		pausedClass:'paused',
		disabledClass: 'disabled',
		playClass:'playing',
		activeClass:'active',
		currentNum:false,
		allNum:false,
		startSlide:null,
		noCircle:false,
		caption:'ul.caption > li',
		pauseOnHover:false,
		autoRotation:false,
		autoHeight:false,
		onChange:false,
		switchTime:3000,
		duration:650,
		event:'click'
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _slides = jQuery(_options.slideElements, _this);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
		var _btnPause = jQuery(_options.btnPause, _this);
		var _btnPlay = jQuery(_options.btnPlay, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _pausedClass = _options.pausedClass;
		var _playClass = _options.playClass;
		var _autoHeight = _options.autoHeight;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
		var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
		var _startSlide = _options.startSlide;
		var _noCycle = _options.noCircle;
		var _onChange = _options.onChange;
		var _pagerGener = _options.pagerGener;
		var _pagerHold = jQuery(_options.pagerHold,_this);
		var _caption = jQuery(_options.caption,_this);
		var _paging = '';
		if(_pagerGener){
			for(var i=0; i< _slides.length; i++){
				_paging += '<li><a href="#">'+(i+1)+'</a></li>';
			}
			_pagerHold.html('<ul>'+_paging+'</ul>');
		}
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		// gallery init
		var _hover = false;
		var _prevIndex = 0;
		var _currentIndex = 0;
		var _slideCount = _slides.length;
		var _timer;
		if(_slideCount < 2) return;

		_prevIndex = _slides.index(_slides.filter('.'+_activeClass));
		if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
		else _currentIndex = _prevIndex;
		if(_startSlide != null) {
			if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
			else _prevIndex = _currentIndex = parseInt(_startSlide);
		}
		_slides.hide().eq(_currentIndex).show();
		_caption.hide().eq(_currentIndex).show();
		if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
		else _this.removeClass(_playClass).addClass(_pausedClass);

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				nextSlide();
				return false;
			});
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentIndex != _ind) {
						_prevIndex = _currentIndex;
						_currentIndex = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// play pause section
		if(_btnPlayPause.length) {
			_btnPlayPause.bind(_controlEvent,function(){
				if(_this.hasClass(_pausedClass)) {
					_this.removeClass(_pausedClass).addClass(_playClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_autoRotation = false;
					if(_timer) clearTimeout(_timer);
					_this.removeClass(_playClass).addClass(_pausedClass);
				}
				return false;
			});
		}
		if(_btnPlay.length) {
			_btnPlay.bind(_controlEvent,function(){
				_this.removeClass(_pausedClass).addClass(_playClass);
				_autoRotation = true;
				autoSlide();
				return false;
			});
		}
		if(_btnPause.length) {
			_btnPause.bind(_controlEvent,function(){
				_autoRotation = false;
				if(_timer) clearTimeout(_timer);
				_this.removeClass(_playClass).addClass(_pausedClass);
				return false;
			});
		}
		// gallery animation
		function prevSlide() {
			_prevIndex = _currentIndex;
			if(_currentIndex > 0) _currentIndex--;
			else {
				if(_noCycle) return;
				else _currentIndex = _slideCount-1;
			}
			switchSlide();
		}
		function nextSlide() {
			_prevIndex = _currentIndex;
			if(_currentIndex < _slideCount-1) _currentIndex++;
			else {
				if(_noCycle) return;
				else _currentIndex = 0;
			}
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
			if(_currentNum) _currentNum.text(_currentIndex+1);
			if(_allNum) _allNum.text(_slideCount);
			_slides.eq(_prevIndex).removeClass(_activeClass);
			_slides.eq(_currentIndex).addClass(_activeClass);
			if(_noCycle) {
				if(_btnPrev.length) {
					if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
					else _btnPrev.removeClass(_disabledClass);
				}
				if(_btnNext.length) {
					if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
					else _btnNext.removeClass(_disabledClass);
				}
			}
			if(typeof _onChange === 'function') {
				_onChange(_this, _currentIndex);
			}
		}
		function switchSlide() {
			_slides.eq(_prevIndex).stop().animate({opacity:0},{duration: _duration, queue: false,complete:function(){
				jQuery(this).css({display:'none'});
			}})
			_slides.eq(_currentIndex).stop().css({display:'block',opacity:0}).animate({opacity:1},{duration: _duration, queue: false,complete:function(){
				jQuery(this).css({opacity:''});
			}})
			_caption.eq(_prevIndex).fadeOut();
			_caption.eq(_currentIndex).fadeIn();
			if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		refreshStatus();
		autoSlide();
	});
};

// scrolling gallery plugin
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: '>div.frame',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'div.switcher li',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		activeClass:'active',
		disabledClass:'disabled',
		generatePagination:'div.switcher',
		curNum:'em.scur-num',
		allNum:'em.sall-num',
		circleSlide:true,
		pauseClass:'gallery-paused',
		pauseButton:'none',
		pauseOnHover:true,
		autoRotation:false,
		stopAfterClick:false,
		switchTime:5000,
		duration:650,
		easing:'swing',
		event:'click',
		afterInit:false,
		vertical:false,
		step:false
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _sliderHolder = jQuery(_options.sliderHolder, _this);
		var _slider = jQuery(_options.slider, _sliderHolder);
		var _slides = jQuery(_options.slides, _slider);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _generatePagination = jQuery(_options.generatePagination, _this);
		var _curNum = jQuery(_options.curNum, _this);
		var _allNum = jQuery(_options.allNum, _this);
		var _pauseButton = jQuery(_options.pauseButton, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _pauseClass = _options.pauseClass;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _easing = _options.easing;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _step = _options.step;
		var _vertical = _options.vertical;
		var _circleSlide = _options.circleSlide;
		var _stopAfterClick = _options.stopAfterClick;
		var _afterInit = _options.afterInit;

		// gallery init
		if(!_slides.length) return;
		var _currentStep = 0;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;

		_slides.each(function(){
			_sumWidth+=jQuery(this).outerWidth(true);
			_sumHeight+=jQuery(this).outerHeight(true);
		});

		// calculate gallery offset
		function recalcOffsets() {
			if(_vertical) {
				if(_step) {
					_stepHeight = _slides.eq(_currentStep).outerHeight(true);
					_stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
					_offset = -_stepHeight*_currentStep;
				} else {
					_stepHeight = _sliderHolder.height();
					_stepCount = Math.ceil(_sumHeight/_stepHeight);
					_offset = -_stepHeight*_currentStep;
					if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
				}
			} else {
				if(_step) {
					_stepWidth = _slides.eq(_currentStep).outerWidth(true)*_step;
					_stepCount = Math.ceil((_sumWidth-_sliderHolder.width())/_stepWidth)+1;
					_offset = -_stepWidth*_currentStep;
					if(_offset < _sliderHolder.width()-_sumWidth) _offset = _sliderHolder.width()-_sumWidth;
				} else {
					_stepWidth = _sliderHolder.width();
					_stepCount = Math.ceil(_sumWidth/_stepWidth);
					_offset = -_stepWidth*_currentStep;
					if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
				}
			}
		}

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				nextSlide();
				return false;
			});
		}
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = jQuery('<ul />');
			for(var i=0; i<_stepCount; i++) jQuery('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
			_list.appendTo(_generatePagination);
			_pagerLinks = _list.children();
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentStep != _ind) {
						if(_stopAfterClick) stopAutoSlide();
						_currentStep = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// gallery animation
		function prevSlide() {
			recalcOffsets();
			if(_currentStep > 0) _currentStep--;
			else if(_circleSlide) _currentStep = _stepCount-1;
			switchSlide();
		}
		function nextSlide() {
			recalcOffsets();
			if(_currentStep < _stepCount-1) _currentStep++;
			else if(_circleSlide) _currentStep = 0;
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
			if(!_circleSlide) {
				_btnPrev.removeClass(_disabledClass);
				_btnNext.removeClass(_disabledClass);
				if(_currentStep == 0) _btnPrev.addClass(_disabledClass);
				if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledClass);
			}
			if(_curNum.length) _curNum.text(_currentStep+1);
			if(_allNum.length) _allNum.text(_stepCount);
		}
		function switchSlide() {
			recalcOffsets();
			if(_vertical) _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
			else _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function stopAutoSlide() {
			if(_timer) clearTimeout(_timer);
			_autoRotation = false;
		}
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		recalcOffsets();
		refreshStatus();
		autoSlide();

		// pause buttton
		if(_pauseButton.length) {
			_pauseButton.click(function(){
				if(_this.hasClass(_pauseClass)) {
					_this.removeClass(_pauseClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_this.addClass(_pauseClass);
					stopAutoSlide();
				}
				return false;
			});
		}

		if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
	});
};

// content tabs module
ContentTabs = {
	options: {
		classOnParent: true,
		hiddenClass: 'tab-hidden',
		visibleClass: 'tab-active',
		activeClass: 'active',
		tabsets: 'ul.tabset',
		tablinks: 'a.tab',
		event: 'click'
	},
	init: function(){
		this.createStyleSheet();
		this.getTabsets();
		return this;
	},
	createStyleSheet: function() {
		this.tabStyleSheet = document.createElement('style');
		this.tabStyleSheet.setAttribute('type', 'text/css');
		this.tabStyleRule = '.'+this.options.hiddenClass;
		this.tabStyleRule += '{position:absolute !important;left:-9999px !important;top:-9999px !important;display:block !important}';
		document.getElementsByTagName('head')[0].appendChild(this.tabStyleSheet);
		if (this.tabStyleSheet.styleSheet) {
			this.tabStyleSheet.styleSheet.cssText = this.tabStyleRule;
		} else {
			this.tabStyleSheet.appendChild(document.createTextNode(this.tabStyleRule));
		}
	},
	getTabsets: function() {
		this.tabsets = this.queryElements(this.options.tabsets);
		for(var i = 0; i < this.tabsets.length; i++) {
			this.initTabset(this.tabsets[i]);
		}
	},
	initTabset: function(tabset) {
		var tabLinks = this.queryElements(this.options.tablinks, tabset), instance = this;
		for(var i = 0; i < tabLinks.length; i++) {
			tabLinks[i]['on'+this.options.event] = function(){
				instance.switchTab(this, tabLinks);
				return false;
			}
			if(this.hasClass(this.options.classOnParent ? tabLinks[i].parentNode : tabLinks[i], this.options.activeClass)) {
				this.switchTab(tabLinks[i], tabLinks);
			}
		}
	},
	switchTab: function(link, set) {
		for(var i = 0; i < set.length; i++) {
			var curLink = set[i];
			var curTab = document.getElementById(curLink.href.substr(curLink.href.indexOf('#')+1));
			if(curLink === link) {
				this.addClass(this.options.classOnParent ? curLink.parentNode : curLink, this.options.activeClass);
				this.addClass(curTab,this.options.visibleClass);
				this.removeClass(curTab,this.options.hiddenClass);
			} else {
				this.removeClass(this.options.classOnParent ? curLink.parentNode : curLink, this.options.activeClass);
				this.removeClass(curTab,this.options.visibleClass);
				this.addClass(curTab,this.options.hiddenClass);
			}
		}
	},
	queryElements: function(selector, holder) {
		var box = holder || document;
		if(box.querySelectorAll) {
			return box.querySelectorAll(selector);
		} else {
			var res = [], selectorData = selector.split('.');
			var tagName = selectorData[0];
			var set = box.getElementsByTagName(tagName);
			if(selectorData.length > 1) {
				for(var i = 0; i < set.length; i++) {
					if(this.hasClass(set[i], selectorData[1])) res.push(set[i]);
				}
				return res;
			} else {
				return set;
			}
		}
	},
	hasClass: function (obj,cname) {
		return (obj.className ? obj.className.match(new RegExp('(\\s|^)'+cname+'(\\s|$)')) : false);
	},
	addClass: function (obj,cname) {
		if (!this.hasClass(obj,cname)) obj.className += " "+cname;
	},
	removeClass: function (obj,cname) {
		if (this.hasClass(obj,cname)) obj.className=obj.className.replace(new RegExp('(\\s|^)'+cname+'(\\s|$)'),' ');
	}
};

function initAutoScalingNav(o){
	if (!o.menuId) o.menuId = "nav";
	if (!o.tag) o.tag = "a";
	if (!o.spacing) o.spacing = 0;
	if (!o.constant) o.constant = 0;
	if (!o.minPaddings) o.minPaddings = 0;
	if (!o.liHovering) o.liHovering = false;
	if (!o.sideClasses) o.sideClasses = false;
	var nav = document.getElementById(o.menuId);
	if(nav)
	{
		nav.className += " scaling-active";
		var lis = nav.getElementsByTagName("li");
		var asFl = [];
		var lisFl = [];
		for (var i=0, j=0; i<lis.length; i++)
		{
			if(lis[i].parentNode == nav)
			{
				var t = lis[i].getElementsByTagName(o.tag).item(0);
				asFl.push(t);
				asFl[j++].width = t.offsetWidth;
				lisFl.push(lis[i]);
			}
			if(o.liHovering)
			{
				lis[i].onmouseover = function()
				{
					this.className += " hover";
				}
				lis[i].onmouseout = function()
				{
					this.className = this.className.replace("hover", "");
				}
			}
		}
		var menuWidth = nav.clientWidth - asFl.length*o.spacing - o.constant;
		if(getItemsWidth(asFl) < menuWidth)
		{
			for (var i=0; getItemsWidth(asFl) < menuWidth; i++)
			{
				asFl[i].width++;
				if(i >= asFl.length-1) i=-1;
			}
			for (var i=0; i<asFl.length; i++)
			{
				asFl[i].style.width = asFl[i].width + "px";
			}
		}
		else if(o.minPaddings > 0)
		{
			for (var i=0; i<asFl.length; i++)
			{
				asFl[i].style.width = asFl[i].width + o.minPaddings*2 + "px";
			}
		}
		if(o.sideClasses)
		{
			lisFl[0].className += " first-child";
			lisFl[0].getElementsByTagName("a").item(0).className += " first-child-a";
			lisFl[lisFl.length-1].className += " last-child";
			lisFl[lisFl.length-1].getElementsByTagName("a").item(0).className += " last-child-a";
		}
	}
	function getItemsWidth(a)
	{
		var w = 0;
		for(var q=0; q<a.length; q++)
		{
			w += a[q].width;
		}
		return w;
	}
};

// navigation accesibility module
function touchNav(options) {
	this.options = {
		mobileReg: /(ipad|iphone|ipod|android|blackberry|iemobile)/gi,
		hoverClass: 'hover',
		followLink: false,
		menuItems: 'li',
		menuOpener: 'a',
		menuDrop: 'div',
		navBlock: null
	}
	for(var p in options) {
		this.options[p] = options[p];
	}
	this.init();
}
touchNav.prototype = {
	init: function() {
		this.isMobile = (this.options.mobileReg).test(navigator.userAgent);
		if(typeof this.options.navBlock === 'string') {
			this.menu = document.getElementById(this.options.navBlock);
		} else if(typeof this.options.navBlock === 'object') {
			this.menu = this.options.navBlock;
		}
		if(this.menu) {
			this.getElements();
			this.addEvents();
		}
	},
	getElements: function() {
		this.menuItems = this.menu.getElementsByTagName(this.options.menuItems);
	},
	hideActiveDropdown: function() {
		if(this.activeParent) {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.removeClass(this.menuItems[i], this.options.hoverClass);
			}
			this.activeParent = null;
		}
	},
	getOpener: function(obj) {
		for(var i = 0; i < obj.childNodes.length; i++) {
			if(obj.childNodes[i].tagName && obj.childNodes[i].tagName.toLowerCase() == this.options.menuOpener.toLowerCase()) {
				return obj.childNodes[i];
			}
		}
		return false;
	},
	getDrop: function(obj) {
		for(var i = 0; i < obj.childNodes.length; i++) {
			if(obj.childNodes[i].tagName && obj.childNodes[i].tagName.toLowerCase() == this.options.menuDrop.toLowerCase()) {
				return obj.childNodes[i];
			}
		}
		return false;
	},
	addEvents: function() {
		// mobile event handlers
		if(this.isMobile) {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.menuItems[i].touchNav = this;
				if(this.getDrop(this.menuItems[i])) {
					this.addHandler(this.getOpener(this.menuItems[i]), 'click', this.bind(this.clickHandler,this.menuItems[i]));
				}
			}
			this.addHandler(document.body, 'click', this.bind(this.outsideHandler, this));
			this.addHandler(document.body, 'touchstart', this.bind(this.outsideHandler, this));
		}
		// desktop event handlers
		else {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.menuItems[i].touchNav = this;
				this.addHandler(this.menuItems[i], 'mouseover', this.mouseoverHandler);
				this.addHandler(this.menuItems[i], 'mouseout', this.mouseoutHandler);
			}
		}
	},
	outsideHandler: function(e) {
		var childFlag = false;
		if(this.activeParent) {
			this.outsideTarget = e.target || e.currentTarget || e.srcElement;
			while (this.outsideTarget.parentNode) {
				if(this.activeParent == this.outsideTarget) {
					childFlag = true;
					break;
				}
				this.outsideTarget = this.outsideTarget.parentNode;
			}
			if(!childFlag) {
				this.hideActiveDropdown();
			}
		}
	},
	mouseoverHandler: function() {
		this.touchNav.addClass(this, this.touchNav.options.hoverClass);
	},
	mouseoutHandler: function() {
		this.touchNav.removeClass(this, this.touchNav.options.hoverClass);
	},
	clickHandler: function(e) {
		// get current dropdown
		var tNav = this.touchNav;
		tNav.currentElement = e.currentTarget || e.srcElement;
		tNav.currentParent = tNav.currentElement.parentNode;

		// hide previous drop (if exists)
		if(tNav.activeParent && !tNav.isParent(tNav.activeParent, tNav.currentParent) && tNav.currentParent != tNav.activeParent) {
			tNav.hideActiveDropdown();
		}

		// handle current drop
		if(tNav.hasClass(tNav.currentParent, tNav.options.hoverClass)) {
			tNav.removeClass(tNav.currentParent, tNav.options.hoverClass);
			if(tNav.options.followLink) {
				window.location.href = tNav.currentElement.href;
			}
		} else {
			tNav.addClass(tNav.currentParent, tNav.options.hoverClass);
			tNav.activeParent = tNav.currentParent;
			return tNav.preventEvent(e);
		}
	},
	preventEvent: function(e) {
		if(!e) e = window.event;
		if(e.preventDefault) e.preventDefault();
		if(e.stopPropagation) e.stopPropagation();
		e.cancelBubble = true;
		return false;
	},
	isParent: function(parent, child) {
		while(child.parentNode) {
			if(child.parentNode == parent) {
				return true;
			}
			child = child.parentNode;
		}
		return false;
	},
	addHandler: function(object, event, handler) {
		if (typeof object.addEventListener != 'undefined') object.addEventListener(event, this.bind(handler,object), false);
		else if (typeof object.attachEvent != 'undefined') object.attachEvent('on' + event, this.bind(handler,object));
	},
	removeHandler: function(object, event, handler) {
		if (typeof object.removeEventListener != 'undefined') object.removeEventListener(event, handler, false);
		else if (typeof object.detachEvent != 'undefined') object.detachEvent('on' + event, handler);
	},
	hasClass: function(obj,cname) {
		return (obj.className ? obj.className.match(new RegExp('(\\s|^)'+cname+'(\\s|$)')) : false);
	},
	addClass: function(obj,cname) {
		if (!this.hasClass(obj,cname)) obj.className += " "+cname;
	},
	removeClass: function(obj,cname) {
		if (this.hasClass(obj,cname)) obj.className=obj.className.replace(new RegExp('(\\s|^)'+cname+'(\\s|$)'),' ');
	},
	bind: function(func, scope){
		return function() {
			return func.apply(scope, arguments);
		}
	}
};

// mobile browsers detect
browserPlatform = {
	platforms: [
		{ uaString:['symbian','midp'], cssFile:'symbian.css' }, // Symbian phones
		{ uaString:['opera','mobi'], cssFile:'opera.css' }, // Opera Mobile
		{ uaString:['msie','ppc'], cssFile:'ieppc.css' }, // IE Mobile <6
		{ uaString:'iemobile', cssFile:'iemobile.css' }, // IE Mobile 6+
		{ uaString:'webos', cssFile:'webos.css' }, // Palm WebOS
		{ uaString:'Android', cssFile:'android.css' }, // Android
		{ uaString:['BlackBerry','/6.0','mobi'], cssFile:'blackberry6.css' },	// Blackberry 6
		{ uaString:['BlackBerry','/7.0','mobi'], cssFile:'blackberry7.css' },	// Blackberry 7+
		{ uaString:'ipad', cssFile:'ipad.css', miscHead:'<meta name="viewport" content="width=device-width" />' }, // iPad
		{ uaString:['safari','mobi'], cssFile:'safari.css', miscHead:'<meta name="viewport" content="width=device-width" />' } // iPhone and other webkit browsers
	],
	options: {
		cssPath:'css/',
		mobileCSS:'allmobile.css'
	},
	init:function(){
		this.checkMobile();
		this.parsePlatforms();
		return this;
	},
	checkMobile: function() {
		if(this.uaMatch('mobi') || this.uaMatch('midp') || this.uaMatch('ppc') || this.uaMatch('webos')) {
			this.attachStyles({cssFile:this.options.mobileCSS});
		}
	},
	parsePlatforms: function() {
		for(var i = 0; i < this.platforms.length; i++) {
			if(typeof this.platforms[i].uaString === 'string') {
				if(this.uaMatch(this.platforms[i].uaString)) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			} else {
				for(var j = 0, allMatch = true; j < this.platforms[i].uaString.length; j++) {
					if(!this.uaMatch(this.platforms[i].uaString[j])) {
						allMatch = false;
					}
				}
				if(allMatch) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			}
		}
	},
	attachStyles: function(platform) {
		var head = document.getElementsByTagName('head')[0], fragment;
		var cssText = '<link rel="stylesheet" href="' + this.options.cssPath + platform.cssFile + '" type="text/css"/>';
		var miscText = platform.miscHead;
		if(platform.cssFile) {
			if(document.body) {
				fragment = document.createElement('div');
				fragment.innerHTML = cssText;
				head.appendChild(fragment.childNodes[0]);
			} else {
				document.write(cssText);
			}
		}
		if(platform.miscHead) {
			if(document.body) {
				fragment = document.createElement('div');
				fragment.innerHTML = miscText;
				head.appendChild(fragment.childNodes[0]);
			} else {
				document.write(miscText);
			}
		}
	},
	uaMatch:function(str) {
		if(!this.ua) {
			this.ua = navigator.userAgent.toLowerCase();
		}
		return this.ua.indexOf(str.toLowerCase()) != -1;
	}
}.init();

/* IE6 Hover fix module */
var ieHover = {
	lazyMode: true,
	init: function(){
		this.setDefaults();
		return this;
	},
	setDefaults: function() {
		this.fixActive = /MSIE 6/.test(navigator.userAgent);
		if(this.fixActive) {
			this.hoverEvents = []; this.hoverQueue = [];
			this.activators = {
				onhover:{on:'onmouseenter', off:'onmouseleave'},
				onactive:{on:'onmousedown', off:'onmouseup'}
			}
			window.attachEvent('onload', this.bind(this.domReady,this));
			window.attachEvent('onunload', this.bind(this.unhookHoverEvents,this));
		}
	},
	domReady: function() {
		this.pageReady = true;
		if(this.lazyMode) {
			this.processStylesheets();
		}
		if(this.hoverQueue.length) {
			for(var i = 0; i < this.hoverQueue.length; i++) {
				this.doFix(this.hoverQueue[i].s,this.hoverQueue[i].c);
			}
		}
	},
	processStylesheets: function() {
		var sheets = document.styleSheets, len = sheets.length;
		for(var i = 0; i < len; i++) { this.parseStylesheet(sheets[i]); }
	},
	parseStylesheet: function(sheet) {
		if(sheet.imports) {
			try {
				var imports = sheet.imports, l = imports.length;
				for(var i=0; i<l; i++) this.parseStylesheet(sheet.imports[i]);
			} catch(e){}
		}
		try {
			var rules = (this.currentSheet = sheet).rules, l = rules.length;
			for(var j=0; j<l; j++) this.parseCSSRule(rules[j]);
		} catch(e){}
	},
	parseCSSRule: function(rule) {
		var select = rule.selectorText, style = rule.style.cssText;
		if(!/(^|\s)(([^a]([^ ]+)?)|(a([^#.][^ ]+)+)):(hover|active)/i.test(select) || !style) return;
		var pseudo = select.replace(/[^:]+:([a-z-]+).*/i, 'on$1');
		var newSelect = select.replace(/(\.([a-z0-9_-]+):[a-z]+)|(:[a-z]+)/gi, '.$2' + pseudo);
		var className = (/\.([a-z0-9_-]*on(hover|active))/i).exec(newSelect)[1];
		var affected = select.replace(/:(hover|active).*$/, '');
		var elements = this.parseSelector(affected);
		if(!elements.length) return;
		this.currentSheet.addRule(newSelect, style);
		for(var i=0; i < elements.length; i++) {
			this.addHoverElement(elements[i], className, this.activators[pseudo]);
		}
	},
	fix: function(selector, className) {
		if(this.fixActive) {
			if(this.pageReady) {
				this.doFix(selector,className)
			} else {
				this.hoverQueue.push({s:selector,c:className});
			}
		}
	},
	doFix: function(selector, className) {
		if(this.fixActive && typeof selector === 'string') {
			var elements = this.parseSelector(selector);
			for(var i=0; i < elements.length; i++) {
				this.addHoverElement(elements[i], className || 'hover', this.activators['onhover']);
			}
		}
	},
	addHoverElement: function(node, className, events) {
		if(!node.hovers) node.hovers = {};
		if(node.hovers[className]) return;
		node.hovers[className] = true;
		this.hookHoverEvent(node, events.on, function() { node.className += ' ' + className; });
		this.hookHoverEvent(node, events.off, function() { node.className = node.className.replace(new RegExp('\\s+'+className, 'g'),''); });
	},
	hookHoverEvent: function(node, type, handler) {
		node.attachEvent(type, handler);
		this.hoverEvents[this.hoverEvents.length] = {
			node:node, type:type, handler:handler
		};
	},
	unhookHoverEvents: function() {
		for(var e,i=0; i < this.hoverEvents.length; i++) {
			e = this.hoverEvents[i];
			e.node.detachEvent(e.type, e.handler);
		}
	},
	parseSelector: (function () {
		var g = /^([^#.>`]*)(#|\.|\>|\`)(.+)$/;
		function parseSelector(a, b) {
			var c = a.split(/\s*\,\s*/);
			var d = [];
			for (var i = 0; i < c.length; i++) {
				d = d.concat(doParse(c[i], b))
			};
			return d
		};
		function doParse(a, b, c) {
			a = a.replace(" ", "`");
			var d = a.match(g);
			var e, listNodes, listSubNodes, subselector, i, limit;
			var f = [];
			if (d == null) {
				d = [a, a]
			};
			if (d[1] == "") {
				d[1] = "*"
			};
			if (c == null) {
				c = "`"
			};
			if (b == null) {
				b = document
			};
			switch (d[2]) {
			case "#":
				subselector = d[3].match(g);
				if (subselector == null) {
					subselector = [null, d[3]]
				};
				e = document.getElementById(subselector[1]);
				if (e == null || (d[1] != "*" && !matchNodeNames(e, d[1]))) {
					return f
				};
				if (subselector.length == 2) {
					f.push(e);
					return f
				};
				return doParse(subselector[3], e, subselector[2]);
			case ".":
				if (c != ">") {
					listNodes = getElementsByTagName(b, d[1])
				} else {
					listNodes = b.childNodes
				};
				for (i = 0, limit = listNodes.length; i < limit; i++) {
					e = listNodes[i];
					if (e.nodeType != 1) {
						continue
					};
					subselector = d[3].match(g);
					if (subselector != null) {
						if (e.className == null || e.className.match("(\\s|^)" + subselector[1] + "(\\s|$)") == null) {
							continue
						};
						listSubNodes = doParse(subselector[3], e, subselector[2]);
						f = f.concat(listSubNodes)
					} else if (e.className != null && e.className.match("(\\s|^)" + d[3] + "(\\s|$)") != null) {
						f.push(e)
					}
				};
				return f;
			case ">":
				if (c != ">") {
					listNodes = getElementsByTagName(b, d[1])
				} else {
					listNodes = b.childNodes
				};
				for (i = 0, limit = listNodes.length; i < limit; i++) {
					e = listNodes[i];
					if (e.nodeType != 1) {
						continue
					};
					if (!matchNodeNames(e, d[1])) {
						continue
					};
					listSubNodes = doParse(d[3], e, ">");
					f = f.concat(listSubNodes)
				};
				return f;
			case "`":
				listNodes = getElementsByTagName(b, d[1]);
				for (i = 0, limit = listNodes.length; i < limit; i++) {
					e = listNodes[i];
					listSubNodes = doParse(d[3], e, "`");
					f = f.concat(listSubNodes)
				};
				return f;
			default:
				if (c != ">") {
					listNodes = getElementsByTagName(b, d[1])
				} else {
					listNodes = b.childNodes
				};
				for (i = 0, limit = listNodes.length; i < limit; i++) {
					e = listNodes[i];
					if (e.nodeType != 1) {
						continue
					};
					if (!matchNodeNames(e, d[1])) {
						continue
					};
					f.push(e)
				};
				return f
			}
		};
		function getElementsByTagName(a, b) {
			if (b == "*" && a.all != null) {
				return a.all
			};
			return a.getElementsByTagName(b)
		};
		function matchNodeNames(a, b) {
			if (b == "*") {
				return true
			};
			return a.nodeName.toLowerCase().replace("html:", "") == b.toLowerCase()
		};
		return parseSelector
	}()),
	bind: function(fn, scope, args) {
		return function() {
			return fn.apply(scope, args || arguments);
		}
	}
}.init();

// png fix
var transparentImage = "images/none.gif";
function fixTrans(){
	if (typeof document.body.style.maxHeight == 'undefined'){
		var imgs = document.getElementsByTagName("img");
		for (i = 0; i < imgs.length; i++){	
			if (imgs[i].src.indexOf(transparentImage) != -1) return;
			if (imgs[i].src.indexOf(".png") != -1){
				var src = imgs[i].src;
				imgs[i].src = transparentImage;
				imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
				imgs[i].style.display = "inline-block";
			}
		}	
	}
};

/*
 * JavaScript Custom Forms 1.3.1
 */
jcf = {
	// global options
	modules: {},
	plugins: {},
	baseOptions: {
		labelActiveClass: 'jcf-label-active',
		hiddenClass:'jcf-hidden',
		focusClass:'jcf-focus',
		wrapperTag: 'div'
	},
	// replacer function
	customForms: {
		replaceAll: function(obj, opt) {
			for(var k in jcf.modules) {
				var els = jcf.lib.queryBySelector(jcf.modules[k].prototype.selector);
				for(var i = 0; i<els.length; i++) {
					if(els[i].jcf) {
						// refresh form element state
						els[i].jcf.refreshState();
					} else {
						// replace form element
						new jcf.modules[k]({
							replaces:els[i]
						});
					}
				}
			}
		}
	},
	// detect device type
	isTouchDevice: (function() {
		try {
			document.createEvent("TouchEvent");
			return true;
		} catch (e) {
			return false;
		}
	}()),
	// define base module
	setBaseModule: function(obj) {
		jcf.customControl = function(opt){
			this.options = jcf.lib.extend({}, jcf.baseOptions, this.defaultOptions, opt);
			this.init();
		}
		for(var p in obj) {
			jcf.customControl.prototype[p] = obj[p];
		}
	},
	// add module to jcf.modules
	addModule: function(obj) {
		if(obj.name){
			// create new module proto class
			jcf.modules[obj.name] = function(){
				jcf.modules[obj.name].superclass.constructor.apply(this, arguments);
			}
			jcf.lib.inherit(jcf.modules[obj.name], jcf.customControl);
			for(var p in obj) {
				jcf.modules[obj.name].prototype[p] = obj[p]
			}
			// on create module
			jcf.modules[obj.name].prototype.onCreateModule();
			// make callback for exciting modules
			for(var mod in jcf.modules) {
				if(jcf.modules[mod] != jcf.modules[obj.name]) {
					jcf.modules[mod].prototype.onModuleAdded(jcf.modules[obj.name]);
				}
			}
		}
	},
	// add plugin to jcf.plugins
	addPlugin: function(obj) {
		if(obj && obj.name) {
			jcf.plugins[obj.name] = function() {
				this.init.apply(this, arguments);
			}
			for(var p in obj) {
				jcf.plugins[obj.name].prototype[p] = obj[p];
			}
		}
	},
	// miscellaneous init
	init: function(){
		this.eventPress = this.isTouchDevice ? 'touchstart' : 'mousedown';
		this.eventMove = this.isTouchDevice ? 'touchmove' : 'mousemove';
		this.eventRelease = this.isTouchDevice ? 'touchend' : 'mouseup';
		return this;
	}
}.init();

/*
 * Custom Form Control prototype
 */
jcf.setBaseModule({
	init: function(){
		if(this.options.replaces) {
			this.realElement = this.options.replaces;
			this.replaceObject();
		}
	},
	defaultOptions: {
		// default module options (will be merged with base options)
	},
	replaceObject: function(){
		this.createWrapper();
		this.attachEvents();
		this.fixStyles();
		this.setupWrapper();
	},
	createWrapper: function(){
		this.fakeElement = document.createElement(this.options.wrapperTag);
		this.fakeElement.jcf = this.realElement.jcf = this;
		this.labelFor = jcf.lib.getLabelFor(this.realElement);
		jcf.lib.disableTextSelection(this.fakeElement);
		jcf.lib.addClass(this.realElement, jcf.baseOptions.hiddenClass);
	},
	attachEvents: function(){
		jcf.lib.event.add(this.realElement, 'focus', this.onFocus, this);
		jcf.lib.event.add(this.realElement, 'blur', this.onBlur, this);
		jcf.lib.event.add(this.fakeElement, 'click', this.onFakeClick, this);
		jcf.lib.event.add(this.fakeElement, jcf.eventPress, this.onFakePressed, this);
		jcf.lib.event.add(this.fakeElement, jcf.eventRelease, this.onFakeReleased, this);

		if(this.labelFor) {
			this.labelFor.jcf = this;
			jcf.lib.event.add(this.labelFor, 'click', this.onFakeClick, this);
			jcf.lib.event.add(this.labelFor, jcf.eventPress, this.onFakePressed, this);
			jcf.lib.event.add(this.labelFor, jcf.eventRelease, this.onFakeReleased, this);
		}
	},
	fixStyles: function() {
		// hide mobile webkit tap effect
		var tapStyle = 'rgba(255,255,255,0)';
		this.realElement.style.webkitTapHighlightColor = tapStyle; 
		this.fakeElement.style.webkitTapHighlightColor = tapStyle; 
		if(this.labelFor) {
			this.labelFor.style.webkitTapHighlightColor = tapStyle; 
		}
	},
	setupWrapper: function(){
		// implement in subclass
	},
	refreshState: function(){
		// implement in subclass
	},
	onFocus: function(){
		if(this.focused) return;
		
		// handle touch devices (pseudo focus)
		if(jcf.isTouchDevice) {
			if(jcf.focusedInstance && jcf.focusedInstance.realElement != this.realElement) {
				jcf.focusedInstance.onBlur();
				jcf.focusedInstance.realElement.blur();
			}
			jcf.focusedInstance = this;
		}
		// common handle
		this.focused = true;
		jcf.lib.addClass(this.fakeElement,this.options.focusClass);
	},
	onBlur: function(cb){
		if(!this.pressedFlag) {
			this.focused = false;
			jcf.lib.removeClass(this.fakeElement,this.options.focusClass);
		}
	},
	onFakeClick: function(){
		if(jcf.isTouchDevice) {
			this.onFocus();
		} else {
			this.realElement.focus();
		}
	},
	onFakePressed: function(e){
		this.pressedFlag = true;
	},
	onFakeReleased: function(){
		this.pressedFlag = false;
	},
	onCreateModule: function(){
		// implement in subclass
	},
	onModuleAdded: function(module) {
		// implement in subclass
	},
	onControlReady: function() {
		// implement in subclass
	}
});

/*
 * JCF Utility Library
 */
jcf.lib = {
	bind: function(func, scope){
		return function() {
			return func.apply(scope, arguments);
		}
	},
	browser: (function() {
		var ua = navigator.userAgent.toLowerCase(), res = {},
		match = /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec(ua) ||
				/(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+))?/.exec(ua) || [];
		res[match[1]] = true;
		res.version = match[2] || "0";
		res.safariMac = ua.indexOf('mac') != -1 && ua.indexOf('safari') != -1;
		return res;
	})(),
	getOffset: function (obj) {
		if (obj.getBoundingClientRect) {
			var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
			var clientLeft = document.documentElement.clientLeft || document.body.clientLeft || 0;
			var clientTop = document.documentElement.clientTop || document.body.clientTop || 0;
			return {
				top:Math.round(obj.getBoundingClientRect().top + scrollTop - clientTop),
				left:Math.round(obj.getBoundingClientRect().left + scrollLeft - clientLeft)
			}
		} else {
			var posLeft = 0, posTop = 0;
			while (obj.offsetParent) {posLeft += obj.offsetLeft; posTop += obj.offsetTop; obj = obj.offsetParent;}
			return {top:posTop,left:posLeft};
		}
	},
	getScrollTop: function() {
		return window.pageYOffset || document.documentElement.scrollTop;
	},
	getScrollLeft: function() {
		return window.pageXOffset || document.documentElement.scrollLeft;
	},
	getWindowWidth: function(){
		return document.compatMode=='CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth;
	},
	getWindowHeight: function(){
		return document.compatMode=='CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight;
	},
	getStyle: function(el, prop) {
		if (document.defaultView && document.defaultView.getComputedStyle) {
			return document.defaultView.getComputedStyle(el, null)[prop];
		} else if (el.currentStyle) {
			return el.currentStyle[prop];
		} else {
			return el.style[prop];
		}
	},
	getParent: function(obj, selector) {
		while(obj.parentNode && obj.parentNode != document.body) {
			if(obj.parentNode.tagName.toLowerCase() == selector.toLowerCase()) {
				return obj.parentNode;
			}
			obj = obj.parentNode;
		}
		return false;
	},
	isParent: function(child, parent) {
		while(child.parentNode) {
			if(child.parentNode === parent) {
				return true;
			}
			child = child.parentNode;
		}
		return false;
	},
	getLabelFor: function(object) {
		if(jcf.lib.getParent(object,'label')) {
			return object.parentNode;
		} else if(object.id) {
			return jcf.lib.queryBySelector('label[for=' + object.id + ']')[0];
		}
	},
	disableTextSelection: function(el){
		el.setAttribute('unselectable', 'on');
		el.style.MozUserSelect = 'none';
		el.style.WebkitUserSelect = 'none';
		el.style.UserSelect = 'none';
		el.onselectstart = function() {return false};
	},
	queryBySelector: function(selector, scope){
		return this.getElementsBySelector(selector, scope);
	},
	prevSibling: function(node) {
		while(node = node.previousSibling) if(node.nodeType == 1) break;
		return node;
	},
	nextSibling: function(node) {
		while(node = node.nextSibling) if(node.nodeType == 1) break;
		return node;
	},
	fireEvent: function(element,event) {
		if (document.createEventObject){
			var evt = document.createEventObject();
			return element.fireEvent('on'+event,evt)
		}
		else{
			var evt = document.createEvent('HTMLEvents');
			evt.initEvent(event, true, true );
			return !element.dispatchEvent(evt);
		}
	},
	isParent: function(p, c) {
		while(c.parentNode) {
			if(p == c) {
				return true;
			}
			c = c.parentNode;
		}
		return false;
	},
	inherit: function(Child, Parent) {
		var F = function() { }
		F.prototype = Parent.prototype
		Child.prototype = new F()
		Child.prototype.constructor = Child
		Child.superclass = Parent.prototype
	},
	extend: function(obj) {
		for(var i = 1; i < arguments.length; i++) {
			for(var p in arguments[i]) {
				if(arguments[i].hasOwnProperty(p)) {
					obj[p] = arguments[i][p];
				}
			}
		}
		return obj;
	},
	hasClass: function (obj,cname) {
		return (obj.className ? obj.className.match(new RegExp('(\\s|^)'+cname+'(\\s|$)')) : false);
	},
	addClass: function (obj,cname) {
		if (!this.hasClass(obj,cname)) obj.className += " "+cname;
	},
	removeClass: function (obj,cname) {
		if (this.hasClass(obj,cname)) obj.className=obj.className.replace(new RegExp('(\\s|^)'+cname+'(\\s|$)'),' ');
	},
	getAllClasses: function(cname, prefix, skip) {
		if(!skip) skip = '';
		if(!prefix) prefix = '';
		return cname ? cname.replace(new RegExp('(\\s|^)'+skip+'(\\s|$)'),' ').replace(/[\s]*([\S]+)+[\s]*/gi,prefix+"$1 ") : '';
	},
	getElementsBySelector: function(selector, scope) {
		if(typeof document.querySelectorAll === 'function') {
			return (scope || document).querySelectorAll(selector);
		}
		var tokens = selector.split(' ');
		var currentContext = [scope || document.body];
		for (var i = 0; i < tokens.length; i++) {
			token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
			if (token.indexOf('#') > -1) {
				var bits = token.split('#'), tagName = bits[0], id = bits[1];
				var element = document.getElementById(id);
				if (tagName && element.nodeName.toLowerCase() != tagName) {
					return [];
				}
				currentContext = [element];
				continue;
			}
			if (token.indexOf('.') > -1) {
				var bits = token.split('.'), tagName = bits[0] || '*', className = bits[1], found = [], foundCount = 0;
				for (var h = 0; h < currentContext.length; h++) {
					var elements;
					if (tagName == '*') {
						elements = currentContext[h].getElementsByTagName('*');
					} else {
						elements = currentContext[h].getElementsByTagName(tagName);
					}
					for (var j = 0; j < elements.length; j++) {
						found[foundCount++] = elements[j];
					}
				}
				currentContext = [];
				var currentContextIndex = 0;
				for (var k = 0; k < found.length; k++) {
					if (found[k].className && found[k].className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'))) {
						currentContext[currentContextIndex++] = found[k];
					}
				}
				continue;
			}
			if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
				var tagName = RegExp.$1 || '*', attrName = RegExp.$2, attrOperator = RegExp.$3, attrValue = RegExp.$4;
				if(attrName.toLowerCase() == 'for' && this.browser.msie && this.browser.version < 8) {
					attrName = 'htmlFor';
				}
				var found = [], foundCount = 0;
				for (var h = 0; h < currentContext.length; h++) {
					var elements;
					if (tagName == '*') {
						elements = currentContext[h].getElementsByTagName('*');
					} else {
						elements = currentContext[h].getElementsByTagName(tagName);
					}
					for (var j = 0; j < elements.length; j++) {
						found[foundCount++] = elements[j];
					}
				}
				currentContext = [];
				var currentContextIndex = 0, checkFunction;
				switch (attrOperator) {
					case '=': checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue) }; break;
					case '~': checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('(\\s|^)'+attrValue+'(\\s|$)'))) }; break;
					case '|': checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))) }; break;
					case '^': checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0) }; break;
					case '$': checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length) }; break;
					case '*': checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1) }; break;
					default : checkFunction = function(e) { return e.getAttribute(attrName) };
				}
				currentContext = [];
				var currentContextIndex = 0;
				for (var k = 0; k < found.length; k++) {
					if (checkFunction(found[k])) {
						currentContext[currentContextIndex++] = found[k];
					}
				}
				continue;
			}
			tagName = token;
			var found = [], foundCount = 0;
			for (var h = 0; h < currentContext.length; h++) {
				var elements = currentContext[h].getElementsByTagName(tagName);
				for (var j = 0; j < elements.length; j++) {
					found[foundCount++] = elements[j];
				}
			}
			currentContext = found;
		}
		return currentContext;
	},
	domReady: function (handler){
		var called = false
		function ready() {
			if (called) return;
			called = true;
			handler();
		}
		if (document.addEventListener) {
			document.addEventListener("DOMContentLoaded", ready, false);
		} else if (document.attachEvent) {
			if (document.documentElement.doScroll && window == window.top) {
				function tryScroll(){
					if (called) return
					if (!document.body) return
					try {
						document.documentElement.doScroll("left")
						ready()
					} catch(e) {
						setTimeout(tryScroll, 0)
					}
				}
				tryScroll()
			}
			document.attachEvent("onreadystatechange", function(){
				if (document.readyState === "complete") {
					ready()
				}
			})
		}
		if (window.addEventListener) window.addEventListener('load', ready, false)
		else if (window.attachEvent) window.attachEvent('onload', ready)
	},
	event: (function(){
		var guid = 0;
		function fixEvent(e) {
			e = e || window.event;
			if (e.isFixed) {
				return e;
			}
			e.isFixed = true; 
			e.preventDefault = e.preventDefault || function(){this.returnValue = false}
			e.stopPropagation = e.stopPropagaton || function(){this.cancelBubble = true}
			if (!e.target) {
				e.target = e.srcElement
			}
			if (!e.relatedTarget && e.fromElement) {
				e.relatedTarget = e.fromElement == e.target ? e.toElement : e.fromElement;
			}
			if (e.pageX == null && e.clientX != null) {
				var html = document.documentElement, body = document.body;
				e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0);
				e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0);
			}
			if (!e.which && e.button) {
				e.which = e.button & 1 ? 1 : (e.button & 2 ? 3 : (e.button & 4 ? 2 : 0));
			}
			if(e.type === "DOMMouseScroll" || e.type === 'mousewheel') {
				e.mWheelDelta = 0;
				if (e.wheelDelta) {
					e.mWheelDelta = e.wheelDelta/120;
				} else if (e.detail) {
					e.mWheelDelta = -e.detail/3;
				}
			}
			return e;
		}
		function commonHandle(event, customScope) {
			event = fixEvent(event);
			var handlers = this.events[event.type];
			for (var g in handlers) {
				var handler = handlers[g];
				var ret = handler.call(customScope || this, event);
				if (ret === false) {
					event.preventDefault()
					event.stopPropagation()
				}
			}
		}
		var publicAPI = {
			add: function(elem, type, handler, forcedScope) {
				if (elem.setInterval && (elem != window && !elem.frameElement)) {
					elem = window;
				}
				if (!handler.guid) {
					handler.guid = ++guid;
				}
				if (!elem.events) {
					elem.events = {};
					elem.handle = function(event) {
						return commonHandle.call(elem, event);
					}
				}
				if (!elem.events[type]) {
					elem.events[type] = {};
					if (elem.addEventListener) elem.addEventListener(type, elem.handle, false);
					else if (elem.attachEvent) elem.attachEvent("on" + type, elem.handle);
					if(type === 'mousewheel') {
						publicAPI.add(elem, 'DOMMouseScroll', handler, forcedScope);
					}
				}
				var fakeHandler = jcf.lib.bind(handler, forcedScope);
				fakeHandler.guid = handler.guid;
				elem.events[type][handler.guid] = forcedScope ? fakeHandler : handler;
			},
			remove: function(elem, type, handler) {
				var handlers = elem.events && elem.events[type];
				if (!handlers) return;
				delete handlers[handler.guid];
				for(var any in handlers) return;
				if (elem.removeEventListener) elem.removeEventListener(type, elem.handle, false);
				else if (elem.detachEvent) elem.detachEvent("on" + type, elem.handle);
				delete elem.events[type];
				for (var any in elem.events) return;
				try {
					delete elem.handle;
					delete elem.events;
				} catch(e) {
					if(elem.removeAttribute) {
						elem.removeAttribute("handle");
						elem.removeAttribute("events");
					}
				}
				if(type === 'mousewheel') {
					publicAPI.remove(elem, 'DOMMouseScroll', handler);
				}
			}
		}
		return publicAPI;
	}())
}

// custom select module
jcf.addModule({
	name:'select',
	selector:'select',
	defaultOptions: {
		handleDropPosition: true,
		wrapperClass:'select-area',
		focusClass:'select-focus',
		dropActiveClass:'select-active',
		selectedClass:'item-selected',
		disabledClass:'select-disabled',
		valueSelector:'span.center',
		optGroupClass:'optgroup',
		openerSelector:'a.select-opener',
		selectStructure:'<span class="left"></span><span class="center"></span><a class="select-opener"></a>',
		selectPrefixClass:'select-',
		dropMaxHeight: 200,
		dropFlippedClass: 'select-options-flipped',
		dropHiddenClass:'options-hidden',
		dropScrollableClass:'options-overflow',
		dropClass:'select-options',
		dropClassPrefix:'drop-',
		dropStructure:'<div class="drop-holder"><div class="drop-list"></div></div>',
		dropSelector:'div.drop-list'
	},
	setupWrapper: function(){
		jcf.lib.addClass(this.fakeElement, this.options.wrapperClass);
		this.realElement.parentNode.insertBefore(this.fakeElement, this.realElement);
		this.fakeElement.innerHTML = this.options.selectStructure;
		this.fakeElement.style.width = this.realElement.offsetWidth + 'px';
		jcf.lib.addClass(this.fakeElement, jcf.lib.getAllClasses(this.realElement.className, this.options.selectPrefixClass, jcf.baseOptions.hiddenClass));

		// create select body
		this.opener = jcf.lib.queryBySelector(this.options.openerSelector, this.fakeElement)[0];
		this.valueText = jcf.lib.queryBySelector(this.options.valueSelector, this.fakeElement)[0];
		this.opener.jcf = this;

		this.createDropdown();
		this.refreshState();
		this.addEvents();
		this.onControlReady(this);
		this.hideDropdown(true);
	},
	addEvents: function(){
		jcf.lib.event.add(this.fakeElement, 'click', this.toggleDropdown, this);
		jcf.lib.event.add(this.realElement, 'change', this.onChange, this);
	},
	onFakeClick: function() {
		// do nothing (drop toggles by toggleDropdown method)
	},
	onFocus: function(){
		// Mac Safari Fix
		if(jcf.lib.browser.safariMac) {
			this.realElement.setAttribute('multiple','multiple');
		}
		jcf.modules[this.name].superclass.onFocus.apply(this, arguments);
		jcf.lib.event.add(this.realElement, 'keydown', this.onKeyDown, this);
		if(jcf.activeControl && jcf.activeControl != this) {
			jcf.activeControl.hideDropdown();
			jcf.activeControl = this;
		}
	},
	onBlur: function(){
		// Mac Safari Fix
		if(jcf.lib.browser.safariMac) {
			this.realElement.removeAttribute('multiple');
		}
		if(!this.isActiveDrop() || !this.isOverDrop()) {
			jcf.modules[this.name].superclass.onBlur.apply(this);
			if(jcf.activeControl === this) jcf.activeControl = null;
			if(!jcf.isTouchDevice) {
				this.hideDropdown();
			}
		}
		jcf.lib.event.remove(this.realElement, 'keydown', this.onKeyDown);
	},
	onChange: function() {
		this.refreshState();
	},
	onKeyDown: function(e){
		jcf.tmpFlag = true;
		setTimeout(function(){jcf.tmpFlag = false},100);
		var context = this;
		context.keyboardFix = true;
		setTimeout(function(){
			context.refreshState();
		},10);
		if(e.keyCode == 13) {
			context.toggleDropdown.apply(context);
			return false;
		}
	},
	onResizeWindow: function(e){
		if(this.isActiveDrop()) {
			this.hideDropdown();
		}
	},
	onScrollWindow: function(e){
		if(this.isActiveDrop()) {
			this.positionDropdown();
		}
	},
	onOptionClick: function(e){
		var opener = e.target && e.target.tagName && e.target.tagName.toLowerCase() == 'li' ? e.target : jcf.lib.getParent(e.target, 'li');
		if(opener) {
			this.realElement.selectedIndex = parseInt(opener.getAttribute('rel'));
			if(jcf.isTouchDevice) {
				this.onFocus();
			} else {
				this.realElement.focus();
			}
			this.refreshState();
			this.hideDropdown();
			jcf.lib.fireEvent(this.realElement, 'change');
		}
		return false;
	},
	onClickOutside: function(e){
		if(jcf.tmpFlag) {
			jcf.tmpFlag = false;
			return;
		}
		if(!jcf.lib.isParent(this.fakeElement, e.target) && !jcf.lib.isParent(this.selectDrop, e.target)) {
			this.hideDropdown();
		}
	},
	onDropHover: function(e){
		if(!this.keyboardFix) {
			this.hoverFlag = true;
			var opener = e.target && e.target.tagName && e.target.tagName.toLowerCase() == 'li' ? e.target : jcf.lib.getParent(e.target, 'li');
			if(opener) {
				this.realElement.selectedIndex = parseInt(opener.getAttribute('rel'));
				this.refreshSelectedClass(parseInt(opener.getAttribute('rel')));
			}
		} else {
			this.keyboardFix = false;
		}
	},
	onDropLeave: function(){
		this.hoverFlag = false;
	},
	isActiveDrop: function(){
		return !jcf.lib.hasClass(this.selectDrop, this.options.dropHiddenClass);
	},
	isOverDrop: function(){
		return this.hoverFlag;
	},
	createDropdown: function(){
		// remove old dropdown if exists
		if(this.selectDrop) {
			this.selectDrop.parentNode.removeChild(this.selectDrop);
		}

		// create dropdown holder
		this.selectDrop = document.createElement('div');
		this.selectDrop.className = this.options.dropClass;
		this.selectDrop.innerHTML = this.options.dropStructure;
		this.selectList = jcf.lib.queryBySelector(this.options.dropSelector,this.selectDrop)[0];
		jcf.lib.addClass(this.selectDrop, this.options.dropHiddenClass);
		document.body.appendChild(this.selectDrop);
		this.selectDrop.jcf = this;
		jcf.lib.event.add(this.selectDrop, 'click', this.onOptionClick, this);
		jcf.lib.event.add(this.selectDrop, 'mouseover', this.onDropHover, this);
		jcf.lib.event.add(this.selectDrop, 'mouseout', this.onDropLeave, this);
		this.buildDropdown();
	},
	buildDropdown: function() {
		// build select options / optgroups
		this.buildDropdownOptions();

		// position and resize dropdown
		this.positionDropdown();

		// cut dropdown if height exceedes
		this.buildDropdownScroll();
	},
	buildDropdownOptions: function() {
		this.resStructure = '';
		this.optNum = 0;
		for(var i = 0; i < this.realElement.children.length; i++) {
			this.resStructure += this.buildElement(this.realElement.children[i]) +'\n';
		}
		this.selectList.innerHTML = this.resStructure;
	},
	buildDropdownScroll: function() {
		if(this.options.dropMaxHeight) {
			if(this.selectDrop.offsetHeight > this.options.dropMaxHeight) {
				this.selectList.style.height = this.options.dropMaxHeight+'px';
				this.selectList.style.overflow = 'auto';
				this.selectList.style.overflowX = 'hidden';
				jcf.lib.addClass(this.selectDrop, this.options.dropScrollableClass);
			}
		}
		jcf.lib.addClass(this.selectDrop, jcf.lib.getAllClasses(this.realElement.className, this.options.dropClassPrefix, jcf.baseOptions.hiddenClass));
	},
	buildElement: function(obj){
		// build option
		var res = '';
		if(obj.tagName.toLowerCase() == 'option') {
			if(!jcf.lib.prevSibling(obj) || jcf.lib.prevSibling(obj).tagName.toLowerCase() != 'option') {
				res += '<ul>';
			}
			res += '<li rel="'+(this.optNum++)+'" class="'+(obj.className? obj.className : '')+' jcfcalc"><a href="#">'+(obj.title? '<img src="'+obj.title+'" alt="" />' : '')+'<span>' + obj.innerHTML + '</span></a></li>';
			if(!jcf.lib.nextSibling(obj) || jcf.lib.nextSibling(obj).tagName.toLowerCase() != 'option') {
				res += '</ul>';
			}
			return res;
		}
		// build option group with options
		else if(obj.tagName.toLowerCase() == 'optgroup' && obj.label) {
			res += '<div class="'+this.options.optGroupClass+'">';
			res += '<strong class="jcfcalc"><em>'+(obj.label)+'</em></strong>';
			for(var i = 0; i < obj.children.length; i++) {
				res += this.buildElement(obj.children[i]);
			}
			res += '</div>';
			return res;
		}
	},
	positionDropdown: function(){
		var ofs = jcf.lib.getOffset(this.fakeElement), selectAreaHeight = this.fakeElement.offsetHeight, selectDropHeight = this.selectDrop.offsetHeight;
		if(this.options.handleDropPosition && jcf.lib.getScrollTop() + jcf.lib.getWindowHeight() < ofs.top + selectAreaHeight + selectDropHeight) {
			this.selectDrop.style.top = (ofs.top - selectDropHeight)+'px';
			jcf.lib.addClass(this.selectDrop, this.options.dropFlippedClass);
		} else {
			this.selectDrop.style.top = (ofs.top + selectAreaHeight)+'px';
			jcf.lib.removeClass(this.selectDrop, this.options.dropFlippedClass);
		}
		this.selectDrop.style.left = ofs.left+'px';
		this.selectDrop.style.width = this.fakeElement.offsetWidth+'px';
	},
	showDropdown: function(){
		document.body.appendChild(this.selectDrop);
		jcf.lib.removeClass(this.selectDrop, this.options.dropHiddenClass);
		jcf.lib.addClass(this.fakeElement,this.options.dropActiveClass);
		this.positionDropdown();

		// show current dropdown
		jcf.lib.event.add(window, 'resize', this.onResizeWindow, this);
		jcf.lib.event.add(window, 'scroll', this.onScrollWindow, this);
		jcf.lib.event.add(document, jcf.eventPress, this.onClickOutside, this);
		this.positionDropdown();
	},
	hideDropdown: function(partial){
		try {
			if (this.selectDrop.parentNode) {
				document.body.removeChild(this.selectDrop);
				if (partial) {
					return;
				}
			}
		}catch(e) {}
		if(typeof this.origSelectedIndex === 'number') {
			this.realElement.selectedIndex = this.origSelectedIndex;
		}
		jcf.lib.removeClass(this.fakeElement,this.options.dropActiveClass);
		jcf.lib.addClass(this.selectDrop, this.options.dropHiddenClass);
		jcf.lib.event.remove(window, 'resize', this.onResizeWindow);
		jcf.lib.event.remove(window, 'scroll', this.onScrollWindow);
		jcf.lib.event.remove(document.documentElement, jcf.eventPress, this.onClickOutside);
		if(jcf.isTouchDevice) {
			this.onBlur();
		}
	},
	toggleDropdown: function(){
		if(jcf.isTouchDevice) {
			this.onFocus();
		} else {
			this.realElement.focus();
		}
		this.dropOpened = true;
		if(!this.realElement.disabled) {
			if(this.isActiveDrop()) {
				this.hideDropdown();
			} else {
				this.showDropdown();
			}
		}
		this.refreshState();
	},
	scrollToItem: function(){
		if(this.isActiveDrop()) {
			var dropHeight = this.selectList.offsetHeight;
			var offsetTop = this.calcOptionOffset(this.getFakeActiveOption());
			var sTop = this.selectList.scrollTop;
			var oHeight = this.getFakeActiveOption().offsetHeight;
			//offsetTop+=sTop;

			if(offsetTop >= sTop + dropHeight) {
				this.selectList.scrollTop = offsetTop - dropHeight + oHeight;
			} else if(offsetTop < sTop) {
				this.selectList.scrollTop = offsetTop;
			}
		}
	},
	getFakeActiveOption: function(c) {
		return jcf.lib.queryBySelector('li[rel="'+(typeof c === 'number' ? c : this.realElement.selectedIndex) +'"]',this.selectList)[0];
	},
	calcOptionOffset: function(fake) {
		var h = 0;
		var els = jcf.lib.queryBySelector('.jcfcalc',this.selectList);
		for(var i = 0; i < els.length; i++) {
			if(els[i] == fake) break;
			h+=els[i].offsetHeight;
		}
		return h;
	},
	childrenHasItem: function(hold,item) {
		var items = hold.getElementsByTagName('*');
		for(i = 0; i < items.length; i++) {
			if(items[i] == item) return true;
		}
		return false;
	},
	removeSelectedClass: function(){
		var children = jcf.lib.queryBySelector('li',this.selectList);
		for(var i = children.length - 1; i >= 0; i--) {
			jcf.lib.removeClass(children[i], this.options.selectedClass);
		}
	},
	setSelectedClass: function(c){
		jcf.lib.addClass(this.getFakeActiveOption(c), this.options.selectedClass);
	},
	refreshSelectedClass: function(c){
		this.removeSelectedClass(c);
		this.setSelectedClass(c);
		if(this.realElement.disabled) {
			jcf.lib.addClass(this.fakeElement, this.options.disabledClass);
		} else {
			jcf.lib.removeClass(this.fakeElement, this.options.disabledClass);
		}
	},
	refreshSelectedText: function() {
		if(!this.dropOpened && this.realElement.title) {
			this.valueText.innerHTML = this.realElement.title;
		} else {
			if(this.realElement.options[this.realElement.selectedIndex].title) {
				this.valueText.innerHTML = '<img src="'+this.realElement.options[this.realElement.selectedIndex].title+'" alt="" />' + this.realElement.options[this.realElement.selectedIndex].innerHTML;
			} else {
				this.valueText.innerHTML = this.realElement.options[this.realElement.selectedIndex].innerHTML;
			}
		}
	},
	refreshState: function(){
		this.origSelectedIndex = this.realElement.selectedIndex;
		this.refreshSelectedClass();
		this.refreshSelectedText();
		this.positionDropdown();
		this.scrollToItem();
	}
});

/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 *
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function(B){var L,T,Q,M,d,m,J,A,O,z,C=0,H={},j=[],e=0,G={},y=[],f=null,o=new Image(),i=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,k=/[^\.]\.(swf)\s*$/i,p,N=1,h=0,t="",b,c,P=false,s=B.extend(B("<div/>")[0],{prop:0}),S=B.browser.msie&&B.browser.version<7&&!window.XMLHttpRequest,r=function(){T.hide();o.onerror=o.onload=null;if(f){f.abort()}L.empty()},x=function(){if(false===H.onError(j,C,H)){T.hide();P=false;return}H.titleShow=false;H.width="auto";H.height="auto";L.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');n()},w=function(){var Z=j[C],W,Y,ab,aa,V,X;r();H=B.extend({},B.fn.fancybox.defaults,(typeof B(Z).data("fancybox")=="undefined"?H:B(Z).data("fancybox")));X=H.onStart(j,C,H);if(X===false){P=false;return}else{if(typeof X=="object"){H=B.extend(H,X)}}ab=H.title||(Z.nodeName?B(Z).attr("title"):Z.title)||"";if(Z.nodeName&&!H.orig){H.orig=B(Z).children("img:first").length?B(Z).children("img:first"):B(Z)}if(ab===""&&H.orig&&H.titleFromAlt){ab=H.orig.attr("alt")}W=H.href||(Z.nodeName?B(Z).attr("href"):Z.href)||null;if((/^(?:javascript)/i).test(W)||W=="#"){W=null}if(H.type){Y=H.type;if(!W){W=H.content}}else{if(H.content){Y="html"}else{if(W){if(W.match(i)){Y="image"}else{if(W.match(k)){Y="swf"}else{if(B(Z).hasClass("iframe")){Y="iframe"}else{if(W.indexOf("#")===0){Y="inline"}else{Y="ajax"}}}}}}}if(!Y){x();return}if(Y=="inline"){Z=W.substr(W.indexOf("#"));Y=B(Z).length>0?"inline":"ajax"}H.type=Y;H.href=W;H.title=ab;if(H.autoDimensions){if(H.type=="html"||H.type=="inline"||H.type=="ajax"){H.width="auto";H.height="auto"}else{H.autoDimensions=false}}if(H.modal){H.overlayShow=true;H.hideOnOverlayClick=false;H.hideOnContentClick=false;H.enableEscapeButton=false;H.showCloseButton=false}H.padding=parseInt(H.padding,10);H.margin=parseInt(H.margin,10);L.css("padding",(H.padding+H.margin));B(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){B(this).replaceWith(m.children())});switch(Y){case"html":L.html(H.content);n();break;case"inline":if(B(Z).parent().is("#fancybox-content")===true){P=false;return}B('<div class="fancybox-inline-tmp" />').hide().insertBefore(B(Z)).bind("fancybox-cleanup",function(){B(this).replaceWith(m.children())}).bind("fancybox-cancel",function(){B(this).replaceWith(L.children())});B(Z).appendTo(L);n();break;case"image":P=false;B.fancybox.showActivity();o=new Image();o.onerror=function(){x()};o.onload=function(){P=true;o.onerror=o.onload=null;F()};o.src=W;break;case"swf":H.scrolling="no";aa='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+H.width+'" height="'+H.height+'"><param name="movie" value="'+W+'"></param>';V="";B.each(H.swf,function(ac,ad){aa+='<param name="'+ac+'" value="'+ad+'"></param>';V+=" "+ac+'="'+ad+'"'});aa+='<embed src="'+W+'" type="application/x-shockwave-flash" width="'+H.width+'" height="'+H.height+'"'+V+"></embed></object>";L.html(aa);n();break;case"ajax":P=false;B.fancybox.showActivity();H.ajax.win=H.ajax.success;f=B.ajax(B.extend({},H.ajax,{url:W,data:H.ajax.data||{},dataType:"text",error:function(ac,ae,ad){if(ac.status>0){x()}},success:function(ad,af,ac){var ae=typeof ac=="object"?ac:f;if(ae.status==200||ae.status===0){if(typeof H.ajax.win=="function"){X=H.ajax.win(W,ad,af,ac);if(X===false){T.hide();return}else{if(typeof X=="string"||typeof X=="object"){ad=X}}}L.html(ad);n()}}}));break;case"iframe":E();break}},n=function(){var V=H.width,W=H.height;if(V.toString().indexOf("%")>-1){V=parseInt((B(window).width()-(H.margin*2))*parseFloat(V)/100,10)+"px"}else{V=V=="auto"?"auto":V+"px"}if(W.toString().indexOf("%")>-1){W=parseInt((B(window).height()-(H.margin*2))*parseFloat(W)/100,10)+"px"}else{W=W=="auto"?"auto":W+"px"}L.wrapInner('<div style="width:'+V+";height:"+W+";overflow: "+(H.scrolling=="auto"?"auto":(H.scrolling=="yes"?"scroll":"hidden"))+';position:relative;"></div>');H.width=L.width();H.height=L.height();E()},F=function(){H.width=o.width;H.height=o.height;B("<img />").attr({id:"fancybox-img",src:o.src,alt:H.title}).appendTo(L);E()},E=function(){var W,V;T.hide();if(M.is(":visible")&&false===G.onCleanup(y,e,G)){B.event.trigger("fancybox-cancel");P=false;return}P=true;B(m.add(Q)).unbind();B(window).unbind("resize.fb scroll.fb");B(document).unbind("keydown.fb");if(M.is(":visible")&&G.titlePosition!=="outside"){M.css("height",M.height())}y=j;e=C;G=H;if(G.overlayShow){Q.css({"background-color":G.overlayColor,opacity:G.overlayOpacity,cursor:G.hideOnOverlayClick?"pointer":"auto",height:B(document).height()});if(!Q.is(":visible")){if(S){B("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"})}Q.show()}}else{Q.hide()}c=R();l();if(M.is(":visible")){B(J.add(O).add(z)).hide();W=M.position(),b={top:W.top,left:W.left,width:M.width(),height:M.height()};V=(b.width==c.width&&b.height==c.height);m.fadeTo(G.changeFade,0.3,function(){var X=function(){m.html(L.contents()).fadeTo(G.changeFade,1,v)};B.event.trigger("fancybox-change");m.empty().removeAttr("filter").css({"border-width":G.padding,width:c.width-G.padding*2,height:H.autoDimensions?"auto":c.height-h-G.padding*2});if(V){X()}else{s.prop=0;B(s).animate({prop:1},{duration:G.changeSpeed,easing:G.easingChange,step:U,complete:X})}});return}M.removeAttr("style");m.css("border-width",G.padding);if(G.transitionIn=="elastic"){b=I();m.html(L.contents());M.show();if(G.opacity){c.opacity=0}s.prop=0;B(s).animate({prop:1},{duration:G.speedIn,easing:G.easingIn,step:U,complete:v});return}if(G.titlePosition=="inside"&&h>0){A.show()}m.css({width:c.width-G.padding*2,height:H.autoDimensions?"auto":c.height-h-G.padding*2}).html(L.contents());M.css(c).fadeIn(G.transitionIn=="none"?0:G.speedIn,v)},D=function(V){if(V&&V.length){if(G.titlePosition=="float"){return'<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+V+'</td><td id="fancybox-title-float-right"></td></tr></table>'}return'<div id="fancybox-title-'+G.titlePosition+'">'+V+"</div>"}return false},l=function(){t=G.title||"";h=0;A.empty().removeAttr("style").removeClass();if(G.titleShow===false){A.hide();return}t=B.isFunction(G.titleFormat)?G.titleFormat(t,y,e,G):D(t);if(!t||t===""){A.hide();return}A.addClass("fancybox-title-"+G.titlePosition).html(t).appendTo("body").show();switch(G.titlePosition){case"inside":A.css({width:c.width-(G.padding*2),marginLeft:G.padding,marginRight:G.padding});h=A.outerHeight(true);A.appendTo(d);c.height+=h;break;case"over":A.css({marginLeft:G.padding,width:c.width-(G.padding*2),bottom:G.padding}).appendTo(d);break;case"float":A.css("left",parseInt((A.width()-c.width-40)/2,10)*-1).appendTo(M);break;default:A.css({width:c.width-(G.padding*2),paddingLeft:G.padding,paddingRight:G.padding}).appendTo(M);break}A.hide()},g=function(){if(G.enableEscapeButton||G.enableKeyboardNav){B(document).bind("keydown.fb",function(V){if(V.keyCode==27&&G.enableEscapeButton){V.preventDefault();B.fancybox.close()}else{if((V.keyCode==37||V.keyCode==39)&&G.enableKeyboardNav&&V.target.tagName!=="INPUT"&&V.target.tagName!=="TEXTAREA"&&V.target.tagName!=="SELECT"){V.preventDefault();B.fancybox[V.keyCode==37?"prev":"next"]()}}})}if(!G.showNavArrows){O.hide();z.hide();return}if((G.cyclic&&y.length>1)||e!==0){O.show()}if((G.cyclic&&y.length>1)||e!=(y.length-1)){z.show()}},v=function(){if(!B.support.opacity){m.get(0).style.removeAttribute("filter");M.get(0).style.removeAttribute("filter")}if(H.autoDimensions){m.css("height","auto")}M.css("height","auto");if(t&&t.length){A.show()}if(G.showCloseButton){J.show()}g();if(G.hideOnContentClick){m.bind("click",B.fancybox.close)}if(G.hideOnOverlayClick){Q.bind("click",B.fancybox.close)}B(window).bind("resize.fb",B.fancybox.resize);if(G.centerOnScroll){B(window).bind("scroll.fb",B.fancybox.center)}if(G.type=="iframe"){B('<iframe id="fancybox-frame" name="fancybox-frame'+new Date().getTime()+'" frameborder="0" hspace="0" '+(B.browser.msie?'allowtransparency="true""':"")+' scrolling="'+H.scrolling+'" src="'+G.href+'"></iframe>').appendTo(m)}M.show();P=false;B.fancybox.center();G.onComplete(y,e,G);K()},K=function(){var V,W;if((y.length-1)>e){V=y[e+1].href;if(typeof V!=="undefined"&&V.match(i)){W=new Image();W.src=V}}if(e>0){V=y[e-1].href;if(typeof V!=="undefined"&&V.match(i)){W=new Image();W.src=V}}},U=function(W){var V={width:parseInt(b.width+(c.width-b.width)*W,10),height:parseInt(b.height+(c.height-b.height)*W,10),top:parseInt(b.top+(c.top-b.top)*W,10),left:parseInt(b.left+(c.left-b.left)*W,10)};if(typeof c.opacity!=="undefined"){V.opacity=W<0.5?0.5:W}M.css(V);m.css({width:V.width-G.padding*2,height:V.height-(h*W)-G.padding*2})},u=function(){return[B(window).width()-(G.margin*2),B(window).height()-(G.margin*2),B(document).scrollLeft()+G.margin,B(document).scrollTop()+G.margin]},R=function(){var V=u(),Z={},W=G.autoScale,X=G.padding*2,Y;if(G.width.toString().indexOf("%")>-1){Z.width=parseInt((V[0]*parseFloat(G.width))/100,10)}else{Z.width=G.width+X}if(G.height.toString().indexOf("%")>-1){Z.height=parseInt((V[1]*parseFloat(G.height))/100,10)}else{Z.height=G.height+X}if(W&&(Z.width>V[0]||Z.height>V[1])){if(H.type=="image"||H.type=="swf"){Y=(G.width)/(G.height);if((Z.width)>V[0]){Z.width=V[0];Z.height=parseInt(((Z.width-X)/Y)+X,10)}if((Z.height)>V[1]){Z.height=V[1];Z.width=parseInt(((Z.height-X)*Y)+X,10)}}else{Z.width=Math.min(Z.width,V[0]);Z.height=Math.min(Z.height,V[1])}}Z.top=parseInt(Math.max(V[3]-20,V[3]+((V[1]-Z.height-40)*0.5)),10);Z.left=parseInt(Math.max(V[2]-20,V[2]+((V[0]-Z.width-40)*0.5)),10);return Z},q=function(V){var W=V.offset();W.top+=parseInt(V.css("paddingTop"),10)||0;W.left+=parseInt(V.css("paddingLeft"),10)||0;W.top+=parseInt(V.css("border-top-width"),10)||0;W.left+=parseInt(V.css("border-left-width"),10)||0;W.width=V.width();W.height=V.height();return W},I=function(){var Y=H.orig?B(H.orig):false,X={},W,V;if(Y&&Y.length){W=q(Y);X={width:W.width+(G.padding*2),height:W.height+(G.padding*2),top:W.top-G.padding-20,left:W.left-G.padding-20}}else{V=u();X={width:G.padding*2,height:G.padding*2,top:parseInt(V[3]+V[1]*0.5,10),left:parseInt(V[2]+V[0]*0.5,10)}}return X},a=function(){if(!T.is(":visible")){clearInterval(p);return}B("div",T).css("top",(N*-40)+"px");N=(N+1)%12};B.fn.fancybox=function(V){if(!B(this).length){return this}B(this).data("fancybox",B.extend({},V,(B.metadata?B(this).metadata():{}))).unbind("click.fb").bind("click.fb",function(X){X.preventDefault();if(P){return}P=true;B(this).blur();j=[];C=0;var W=B(this).attr("rel")||"";if(!W||W==""||W==="nofollow"){j.push(this)}else{j=B("a[rel="+W+"], area[rel="+W+"]");C=j.index(this)}w();return});return this};B.fancybox=function(Y){var X;if(P){return}P=true;X=typeof arguments[1]!=="undefined"?arguments[1]:{};j=[];C=parseInt(X.index,10)||0;if(B.isArray(Y)){for(var W=0,V=Y.length;W<V;W++){if(typeof Y[W]=="object"){B(Y[W]).data("fancybox",B.extend({},X,Y[W]))}else{Y[W]=B({}).data("fancybox",B.extend({content:Y[W]},X))}}j=jQuery.merge(j,Y)}else{if(typeof Y=="object"){B(Y).data("fancybox",B.extend({},X,Y))}else{Y=B({}).data("fancybox",B.extend({content:Y},X))}j.push(Y)}if(C>j.length||C<0){C=0}w()};B.fancybox.showActivity=function(){clearInterval(p);T.show();p=setInterval(a,66)};B.fancybox.hideActivity=function(){T.hide()};B.fancybox.next=function(){return B.fancybox.pos(e+1)};B.fancybox.prev=function(){return B.fancybox.pos(e-1)};B.fancybox.pos=function(V){if(P){return}V=parseInt(V);j=y;if(V>-1&&V<y.length){C=V;w()}else{if(G.cyclic&&y.length>1){C=V>=y.length?0:y.length-1;w()}}return};B.fancybox.cancel=function(){if(P){return}P=true;B.event.trigger("fancybox-cancel");r();H.onCancel(j,C,H);P=false};B.fancybox.close=function(){if(P||M.is(":hidden")){return}P=true;if(G&&false===G.onCleanup(y,e,G)){P=false;return}r();B(J.add(O).add(z)).hide();B(m.add(Q)).unbind();B(window).unbind("resize.fb scroll.fb");B(document).unbind("keydown.fb");if(G.type==="iframe"){m.find("iframe").attr("src",S&&/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")}if(G.titlePosition!=="inside"){A.empty()}M.stop();function V(){Q.fadeOut("fast");A.empty().hide();M.hide();B.event.trigger("fancybox-cleanup");m.empty();G.onClosed(y,e,G);y=H=[];e=C=0;G=H={};P=false}if(G.transitionOut=="elastic"){b=I();var W=M.position();c={top:W.top,left:W.left,width:M.width(),height:M.height()};if(G.opacity){c.opacity=1}A.empty().hide();s.prop=1;B(s).animate({prop:0},{duration:G.speedOut,easing:G.easingOut,step:U,complete:V})}else{M.fadeOut(G.transitionOut=="none"?0:G.speedOut,V)}};B.fancybox.resize=function(){if(Q.is(":visible")){Q.css("height",B(document).height())}B.fancybox.center(true)};B.fancybox.center=function(){var V,W;if(P){return}W=arguments[0]===true?1:0;V=u();if(!W&&(M.width()>V[0]||M.height()>V[1])){return}M.stop().animate({top:parseInt(Math.max(V[3]-20,V[3]+((V[1]-m.height()-40)*0.5)-G.padding)),left:parseInt(Math.max(V[2]-20,V[2]+((V[0]-m.width()-40)*0.5)-G.padding))},typeof arguments[0]=="number"?arguments[0]:200)};B.fancybox.init=function(){if(B("#fancybox-wrap").length){return}B("body").append(L=B('<div id="fancybox-tmp"></div>'),T=B('<div id="fancybox-loading"><div></div></div>'),Q=B('<div id="fancybox-overlay"></div>'),M=B('<div id="fancybox-wrap"></div>'));d=B('<div id="fancybox-outer"></div>').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>').appendTo(M);d.append(m=B('<div id="fancybox-content"></div>'),J=B('<a id="fancybox-close"></a>'),A=B('<div id="fancybox-title"></div>'),O=B('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),z=B('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));J.click(B.fancybox.close);T.click(B.fancybox.cancel);O.click(function(V){V.preventDefault();B.fancybox.prev()});z.click(function(V){V.preventDefault();B.fancybox.next()});if(B.fn.mousewheel){M.bind("mousewheel.fb",function(V,W){if(P){V.preventDefault()}else{if(B(V.target).get(0).clientHeight==0||B(V.target).get(0).scrollHeight===B(V.target).get(0).clientHeight){V.preventDefault();B.fancybox[W>0?"prev":"next"]()}}})}if(!B.support.opacity){M.addClass("fancybox-ie")}if(S){T.addClass("fancybox-ie6");M.addClass("fancybox-ie6");B('<iframe id="fancybox-hide-sel-frame" src="'+(/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")+'" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(d)}};B.fn.fancybox.defaults={padding:10,margin:40,opacity:false,modal:false,cyclic:false,scrolling:"auto",width:560,height:340,autoScale:true,autoDimensions:true,centerOnScroll:false,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:true,hideOnContentClick:false,overlayShow:true,overlayOpacity:0.7,overlayColor:"#777",titleShow:true,titlePosition:"float",titleFormat:null,titleFromAlt:false,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",easingOut:"swing",showCloseButton:true,showNavArrows:true,enableEscapeButton:true,enableKeyboardNav:true,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}};B(document).ready(function(){B.fancybox.init()})})(jQuery);

