jQuery.noConflict();

//Page init scripts
jQuery(window).load(function(){
	if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
		remove_home_flash_intro();   
   	};
  		initSwichMainImage();
		initNav();
		VSA_initScrollbars();
		initResizeScroll(); 		
		initBackgroundResize();
	
	//Navigation through the big arrows LEFT
	jQuery(".next_big").click(function(){
		var current_slide = jQuery(this).attr("rel");
		 grayAnimation(jQuery('li[slidenumnav='+current_slide+']').next("li"), true);                   	
		jQuery('li[slidenumnav='+current_slide+']').next("li").click();
	});                                                     
	//Navigation through the big arrows RIGHT
	jQuery(".prev_big").click(function(){
		var current_slide = jQuery(this).attr("rel"); 
		grayAnimation(jQuery('li[slidenumnav='+current_slide+']').prev("li"), true);     
		jQuery('li[slidenumnav='+current_slide+']').prev("li").click();
	});
	
	// Clean Wordpress Gengerated Empty Tags
	jQuery('p')
    .filter(function() {
        return jQuery.trim(jQuery(this).text()) === ''
    }).remove()
	
	//Tabs open by default on press section
/*
	jQuery(".btn.press").click();                                   
*/
	
	function grayAnimation(elem, state){
		if(!elem.hasClass('active')){
			if(state){
				elem.find('.fly').animate({ opacity: 1 }, { queue: false, duration: 200 });
			}
			else {
				elem.find('.fly').animate({ opacity: 0 }, { queue: false, duration: 200 });
			}
		}
	};
});
jQuery(function(){
	if(navigator.userAgent.toLowerCase().indexOf('msie 6.0') != -1){
		document.body.style.display = 'none';
		alert('You are using an outdated web browser. Please upgrate it to a newer version');
	}
	initAddClass();
	initNavFix();
	initOpenClose();
	initGallery();   
});

acabou_o_flash = false;

/* initResizeScroll */
function initResizeScroll(){
	var timer;
	function isMobile(){
		return (/(ipad|iphone|ipod|android|blackberry|iemobile)/gi).test(navigator.userAgent)
	};
	jQuery(window).bind('resize orientationchange', function(){
		ref();
	});
	function getPageWidth() {
		return jQuery('.bg-gallery').width();
	};
	function getPageHeight() {
		return jQuery('.bg-gallery').height();
	};
	function ref() {
		// document.getElementById('nav').style.width = getPageWidth() + 'px';
		if(isMobile()){
			jQuery('#bottom-panel').css({
				position: 'absolute',
				bottom: 'auto',
				top: getPageHeight() - jQuery('#bottom-panel').height() - jQuery('#nav').height()
			});
		};
	};
	setInterval(ref, 100);
};

/* fix nav */
function initNav() {
	jQuery('#nav > li').bind('click', function(){
		if(jQuery(this).find('.drop').length){
			if(!jQuery(this).hasClass('hover')){
				jQuery(this).addClass('hover')
				return false;
			}
		}
	}).bind('mouseleave', function(){
		jQuery(this).removeClass('hover')
	}) 
}

/* home open-close */
function initHomeOpenClose(){
	jQuery('.bg-gallery').each(function(){
		var set = jQuery(this);
		var openBox = jQuery('.text-box', set);
	})
};

/* initSwichMainImage */
function initSwichMainImage(){
	jQuery("#flash_intro").css({backgroundColor: "transparent"});
	
	var slideshow;
	var delay = 100;
	var animSpeed = 200;
	
	/* home page animation */
	if(jQuery('body').hasClass('home-page')){   
		//do nothing;
	}else{
		jQuery('#nav > li').not("li:first").each(function(idx){
			if(jQuery(this).attr('title')){
				jQuery(this).attr('slideNumNav',jQuery(this).attr('title')).removeAttr('title');
				jQuery(this).bind('mouseenter', function(){
					clearTimeout(slideshow.timer);
					if(jQuery('.bg-gallery').find('li').filter('[slideNum= ' + jQuery(this).attr('slideNumNav') + ']').is(':hidden')){
						slideshow.prevSlide = slideshow.nextSlide;
						slideshow.nextSlide = jQuery('.bg-gallery').find('li').filter('[slideNum= ' + jQuery(this).attr('slideNumNav') + ']').index();
						slideshow.swichSlide(slideshow.prevSlide, slideshow.nextSlide);
						slideshow.swichTime = false; 
					};
				}).bind('mouseleave', function(){
					slideshow.autoRotation();
				});
			};
		});
		// jQuery('.text-box .more-link').bind('click', function(){
		// 			clearTimeout(slideshow.timer);
		// 			slideshow.swichTime = false;
		// 		});
	};
	
	jQuery('.bg-gallery').each(function(){
		var set = jQuery(this);
		var slides = set.find('li');
		slides.each(function(){
			if(jQuery(this).attr('rel')) jQuery(this).attr('slideNum',jQuery(this).attr('rel')).removeAttr('rel');
		});                     
		slideshow = new initSlidesNV(set,{
			list: '>ul',
			//swichTime: jQuery('body').hasClass('home-page') ? 5000 : false,
			swichTime: false,			
			onStart: function(obj, list, slides, next){
				slides.css({ position: 'absolute', top: 0, left: 0 });
				if(jQuery('#nav > li').filter('[slideNumNav= ' + slides.eq(next).attr('slideNum') + ']').length){
					jQuery('#nav > li').removeClass('active-slideshow');
					jQuery('#nav > li').filter('[slideNumNav= ' + slides.eq(next).attr('slideNum') + ']').addClass('active-slideshow');
				}
			},
			afterAnimation: function(obj, list, slides, next){
				if(jQuery('#nav > li').filter('[slideNumNav= ' + slides.eq(next).attr('slideNum') + ']').length){
					jQuery('#nav > li').removeClass('active-slideshow');
					jQuery('#nav > li').filter('[slideNumNav= ' + slides.eq(next).attr('slideNum') + ']').addClass('active-slideshow');
				}
			}
		});
	});
	
	jQuery('.bottom-panel .holder > ul > li').each(function(idx){
		var image = jQuery(this).find('img');
		image.clone();
		var gray = image.clone().addClass('grayscaled').appendTo(jQuery(this)).grayscale();
		image.addClass('fly').css({ opacity: 0 });
		if(jQuery(this).attr('rel')){
			jQuery(this).attr('slideNumNav',jQuery(this).attr('rel')).removeAttr('rel');
			// jQuery(this).bind('click', function(){
			jQuery(this).click(function(){
				var tt = jQuery('.bottom-panel .holder > ul > li').filter('.active:eq(0)');
				jQuery('.bottom-panel .holder > ul > li').removeClass('active');
				grayAnimation(tt, false);
				jQuery(this).addClass('active');
				if(jQuery('.bg-gallery').find('li').filter('[slideNum= ' + jQuery(this).attr('slideNumNav') + ']').is(':hidden')){
					slideshow.prevSlide = slideshow.nextSlide;
					slideshow.nextSlide = jQuery('.bg-gallery').find('li').filter('[slideNum= ' + jQuery(this).attr('slideNumNav') + ']').index();
					slideshow.swichSlide(slideshow.prevSlide, slideshow.nextSlide);
				};
				return false;
			});
		};
	});
	jQuery('.bottom-panel .holder > ul > li').filter('[slideNumNav= ' + slideshow.slides.eq(slideshow.startSlide).attr('slideNum') + ']:eq(0)')
		.addClass('active')
		.find('.fly').css({ opacity: 1 });
	jQuery('.bottom-panel .holder > ul > li').bind('mouseenter', function(){
		/* mouse over */
		grayAnimation(jQuery(this), true);
	}).bind('mouseleave', function(){
		/* mouse over */
		grayAnimation(jQuery(this), false);
	});
	function grayAnimation(elem, state){
		if(!elem.hasClass('active')){
			if(state){
				elem.find('.fly').animate({ opacity: 1 }, { queue: false, duration: animSpeed });
			}
			else {
				elem.find('.fly').animate({ opacity: 0 }, { queue: false, duration: animSpeed });
			}
		}
	}; 
};

// grayscale plugin
(function($){
	var IE = $.browser.msie && $.browser.version <= 9;
	function grayscale(image) {
		if(IE) {
			image.style.filter = 'gray';
		} else {
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			var imgWidth = image.width;
			var imgHeight = image.height;
			canvas.width = imgWidth;
			canvas.height = imgHeight;
			ctx.drawImage(image, 0, 0);
			var imageData = ctx.getImageData(0, 0, imgWidth, imgHeight);
			for (i = 0; i < imageData.height; i++) {
				for (j = 0; j < imageData.width; j++) {
					var index = (i*4)*imageData.width+(j*4);
					var red = imageData.data[index];
					var green = imageData.data[index+1];
					var blue = imageData.data[index+2];
					var alpha = imageData.data[index+3];
					var average = (red+green+blue)/3;
					imageData.data[index] = average;
					imageData.data[index+1] = average;
					imageData.data[index+2] = average;
					imageData.data[index+3] = alpha;
				}
			}
			ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
			image.parentNode.insertBefore(canvas, image);
			image.style.display = 'none';
			//image.parentNode.removeChild(image);
		}
	}
	$.fn.grayscale = function(){
		return this.each(function(){
			grayscale(this);
		});
	}
})(jQuery);

// background resize init
function initBackgroundResize(){
	var holder = document.getElementById('bg');
	var images = holder.getElementsByTagName('img');
	for(var i = 0; i < images.length; i++) {
		if(images[i].className.indexOf('wp-post-image') != -1){
			backgroundStretcher.stretchImage(images[i]);
		};
	};
	backgroundStretcher.setBgHolder(holder);
	backgroundAdjust();
	
	jQuery('.text-frame').each(function(){
		jQuery(this).css({ marginTop: -jQuery(this).height()/2 });
	});
};

/* backgroundAdjust */

function backgroundAdjust() {
	var baseRatio = 1.76;
	var adjMod = 0.9;  
	var th = jQuery(window).height();
	var tw = jQuery(window).width();
	var posAdjust = "";
	var ratio = tw/th;
	var imgElems = jQuery("#bg > li > img");
	
	imgElems.css({'position':'relative','left':0,'top':0}) //reset
	
	if ((navigator.userAgent.indexOf('iPad') != -1)) {

 			posAdjust = (tw-(baseRatio * th))*adjMod;
			imgElems.css({'position':'relative','left':posAdjust});

	}
	else if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1)) {
		//no adjustment
	}		
	else if (jQuery('#bg').hasClass('Advertisements')) {
		return;		
	}
	else {
	if(tw>=1000){
		if(ratio<baseRatio) {
			posAdjust = (tw-(baseRatio * th))*adjMod;
			imgElems.css({'position':'relative','left':posAdjust});
		}
		else if(ratio>baseRatio/*  && jQuery('#bg').not('.history') */)  {
			posAdjust = (th-(tw/baseRatio))*adjMod;
			imgElems.css({'position':'relative','top':posAdjust});
		}
		else {
			// no adjustment
		}
	
		}
	}
}
/* slideshow module */
function initSlidesNV(context, options){this.init(context, options)}
(function( $ ){
	initSlidesNV.prototype = {
		list: '>ul',
		slides: '>li',
		animationSpeed: 500,
		btnPrev: '.prev',
		btnNext: '.next',
		eventType: 'click',
		eventTypeForPager: 'click',
		pagerLinks: false,
		swichTime: false, // 1000 = 1 sec
		circle: true,
		direction: 'rtl', // 'rtl', 'ltr', 'ttb', 'btt'
		autoHeightList: false,
		startSlide: 0,
		stopOnHover: false,
		onStart: function(){},
		afterAnimation: function(){},
		init: function(context, options){
			for ( var i in options ) this[i] = options[i]; 
			this.set = jQuery(context);
			if(this.set == undefined) return;
			this.waitAnimation = true;
			this.prevSlide = this.nextSlide = this.startSlide;
			this.btnNext = this.set.find(this.btnNext);
			this.btnPrev = this.set.find(this.btnPrev);
			this.list = this.set.find(this.list);
			this.slides = this.list.find(this.slides);
			if(this.pagerLinks){
				this.set.find(this.pagerLinks).each(this.binder(function(i, links){
					jQuery(links).bind(this.eventTypeForPager, this.binder(function(){
						this.prevSlide = this.nextSlide;
						this.nextSlide = i;
						if(this.nextSlide != this.prevSlide) this.swichSlide(this.prevSlide, this.nextSlide);
						return false;
					}))
				}))
			};
			this.btnNext.bind(this.eventType, this.binder(function(){
				if(this.waitAnimation){
					this.waitAnimation = false;
					this.next();
				};
				return false;
			}));
			this.btnPrev.bind(this.eventType, this.binder(function(){
				if(this.waitAnimation){
					this.waitAnimation = false;
					this.prev();
				};
				return false;
			}));
			this.autoRotation();
			if(this.stopOnHover){
				this.set.bind('mouseenter', this.binder(function(){
					clearTimeout(this.timer);
				})).bind('mouseleave', this.binder(function(){
					this.autoRotation();
				}))
			}
			this.slides.hide().eq(this.nextSlide).show();
			this.onStart(this, this.list, this.slides, this.nextSlide);
		},
		prev: function(){
			this.prevSlide = this.nextSlide;
			if(this.nextSlide > 0){
				this.nextSlide--
			}
			else if(this.circle) {
				this.nextSlide = this.slides.length-1
			};
			this.swichSlide(this.prevSlide, this.nextSlide);
		},
		next: function(){
			this.prevSlide = this.nextSlide;
			if(this.nextSlide < this.slides.length-1){
				this.nextSlide++
			}
			else if(this.circle) {
				this.nextSlide = 0
			};
			this.swichSlide(this.prevSlide, this.nextSlide);
		},
		swichSlide: function(prev, next){
			if(!this.slides.eq(next).length) return;
			this.slides.eq(prev).animate({
				opacity: 0
			}, { queue: false, duration: this.animationSpeed, complete: this.binder(function(){
				this.slides.eq(prev).css({ display: 'none' });
			})})
			this.slides.eq(next).css({ 
				opacity: 0,
				display: 'block'
			}).animate({
				opacity: 1
			}, { queue: false, duration: this.animationSpeed, complete: this.binder(function(){
				this.afterAnimation(this, this.list, this.slides, next);
				this.waitAnimation = true;
				if(this.autoHeightList) this.autoHeight(this.nextSlide);
				clearTimeout(this.timer);
				this.autoRotation();
			})});
		},
		autoHeight: function(next){
			if(this.autoHeightList){
				this.list.animate({ height: this.slides.eq(next).outerHeight() }, { queue: false, duration: 150 });
			}
		},
		autoRotation: function(){
			if(this.swichTime && this.swichTime > 0){
				clearTimeout(this.timer);
				this.timer = setTimeout(this.binder(function(){
					if(this.direction == 'ltr'){
						this.prev();
					}else if(this.direction == 'rtl') {
						this.next();
					};
				}), this.swichTime)
			}
		},
		binder: function(fn, scope, args){
			var newScope = scope || this;
			return function() {
				return fn.apply(newScope, args || arguments);
			}
		}
	}
})( jQuery );


/* initOpenClose */
function initOpenClose(){
	// jQuery('.text-box').OpenClose({
	// 		activeClass:'active',
	// 		opener:'.more-link',
	// 		slider:'div.hide-text',
	// 		effect:'slide',
	// 		animSpeed:500
	// 	});
	jQuery('.bottom-panel').OpenClose({
		activeClass:'active',
		opener:'.btn-holder .btn',
		slider:'.gallery',
		effect:'slide',
		animSpeed:500
	});
	jQuery('.left-slide-box').OpenClose({
		activeClass:'active',
		opener:'.btn',
		slider:'div.text-holder',
		effect:'slide',
		diraction: 'horizontal',
		animSpeed:500
	});
	jQuery('.right-slide-box').OpenClose({
		activeClass:'active',
		opener:'.btn',
		slider:'div.text-holder',
		effect:'slide',
		diraction: 'horizontal',
		leftToRight: true,
		animSpeed:500
	});
	
	jQuery('.right-slide-box .btn').click();
};
// open-close plugin
jQuery.fn.OpenClose = function(_options){
	// default options
	var _options = jQuery.extend({
		activeClass:'active',
		opener:'.opener',
		slider:'.slide',
		animSpeed: 400,
		animStart:false,
		animEnd:false,
		effect:'fade',
		diraction: 'vertical',
		leftToRight: false,
		outClickHide: false,
		event:'click'
	},_options);

	return this.each(function(){
		// options
		var _holder = jQuery(this);
		var _slideSpeed = _options.animSpeed;
		var _activeClass = _options.activeClass;
		var _opener = jQuery(_options.opener, _holder);
		var _slider = jQuery(_options.slider, _holder);
		var _animStart = _options.animStart;
		var _animEnd = _options.animEnd;
		var _effect = _options.effect;
		var _event = _options.event;
		var diraction = _options.diraction;
		var leftToRight = _options.leftToRight;
		_slider.show();
		var slideWidth = _slider.outerWidth(true);
		var slideHeight = _slider.outerHeight(true);
		
		if(_slider.length) {
			_opener.bind(_event,function(){
			if(_options.opener == ".btn-holder .btn"){
				var _slideControls = jQuery(".next_big, .prev_big");
				if(jQuery('#bg').hasClass('press')) {
					var _aniheight = 258;
				}else if(jQuery('#bg').hasClass('fragrances')){
					var _aniheight = 200;
				}else{
					var _aniheight = 170;
				} 
				jQuery(_slideControls).animate({bottom: _aniheight},_slideSpeed);
			}
				if(!_slider.is(':animated')) {
					if(typeof _animStart === 'function') _animStart();
					if(_holder.hasClass(_activeClass)) {
						if(_effect == 'fade'){
							_slider.fadeOut(_slideSpeed,function(){
								if(typeof _animEnd === 'function') _animEnd();
							});
						}
						else { 
							if(diraction == 'horizontal'){
								if(leftToRight){
									_slider.animate({ marginRight: -slideWidth },{
										queue: false, duration: _slideSpeed, complete: function(){
											if(typeof _animEnd === 'function') _animEnd();
										}
									});
								}
								else {
									_slider.animate({ marginLeft: -slideWidth },{
										queue: false, duration: _slideSpeed, complete: function(){
											if(typeof _animEnd === 'function') _animEnd();
										}
									});
								}
							}
							else {
								_slider.slideUp(_slideSpeed, function(){
									if(typeof _animEnd === 'function') _animEnd();
								})
								// _slider.animate({ marginBottom: -slideHeight },{
									// queue: false, duration: _slideSpeed, complete: function(){
										// if(typeof _animEnd === 'function') _animEnd();
									// }
								// });
							}
						}
						if(_options.opener == ".btn-holder .btn"){
							jQuery(".next_big, .prev_big").animate({bottom: '60'},_slideSpeed);
						}
						_holder.removeClass(_activeClass);
					}
					else {

						if(_effect == 'fade'){
							_slider.fadeIn(_slideSpeed,function(){
								if(typeof _animEnd === 'function') _animEnd();
								_holder.addClass(_activeClass);
							});
						}
						else {
							if(diraction == 'horizontal'){
								if(leftToRight){
									_slider.css({ marginRight: -slideWidth, display: 'block' }).animate({ marginRight: 0 },{
										queue: false, duration: _slideSpeed, complete: function(){
											if(typeof _animEnd === 'function') _animEnd();
											_holder.addClass(_activeClass);
										}
									});
								}
								else {
									_slider.css({ marginLeft: -slideWidth, display: 'block' }).animate({ marginLeft: 0 },{
										queue: false, duration: _slideSpeed, complete: function(){
											if(typeof _animEnd === 'function') _animEnd();
											_holder.addClass(_activeClass);
										}
									});
								}
							}
							else {
								_slider.slideDown(_slideSpeed, function(){
									if(typeof _animEnd === 'function') _animEnd();
									_holder.addClass(_activeClass);
								});
								// _slider.css({ marginBottom: -slideHeight, display: 'block' }).animate({ marginBottom: 0 },{
									// queue: false, duration: _slideSpeed, complete: function(){
										// if(typeof _animEnd === 'function') _animEnd();
										// _holder.addClass(_activeClass);
									// }
								// });
							}
						}
					}
				}
				return false;
			});
			if(_holder.hasClass(_activeClass)) _slider.show();
			else _slider.hide();
			if(_options.outClickHide){
				jQuery('body').bind('click', function(e){
					if(_holder.hasClass(_activeClass)) {
						if(!jQuery(e.target).parents().is(_holder)){
							if(_effect == 'fade'){
								_slider.fadeOut(_slideSpeed,function(){
									if(typeof _animEnd === 'function') _animEnd();
								});
							}
							else {
								if(diraction == 'horizontal'){
									if(leftToRight){
										_slider.animate({ marginRight: -slideWidth },{
											queue: false, duration: _slideSpeed, complete: function(){
												if(typeof _animEnd === 'function') _animEnd();
											}
										});
									}
									else {
										_slider.animate({ marginLeft: -slideWidth },{
											queue: false, duration: _slideSpeed, complete: function(){
												if(typeof _animEnd === 'function') _animEnd();
											}
										});
									}
								}
								else {
									_slider.slideUp(_slideSpeed, function(){
										if(typeof _animEnd === 'function') _animEnd();
									})
									// _slider.animate({ marginBottom: -slideHeight },{
										// queue: false, duration: _slideSpeed, complete: function(){
											// _slider.hide();
											// if(typeof _animEnd === 'function') _animEnd();
										// }
									// });
								}
							}
							_holder.removeClass(_activeClass);
						}
					}
				});
			};
		}
	});
};

//Init main gallery
function initGallery(){
	jQuery('div.gallery').each(function(){
		var holder = jQuery(this);
		holder.NVcirclegallery({
			btnPrev:'a.prev',
			btnNext:'a.next',
			step: 5,
			afterAnim: function(){
				holder.find('img.grayscaled').each(function(){
					var image = jQuery(this);
					if(image.prev('canvas').length) {
						image.prev('canvas').remove()
						image.grayscale();
					}
				});
			}
		});
	})
};

jQuery.fn.NVcirclegallery = function($options){
	var $options = jQuery.extend({
		//Options plugin
		sliderHolder: '>div',
		slider: '>ul',
		slides: '>li',
		btnPrev: '.prev',
		btnNext: '.next',
		vertical: false,
		autorotate: false,
		hoverPause: true,
		speed: 650,
		easingEffect: '',
		swichTime: 2000,
		startPosition: 1,
		afterAnim: false,
		step: false
	},$options);

	return this.each(function(){
		var $this = jQuery(this);
		//Set options for plugins
		var sliderHolder = jQuery($options.sliderHolder, $this);
		if(!sliderHolder.length){
			sliderHolder = $this;
		};
		var slider = jQuery($options.slider, sliderHolder),
			slides = jQuery($options.slides, slider),
			btnPrev = jQuery($options.btnPrev, $this),
			btnNext = jQuery($options.btnNext, $this),
			vertical = $options.vertical,
			startPosition = $options.startPosition,
			step = $options.step,
			autorotate = $options.autorotate,
			hoverPause = $options.hoverPause,
			speed = $options.speed,
			swichTime = $options.swichTime,
			afterAnim = $options.afterAnim,
			easingEffect = $options.easingEffect,
			waitAnimation = false;
		if(!slider.length) return;
		var summHeight = 0,
			summWidth = 0,
			currentStep = 0,
			currentIndex,
			prevIndex,
			direction,
			stepCount,
			timer,
			pagerLink,
			slidesCount = slides.length,
			visibleCount = vertical ? Math.ceil(sliderHolder.height()/slides.outerHeight(true)) : Math.ceil(sliderHolder.width()/slides.outerWidth(true)),
			holdW = sliderHolder.width();
		
		// if(slidesCount <= visibleCount ) return;
		if(slides.hasClass('active')) currentIndex = slides.filter('.active:eq(0)').index();
		else currentIndex = 0;
		prevIndex = currentIndex;
		function recalc(){
			summHeight = 0;
			summWidth = 0;
			slides.each(function(){
				summWidth += jQuery(this).width() + parseInt(jQuery(this).css('padding-left')) + parseInt(jQuery(this).css('padding-right'));
				summHeight += jQuery(this).height() + parseInt(jQuery(this).css('padding-top')) + parseInt(jQuery(this).css('padding-bottom'));
			});
			stepCount = Math.ceil(summWidth/sliderHolder.width());
			if(vertical) slider.css({ height: summHeight });
			else slider.css({ width: summWidth });
		};
		recalc();
		jQuery(window).load(function(){
			recalc();
		});

		if(startPosition || startPosition > 1){
			for(var i = 0; i < startPosition-1; i++ ){
				slider.append(slides.eq(i).clone(true));
				slides.eq(i).remove();
			}
			slides = slider.children();
		};
		function initRecalc(){
			if(!$options.step){
				var _w = 0;
				var num = 0;
				slides.each(function(i){
					if(vertical){
						if(_w <= holdW && vertical){
							_w += slides.eq(i).outerHeight(true);
						}
					}
					else {
						if(_w <= holdW){
							num++;
							_w += slides.eq(i).outerWidth(true);
						}
					}
				});
				step = num-1;
			}
			waitAnimation = true;
			
			
			if(direction == 1){
				for(var i = 0; i < slidesCount-1; i++ ){
					if(i < step ){
						slider.append(slides.eq(i).clone(true));
						if(vertical) { currentStep += slides.eq(i).outerHeight(true) }
						else { currentStep += slides.eq(i).outerWidth(true) }
					}
				}
				if(vertical){ slider.css({ height: summHeight + currentStep }); }
				else { slider.css({ width: summWidth + currentStep }); }
			}
			else if(direction == -1){
				for( var i = slidesCount-1; i > 0; i-- ){
					if(i > slidesCount - 1 - step ){
						slider.prepend(slides.eq(i).clone(true));
						if(vertical) { currentStep += slides.eq(i).outerHeight(true); }
						else { currentStep += slides.eq(i).outerWidth(true); }
					}
				}
				if(vertical) {
					slider.css({ marginTop: -currentStep, height: summHeight + currentStep });
					currentStep = 0;
				}
				else {
					slider.css({ marginLeft: -currentStep, width: summWidth + currentStep });
					currentStep = 0;
				}
			}
			
		}
		function prevSlide(){
			if(waitAnimation) return false;
			direction = -1;
			initRecalc();
			animateSlider();
		}
		function nextSlide(){
			if(waitAnimation) return false;
			direction = 1;
			initRecalc();
			animateSlider();
		}
		btnPrev.bind('click', function(){
			if(!waitAnimation && summWidth > sliderHolder.width() ){
				if(timer) clearTimeout(timer)
				prevSlide();
			}
			return false;
		});
		btnNext.bind('click', function(){
/*
			console.log(summWidth , sliderHolder.width())
*/
			if(!waitAnimation && summWidth > sliderHolder.width()){
				if(timer) clearTimeout(timer)
				nextSlide();
			}
			return false;
		});
		function animateSlider(){
			var marginType = {};
			marginType[vertical ? 'marginTop' : 'marginLeft'] = -currentStep*direction;
			slider.animate(marginType, { queue: false, duration: speed, easing: easingEffect, complete: function(){
				if(direction == 1){
					slides.each(function(i, el){
						if(i < step ){
							slides.eq(i).remove();
						}
					})
				}
				else if(direction == -1){
					slides.each(function(i, el){
						if(i > slidesCount - step - 1 ){
							slides.eq(i).remove();
						}
					})
				}
				slides = slider.children();
				if(vertical){ slider.css({ marginTop: 0, height: summHeight }); }
				else { slider.css({ marginLeft: 0, width: summWidth }); }
				waitAnimation = false;
			}});
			currentStep = 0;
			if($options.autorotate) autorotate = true;
			autoSlide();
			if(afterAnim) afterAnim();
		};
		function autoSlide(){
			if(autorotate){
				if(timer) clearTimeout(timer);
				timer = setTimeout(nextSlide, swichTime)
			}
		};
		autoSlide();
		if(hoverPause){
			$this.hover(
				function(){ if(timer) clearTimeout(timer) },
				function(){ if($options.autorotate) autorotate = true; autoSlide(); }
			)
		}
	});
};

// image stretch module
backgroundStretcher = {
	images: [],
	holders: [],
	viewWidth: 0,
	viewHeight: 0,
	stretchByWindow: false, // or entire page
	init: function(){
		this.addHandlers();
		this.resizeAll();
		return this;
	},
	stretchImage: function(obj) {
		var img = new Image();
		img.onload = this.bind(function(){
			obj.iRatio = img.width / img.height;
			obj.iWidth = img.width;
			obj.iHeight = img.height;
			obj.style.visibility = "visible";   	
			obj.style.msInterpolationMode = 'bicubic'; // IE7 fix
			this.resizeImage(obj);
		});
		img.src = obj.src;
		this.images.push(obj);
	},
	setBgHolder: function(obj) {
		this.holders.push(obj);
		this.resizeAll();
	},
	resizeImage: function(obj) {
		if(obj.iRatio) {
			var slideWidth = this.viewWidth;
			var slideHeight = slideWidth / obj.iRatio;
			if(slideHeight < this.viewHeight) {
				slideHeight = this.viewHeight;
				slideWidth = slideHeight * obj.iRatio;
			}
			obj.style.width = slideWidth+'px';
			obj.style.height = slideHeight+'px';
			obj.style.visibility = "visible";
			//obj.style.marginLeft = "-"+(window.width - obj.style.width)/2+"px";	 			
			// obj.style.top = (this.viewHeight - slideHeight)/2+'px';
			// obj.style.left = (this.viewWidth - slideWidth)/2+'px';
		}
	},
	resizeHolder: function(obj) {
		obj.style.width = this.viewWidth+'px';
		obj.style.height = this.viewHeight+'px';
	},
	getWindowWidth: function() {
		return typeof window.innerWidth === 'number' ? window.innerWidth : document.documentElement.clientWidth;
	},
	getWindowHeight: function() {
		return typeof window.innerHeight === 'number' ? window.innerHeight : document.documentElement.clientHeight;
	},
	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)
		);
	},
	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)
		);
	},
	resizeAll: function() {
		// crop holder width by window size
		for(var i = 0; i < this.holders.length; i++) {
			this.holders[i].style.width = '100%'; 
		}
		
		// delay required for IE to handle resize
		clearTimeout(this.resizeTimer);
		this.resizeTimer = setTimeout(this.bind(function(){
			// hide background holders
			for(var i = 0; i < this.holders.length; i++) {
				this.holders[i].style.display = 'none';
			}
			
			// calculate real page dimensions with hidden background blocks
			this.viewWidth = this[this.stretchByWindow ? 'getWindowWidth' : 'getPageWidth']();
			this.viewHeight = this[this.stretchByWindow ? 'getWindowHeight' : 'getPageHeight']();
			
			// show and resize all background holders
			for(i = 0; i < this.holders.length; i++) {
				this.holders[i].style.display = 'block';
				this.resizeHolder(this.holders[i]);
			}
			for(i = 0; i < this.images.length; i++) {
				this.resizeImage(this.images[i]);
			}
			backgroundAdjust();

		}),10);
	},
	addHandlers: function() {
		if (window.addEventListener){
			 window.addEventListener('resize', this.bind(this.resizeAll), false);
			 window.addEventListener('orientationchange', this.bind(this.resizeAll), false);
		}
		else if (window.attachEvent){
			window.attachEvent('onresize', this.bind(this.resizeAll));
		}
	},
	bind: function(fn, scope, args) {
		var newScope = scope || this;
		return function() {
			return fn.apply(newScope, args || arguments);
		}
	} 
}.init();

/* initNavFix */
function initNavFix(){
	new touchNav({
		navBlock: 'nav'
	});
};

// 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], 'click', 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);
		}
	}
}

/* initAddClass */
function initAddClass() {
addClass({
tagName:'a',
tagClass:'more-link',
classAdd:'div-active',
addToParent:true
})
}
function addClass (_options) {
var _tagName = _options.tagName;
var _tagClass = _options.tagClass;
var _classAdd = _options.classAdd;
var _addToParent = false || _options.addToParent;
var _el = document.getElementsByTagName(_tagName);
if (_el) {
for (var i=0; i < _el.length; i++) {
if (_el[i].className.indexOf(_tagClass) != -1) {
_el[i].onclick = function() {
if (_addToParent) {
if (this.parentNode.className.indexOf(_classAdd) == -1) {
this.parentNode.className += ' '+_classAdd;
} else {
this.parentNode.className = this.parentNode.className.replace(_classAdd,'');
}
} else {
if (this.className.indexOf(_classAdd) == -1) {
this.className += ' '+_classAdd;
} else {
this.className = this.className.replace(_classAdd,'');
}
}
return false;
}
}
}
}
};

// mobile
var mobi = ['opera', 'iemobile', 'webos', 'android', 'iphone', 'ipad'];
var midp = ['blackberry', 'symbian'];
var ua = navigator.userAgent.toLowerCase();
var desktop = '';
if ((ua.indexOf('midp') != -1) || (ua.indexOf('mobi') != -1) || ((ua.indexOf('ppc') != -1) && (ua.indexOf('mac') == -1)) || (ua.indexOf('webos') != -1)) {
	document.write('<link rel="stylesheet" href="css/allmobile.css" type="text/css" media="all"/>');
	if (ua.indexOf('midp') != -1) {
		for (var i = 0; i < midp.length; i++) {
			if (ua.indexOf(midp[i]) != -1) {
				document.write('<link rel="stylesheet" href="css/' + midp[i] + '.css" type="text/css"/>');
				document.write('<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />');
			}
		}
	}
	else {
		if ((ua.indexOf('mobi') != -1) || (ua.indexOf('ppc') != -1) || (ua.indexOf('webos') != -1)) {
			for (var i = 0; i < mobi.length; i++) {
				if (ua.indexOf(mobi[i]) != -1) {
					document.write('<link rel="stylesheet" href="css/' + mobi[i] + '.css" type="text/css"/>');
					document.write('<meta name="viewport" content="width=device-width"/>');
					break;
				}
			}
		}
	}
}
else {
	document.write(desktop);
}

var VSA_scrollAreas = new Array();
var VSA_default_imagesPath = "images";
var VSA_default_btnUpImage = "button-up.gif";
var VSA_default_btnDownImage = "button-down.gif";
var VSA_default_scrollStep = 5;
var VSA_default_wheelSensitivity = 10;
var VSA_default_scrollbarPosition = 'right';//'left','right','inline';
var VSA_default_scrollButtonHeight = 22;
var VSA_default_scrollbarWidth = 43;
var VSA_resizeTimer = 2000;
var VSA_touchFlag = isTouchDevice(); // true/false - move scroll with scrollable body

function remove_home_flash_intro(){
	acabou_o_flash = true;
	var slideshow;
	var delay = 100;
	var animSpeed = 200;
	/* home page animation */
	if(jQuery('body').hasClass('home-page')){
		jQuery('#nav > li').not("li:first").each(function(idx){
			if(jQuery(this).attr('title')){
				jQuery(this).attr('slideNumNav',jQuery(this).attr('title')).removeAttr('title');
				jQuery(this).bind('mouseenter', function(){
					clearTimeout(slideshow.timer);
					if(jQuery('.bg-gallery').find('li').filter('[slideNum= ' + jQuery(this).attr('slideNumNav') + ']').is(':hidden')){
						slideshow.prevSlide = slideshow.nextSlide;
						slideshow.nextSlide = jQuery('.bg-gallery').find('li').filter('[slideNum= ' + jQuery(this).attr('slideNumNav') + ']').index();
						slideshow.swichSlide(slideshow.prevSlide, slideshow.nextSlide);
						slideshow.swichTime = false; 
					};
				}).bind('mouseleave', function(){
					slideshow.autoRotation();
				});
			};
		});
		// jQuery('.text-box .more-link').bind('click', function(){
		// 			clearTimeout(slideshow.timer);
		// 			slideshow.swichTime = false;
		// 		});
	};
	jQuery('.bg-gallery').each(function(){
		var set = jQuery(this);
		var slides = set.find('li');
		slides.each(function(){
			if(jQuery(this).attr('rel')) jQuery(this).attr('slideNum',jQuery(this).attr('rel')).removeAttr('rel');
		});                     
		slideshow = new initSlidesNV(set,{
			list: '>ul',
			swichTime: false, //5000,			
			onStart: function(obj, list, slides, next){
				slides.css({ position: 'absolute', top: 0, left: 0 });
				if(jQuery('#nav > li').filter('[slideNumNav= ' + slides.eq(next).attr('slideNum') + ']').length){
					jQuery('#nav > li').removeClass('active-slideshow');
					jQuery('#nav > li').filter('[slideNumNav= ' + slides.eq(next).attr('slideNum') + ']').addClass('active-slideshow');
				}
			},
			afterAnimation: function(obj, list, slides, next){
				if(jQuery('#nav > li').filter('[slideNumNav= ' + slides.eq(next).attr('slideNum') + ']').length){
					jQuery('#nav > li').removeClass('active-slideshow');
					jQuery('#nav > li').filter('[slideNumNav= ' + slides.eq(next).attr('slideNum') + ']').addClass('active-slideshow');
				}
			}
		});
	});
	jQuery("#flash_intro").fadeOut("slow").remove();
}	

function VSA_initScrollbars() {
	if(!document.body.children) return;
	var scrollElements = VSA_getElements("vscrollable", "DIV", document, "class");
	for (var i=0; i<scrollElements.length; i++)
	{
		VSA_scrollAreas[i] = new VScrollArea(i, scrollElements[i]);
	}
}

function isTouchDevice() {
	try {
		document.createEvent("TouchEvent");
		return true;
	} catch (e) {
		return false;
	}
}

function touchHandler(event) {
	var touches = event.changedTouches, first = touches[0], type = "";
	switch(event.type) {
		case "touchstart": type = "mousedown"; break;
		case "touchmove":  type = "mousemove"; break;
		case "touchend":   type = "mouseup"; break;
		default: return;
	}
	var simulatedEvent = document.createEvent("MouseEvent");
	simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null);
	first.target.dispatchEvent(simulatedEvent);
	event.preventDefault();
}

function VScrollArea(index, elem) //constructor
{
	this.index = index;
	this.element = elem;

	var attr = this.element.getAttribute("imagesPath");
	this.imagesPath = attr ? attr : VSA_default_imagesPath;

	attr = this.element.getAttribute("btnUpImage");
	this.btnUpImage = attr ? attr : VSA_default_btnUpImage;

	attr = this.element.getAttribute("btnDownImage");
	this.btnDownImage = attr ? attr : VSA_default_btnDownImage;

	attr = Number(this.element.getAttribute("scrollStep"));
	this.scrollStep = attr ? attr : VSA_default_scrollStep;

	attr = Number(this.element.getAttribute("wheelSensitivity"));
	this.wheelSensitivity = attr ? attr : VSA_default_wheelSensitivity;

	attr = this.element.getAttribute("scrollbarPosition");
	this.scrollbarPosition = attr ? attr : VSA_default_scrollbarPosition;
	
	attr = this.element.getAttribute("scrollButtonHeight");
	this.scrollButtonHeight = attr ? attr : VSA_default_scrollButtonHeight;

	attr = this.element.getAttribute("scrollbarWidth");
	this.scrollbarWidth = attr ? attr : VSA_default_scrollbarWidth;

	this.scrolling = false;

	this.iOffsetY = 0;
	this.scrollHeight = 0;
	this.scrollContent = null;
	this.scrollbar = null;
	this.scrollup = null;
	this.scrolldown = null;
	this.scrollslider = null;
	this.scroll = null;
	this.enableScrollbar = false;
	this.scrollFactor = 1;
	this.scrollingLimit = 0;
	this.topPosition = 0;

	//functions declaration
	this.init = VSA_init;
	this.scrollUp = VSA_scrollUp;
	this.scrollDown = VSA_scrollDown;
	this.createScrollBar = VSA_createScrollBar;
	this.scrollIt = VSA_scrollIt;

	this.init();
}

function VSA_init() {
	this.scrollContent = document.createElement("DIV");
	this.scrollContent.style.position = "absolute";
	this.scrollContent.style.overflow = "hidden";
	this.scrollContent.style.width = this.element.offsetWidth + "px";
	this.scrollContent.style.height = this.element.offsetHeight + "px";

	while(this.element.childNodes.length) this.scrollContent.appendChild(this.element.childNodes[0]);

	this.element.style.overflow = "hidden";
	this.element.style.display = "block";
	this.element.style.visibility = "visible";
	this.element.style.position = "relative";
	this.element.appendChild(this.scrollContent);

	this.scrollContent.className = 'scroll-content';

	this.element.index = this.index;
	this.element.over = false;
	
	var _this = this;

	if(document.all && !window.opera) {
		this.element.onmouseenter = function(){_this.element.over = true;};
		this.element.onmouseleave = function(){_this.element.over = false;}
	} else {
		this.element.onmouseover = function(){_this.element.over = true;};
		this.element.onmouseout = function(){_this.element.over = false;}
	}

	if (document.all)
	{
		this.element.onscroll = VSA_handleOnScroll;
		this.element.onresize = VSA_handleResize;
	}
	else
	{
		window.onresize = VSA_handleResize;
	}
	
	this.createScrollBar();
	
	if (window.addEventListener) {
		/* DOMMouseScroll is for mozilla. */
		this.element.addEventListener('DOMMouseScroll', VSA_handleMouseWheel, false);
	}
	/* IE/Opera. */
	this.element.onmousewheel = document.onmousewheel = VSA_handleMouseWheel;

	// move content by touch
	if(VSA_touchFlag) {
		_this.scrollContent.onmousedown = function(e) {
			var startY = e.pageY-getRealTop(_this.scrollContent);
			var origTop = _this.scrollContent.scrollTop;
			_this.scrollContent.onmousemove = function(e) {
				var moveY = e.pageY-getRealTop(_this.scrollContent);
				var iNewY = origTop-(moveY-startY);
				if(iNewY < 0) iNewY = 0;
				if(iNewY > _this.scrollContent.scrollHeight) iNewY = _this.scrollContent.scrollHeight;
				_this.scrollContent.scrollTop = iNewY;
				_this.scrollslider.style.top =  1 / _this.scrollFactor * Math.abs(_this.scrollContent.scrollTop) + _this.scrollButtonHeight + "px";
			}
		}
		_this.scrollContent.onmouseup = function(e) {
			_this.scrollContent.onmousemove = null;
		}
		this.scrollContent.addEventListener("touchstart", touchHandler, true);
		this.scrollContent.addEventListener("touchmove", touchHandler, true);
		this.scrollContent.addEventListener("touchend", touchHandler, true);
	}
}

function VSA_createScrollBar()
{
	if (this.scrollbar != null)
	{
		this.element.removeChild(this.scrollbar);
		this.scrollbar = null;
	}
	
	if (this.scrollContent.scrollHeight <= this.scrollContent.offsetHeight)
		this.enableScrollbar = false;
	else if (this.element.offsetHeight > 2*this.scrollButtonHeight)
		this.enableScrollbar = true;
	else
		this.enableScrollbar = false;

	if (this.scrollContent.scrollHeight - Math.abs(this.scrollContent.scrollTop) < this.element.offsetHeight)
		this.scrollContent.style.top = 0;

	if (this.enableScrollbar)
	{
		this.scrollbar = document.createElement("DIV");
		this.element.appendChild(this.scrollbar);
		this.scrollbar.style.position = "absolute";
		this.scrollbar.style.top = "0px";
		this.scrollbar.style.height = this.element.offsetHeight+"px";
		this.scrollbar.style.width = this.scrollbarWidth + "px";

		this.scrollbar.className = 'vscroll-bar';

		if(this.scrollbarWidth != this.scrollbar.offsetWidth)
		{
			this.scrollbarWidth = this.scrollbar.offsetHeight;
		}
		
		this.scrollbarWidth = this.scrollbar.offsetWidth;

		if(this.scrollbarPosition == 'left')
		{
			this.scrollContent.style.left = this.scrollbarWidth + 5 + "px";
			this.scrollContent.style.width = this.element.offsetWidth - this.scrollbarWidth - 5 + "px";
		}
		else if(this.scrollbarPosition == 'right')
		{
			this.scrollbar.style.left = this.element.offsetWidth - this.scrollbarWidth  + "px";
			this.scrollContent.style.width = this.element.offsetWidth - this.scrollbarWidth - 5 + "px";
		}

		//create scroll up button
		this.scrollup = document.createElement("DIV");
		this.scrollup.index = this.index;
		this.scrollup.onmousedown = VSA_handleBtnUpMouseDown;
		this.scrollup.onmouseup = VSA_handleBtnUpMouseUp;
		this.scrollup.onmouseout = VSA_handleBtnUpMouseOut;
		
		if(VSA_touchFlag) {
			this.scrollup.addEventListener("touchstart", touchHandler, true);
			this.scrollup.addEventListener("touchend", touchHandler, true);
		}
		
		this.scrollup.style.position = "absolute";
		this.scrollup.style.top = "0px";
		this.scrollup.style.left = "0px";
		this.scrollup.style.height = this.scrollButtonHeight + "px";
		this.scrollup.style.width = this.scrollbarWidth + "px";
		
		this.scrollup.innerHTML = '<img src="' + this.imagesPath + '/' + this.btnUpImage + '" border="0"/>';
		this.scrollbar.appendChild(this.scrollup);

		this.scrollup.className = 'vscroll-up';

		if(this.scrollButtonHeight != this.scrollup.offsetHeight)
		{
			this.scrollButtonHeight = this.scrollup.offsetHeight;
		}
		
		//create scroll down button
		this.scrolldown = document.createElement("DIV");
		this.scrolldown.index = this.index;
		this.scrolldown.onmousedown = VSA_handleBtnDownMouseDown;
		this.scrolldown.onmouseup = VSA_handleBtnDownMouseUp;
		this.scrolldown.onmouseout = VSA_handleBtnDownMouseOut;
		
		if(VSA_touchFlag) {
			this.scrolldown.addEventListener("touchstart", touchHandler, true);
			this.scrolldown.addEventListener("touchend", touchHandler, true);
		}
		
		this.scrolldown.style.position = "absolute";
		this.scrolldown.style.left = "0px";
		this.scrolldown.style.top =  this.scrollbar.offsetHeight - this.scrollButtonHeight + "px";
		this.scrolldown.style.width = this.scrollbarWidth + "px";
		this.scrolldown.innerHTML = '<img src="' + this.imagesPath + '/' + this.btnDownImage + '" border="0"/>';
		this.scrollbar.appendChild(this.scrolldown);

		this.scrolldown.className = 'vscroll-down';

		//create scroll
		this.scroll = document.createElement("DIV");
		this.scroll.index = this.index;
		this.scroll.style.position = "absolute";
		this.scroll.style.zIndex = 0;
		this.scroll.style.textAlign = "center";
		this.scroll.style.top = this.scrollButtonHeight + "px";
		this.scroll.style.left = "0px";
		this.scroll.style.width = this.scrollbarWidth + "px";
		
		var h = this.scrollbar.offsetHeight - 2*this.scrollButtonHeight;
		this.scroll.style.height = ((h > 0) ? h : 0) + "px";
		
		this.scroll.innerHTML = '';
		this.scroll.onclick = VSA_handleScrollbarClick;
		this.scrollbar.appendChild(this.scroll);
		this.scroll.style.overflow = "hidden";

		this.scroll.className = "vscroll-line";

		//create slider
		this.scrollslider = document.createElement("DIV");
		this.scrollslider.index = this.index;
		this.scrollslider.style.position = "absolute";
		this.scrollslider.style.zIndex = 1000;
		this.scrollslider.style.textAlign = "center";
		this.scrollslider.innerHTML = '<div id="vscrollslider' + this.index + '" style="padding:0;margin:0;"><div class="scroll-bar-top"></div><div class="scroll-bar-bottom"></div></div>';
		this.scrollbar.appendChild(this.scrollslider);
		
		this.subscrollslider = document.getElementById("vscrollslider"+this.index);
		this.subscrollslider.style.height = Math.round((this.scrollContent.offsetHeight/this.scrollContent.scrollHeight)*(this.scrollbar.offsetHeight - 2*this.scrollButtonHeight)) + "px";
		
		this.scrollslider.className = "vscroll-slider";
		
		this.scrollHeight = this.scrollbar.offsetHeight - 2*this.scrollButtonHeight - this.scrollslider.offsetHeight;
		this.scrollFactor = (this.scrollContent.scrollHeight - this.scrollContent.offsetHeight)/this.scrollHeight;
		this.topPosition = getRealTop(this.scrollbar) + this.scrollButtonHeight;
		/* this.scrollbarHeight = this.scrollbar.offsetHeight - 2*this.scrollButtonHeight - this.scrollslider.offsetHeight; */

		this.scrollslider.style.top = /* 1 / this.scrollFactor * Math.abs(this.scrollContent.offsetTop) +*/ this.scrollButtonHeight + "px";
		this.scrollslider.style.left = "0px";
		this.scrollslider.style.width = "100%";
		this.scrollslider.onmousedown = VSA_handleSliderMouseDown;
		if(VSA_touchFlag) {
			this.scrollslider.addEventListener("touchstart", touchHandler, true);
		}
		if (document.all)
			this.scrollslider.onmouseup = VSA_handleSliderMouseUp;
	}
	else
		this.scrollContent.style.width = this.element.offsetWidth + "px";
}

function VSA_handleBtnUpMouseDown()
{
	var sa = VSA_scrollAreas[this.index];
	sa.scrolling = true;
	sa.scrollUp();
}

function VSA_handleBtnUpMouseUp()
{
	VSA_scrollAreas[this.index].scrolling = false;
}

function VSA_handleBtnUpMouseOut()
{
	VSA_scrollAreas[this.index].scrolling = false;
}

function VSA_handleBtnDownMouseDown()
{
	var sa = VSA_scrollAreas[this.index];
	sa.scrolling = true;
	sa.scrollDown();
}

function VSA_handleBtnDownMouseUp()
{
	VSA_scrollAreas[this.index].scrolling = false;
}

function VSA_handleBtnDownMouseOut()
{
	VSA_scrollAreas[this.index].scrolling = false;
}

function VSA_scrollIt()
{
	this.scrollContent.scrollTop = this.scrollFactor * ((this.scrollslider.offsetTop + this.scrollslider.offsetHeight/2) - this.scrollButtonHeight - this.scrollslider.offsetHeight/2);
}

function VSA_scrollUp()
{
	if (this.scrollingLimit > 0)
	{
		this.scrollingLimit--;
		if (this.scrollingLimit == 0) this.scrolling = false;
	}
	if (!this.scrolling) return;
	if ( this.scrollContent.scrollTop - this.scrollStep > 0)
	{
		this.scrollContent.scrollTop -= this.scrollStep;
		this.scrollslider.style.top = 1 / this.scrollFactor * Math.abs(this.scrollContent.scrollTop) + this.scrollButtonHeight + "px";
	}
	else
	{
		this.scrollContent.scrollTop = "0";
		this.scrollslider.style.top = this.scrollButtonHeight + "px";
		return;
	}
	setTimeout("VSA_Ext_scrollUp(" + this.index + ")", 30);
}

function VSA_Ext_scrollUp(index)
{
	VSA_scrollAreas[index].scrollUp();
}

function VSA_scrollDown()
{
	if (this.scrollingLimit > 0)
	{
		this.scrollingLimit--;
		if (this.scrollingLimit == 0) this.scrolling = false;
	}
	if (!this.scrolling) return;


	this.scrollContent.scrollTop += this.scrollStep;
	this.scrollslider.style.top =  1 / this.scrollFactor * Math.abs(this.scrollContent.scrollTop) + this.scrollButtonHeight + "px";

	if (this.scrollContent.scrollTop >= (this.scrollContent.scrollHeight - this.scrollContent.offsetHeight))
	{
		this.scrollContent.scrollTop = (this.scrollContent.scrollHeight - this.scrollContent.offsetHeight);
		this.scrollslider.style.top = this.scrollbar.offsetHeight - this.scrollButtonHeight - this.scrollslider.offsetHeight + "px";
		return;
	}

	setTimeout("VSA_Ext_scrollDown(" + this.index + ")", 30);
}

function VSA_Ext_scrollDown(index)
{
	VSA_scrollAreas[index].scrollDown();
}

function VSA_handleMouseMove(evt)
{
	var sa = VSA_scrollAreas[((document.all && !window.opera) ? this.index : document.documentElement.scrollAreaIndex)];
	var posy = 0;
	if (!evt) var evt = window.event;
	
	if (evt.pageY)
		posy = evt.pageY;
	else if (evt.clientY)
		posy = evt.clientY;
			
		if (document.all && !window.opera)
		{
			if(!document.addEventListener) {
				posy += document.documentElement.scrollTop;
			}
		}

	var iNewY = posy - sa.iOffsetY - getRealTop(sa.scrollbar) - sa.scrollButtonHeight;
		iNewY += sa.scrollButtonHeight;
		
	if (iNewY < sa.scrollButtonHeight)
		iNewY = sa.scrollButtonHeight;
	if (iNewY > (sa.scrollbar.offsetHeight - sa.scrollButtonHeight) - sa.scrollslider.offsetHeight)
		iNewY = (sa.scrollbar.offsetHeight - sa.scrollButtonHeight) - sa.scrollslider.offsetHeight;

	sa.scrollslider.style.top = iNewY + "px";

	sa.scrollIt();
}

function VSA_handleSliderMouseDown(evt)
{
	if (!(document.uniqueID && document.compatMode && !window.XMLHttpRequest))
	{
		document.onselectstart = function() { return false; }
		document.onmousedown = function() { return false; }
	}

	var sa = VSA_scrollAreas[this.index];
	if (document.all && !window.opera)
	{
		sa.scrollslider.setCapture()
		sa.iOffsetY = event.offsetY;
		sa.scrollslider.onmousemove = VSA_handleMouseMove;
		if(VSA_touchFlag) {
			sa.scrollslider.addEventListener("touchmove", touchHandler, true);
		}
	}
	else
	{
		if(window.opera)
		{
			sa.iOffsetY = event.offsetY;
		}
		else
		{
			sa.iOffsetY = evt.layerY;
		}
		document.documentElement.scrollAreaIndex = sa.index;
		document.documentElement.addEventListener("mousemove", VSA_handleMouseMove, true);
		document.documentElement.addEventListener("mouseup", VSA_handleSliderMouseUp, true);
		if(VSA_touchFlag) {
			document.documentElement.addEventListener("touchmove", touchHandler, true);
			document.documentElement.addEventListener("touchend", touchHandler, true);
		}
	}
	return false;
}

function VSA_handleSliderMouseUp()
{
	if (!(document.uniqueID && document.compatMode && !window.XMLHttpRequest))
	{
		document.onmousedown = null;
		document.onselectstart = null;
	}

	if (document.all && !window.opera)
	{
		var sa = VSA_scrollAreas[this.index];
		sa.scrollslider.onmousemove = null;
		sa.scrollslider.releaseCapture();
		sa.scrollIt();
	}
	else
	{
		var sa = VSA_scrollAreas[document.documentElement.scrollAreaIndex];
		document.documentElement.removeEventListener("mousemove", VSA_handleMouseMove, true);
		document.documentElement.removeEventListener("mouseup", VSA_handleSliderMouseUp, true);
		if(VSA_touchFlag) {
			document.documentElement.removeEventListener("touchmove", touchHandler, true);
			document.documentElement.removeEventListener("touchend", touchHandler, true);
		}
		sa.scrollIt();
	}
	return false;
}

function VSA_handleResize()
{
	if (VSA_resizeTimer)
	{
		clearTimeout(VSA_resizeTimer);
		VSA_resizeTimer = 0;
	}
	VSA_resizeTimer = setTimeout("VSA_performResizeEvent()", 100);
}

function VSA_performResizeEvent()
{
	for (var i=0; i<VSA_scrollAreas.length; i++)
		VSA_scrollAreas[i].createScrollBar();
}
function VSA_handleMouseWheel(event){
	if (this.index != null) {
		var sa = VSA_scrollAreas[this.index];
		if (sa.scrollbar == null) return;
		sa.scrolling = true;
		sa.scrollingLimit = sa.wheelSensitivity;

		var delta = 0;
		if (!event) /* For IE. */
			event = window.event;
		if (event.wheelDelta) { /* IE/Opera. */
			delta = event.wheelDelta/120;
			/*if (window.opera) delta = -delta;*/
		} else if (event.detail) { /* Mozilla case. */
			delta = -event.detail/3;
		}

		if (delta && sa.element.over) {
			if (delta > 0) {
				sa.scrollUp();
			} else {
				sa.scrollDown();
			}
			if (event.preventDefault) {
				event.preventDefault();
			}
			event.returnValue = false;
		}
	}
}

function VSA_handleSelectStart()
{
	event.returnValue = false;
}

function VSA_handleScrollbarClick(evt)
{
	var sa = VSA_scrollAreas[this.index];
	var offsetY = (document.all ? event.offsetY : evt.layerY);

	if (offsetY < (sa.scrollButtonHeight + sa.scrollslider.offsetHeight/2))
		sa.scrollslider.style.top = sa.scrollButtonHeight + "px";
	else if (offsetY > (sa.scrollbar.offsetHeight - sa.scrollButtonHeight - sa.scrollslider.offsetHeight))
		sa.scrollslider.style.top = sa.scrollbar.offsetHeight - sa.scrollButtonHeight - sa.scrollslider.offsetHeight + "px";
	else
	{
		sa.scrollslider.style.top = offsetY + sa.scrollButtonHeight - sa.scrollslider.offsetHeight/2 + "px";
	}
	sa.scrollIt();
}

function VSA_handleOnScroll()
{
	//event.srcElement.doScroll("pageUp");
}

//--- common functions ----

function VSA_getElements(attrValue, tagName, ownerNode, attrName) //get Elements By Attribute Name
{
	if (!tagName) tagName = "*";
	if (!ownerNode) ownerNode = document;
	if (!attrName) attrName = "name";
	var result = [];
	var nl = ownerNode.getElementsByTagName(tagName);
	for (var i=0; i<nl.length; i++)
	{
	//	if (nl.item(i).getAttribute(attrName) == attrValue)
//		result.push(nl.item(i));
		if (nl.item(i).className.indexOf(attrValue) != -1)
		result.push(nl.item(i));
	}
	return result;
}

function getRealTop(obj) {
	if (obj.getBoundingClientRect) {
		var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
		var clientTop = document.documentElement.clientTop || document.body.clientTop || 0;
		return Math.round(obj.getBoundingClientRect().top + scrollTop - clientTop);
	} else {
		var posTop = 0;
		while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
		return posTop;
	}
};



/*
 * touchSwipe - jQuery Plugin
 * http://plugins.jquery.com/project/touchSwipe
 * http://labs.skinkers.com/touchSwipe/
 *
 * Copyright (c) 2010 Matt Bryson (www.skinkers.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * $version: 1.2.3
 *
 * Changelog
 * $Date: 2010-12-12 (Wed, 12 Dec 2010) $
 * $version: 1.0.0 
 * $version: 1.0.1 - removed multibyte comments
 *
 * $Date: 2011-21-02 (Mon, 21 Feb 2011) $
 * $version: 1.1.0 	- added allowPageScroll property to allow swiping and scrolling of page
 *					- changed handler signatures so one handler can be used for multiple events
 * $Date: 2011-23-02 (Wed, 23 Feb 2011) $
 * $version: 1.2.0 	- added click handler. This is fired if the user simply clicks and does not swipe. The event object and click target are passed to handler.
 *					- If you use the http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ plugin, you can also assign jQuery mouse events to children of a touchSwipe object.
 * $version: 1.2.1 	- removed console log!
 *
 * $version: 1.2.2 	- Fixed bug where scope was not preserved in callback methods. 
 *
 * $Date: 2011-28-04 (Thurs, 28 April 2011) $
 * $version: 1.2.4 	- Changed licence terms to be MIT or GPL inline with jQuery. Added check for support of touch events to stop non compatible browsers erroring.
 *
 * A jQuery plugin to capture left, right, up and down swipes on touch devices.
 * You can capture 2 finger or 1 finger swipes, set the threshold and define either a catch all handler, or individual direction handlers.
 * Options:
 * 		swipe 		Function 	A catch all handler that is triggered for all swipe directions. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeLeft	Function 	A handler that is triggered for "left" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeRight	Function 	A handler that is triggered for "right" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeUp		Function 	A handler that is triggered for "up" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeDown	Function 	A handler that is triggered for "down" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 *		swipeStatus Function 	A handler triggered for every phase of the swipe. Handler is passed 4 arguments: event : The original event object, phase:The current swipe face, either "start”, "move”, "end” or "cancel”. direction : The swipe direction, either "up”, "down”, "left " or "right”.distance : The distance of the swipe.
 *		click		Function	A handler triggered when a user just clicks on the item, rather than swipes it. If they do not move, click is triggered, if they do move, it is not.
 *
 * 		fingers 	int 		Default 1. 	The number of fingers to trigger the swipe, 1 or 2.
 * 		threshold 	int  		Default 75.	The number of pixels that the user must move their finger by before it is considered a swipe.
 *		triggerOnTouchEnd Boolean Default true If true, the swipe events are triggered when the touch end event is received (user releases finger).  If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
 *		allowPageScroll String Default "auto". How the browser handles page scrolls when the user is swiping on a touchSwipe object. 
 *										"auto" : all undefined swipes will cause the page to scroll in that direction.
 *										"none" : the page will not scroll when user swipes.
 *										"horizontal" : will force page to scroll on horizontal swipes.
 *										"vertical" : will force page to scroll on vertical swipes.
 *
 * This jQuery plugin will only run on devices running Mobile Webkit based browsers (iOS 2.0+, android 2.2+)
 */
(function($) 
{
	
	
	
	$.fn.swipe = function(options) 
	{
		if (!this) return false;
		
		// Default thresholds & swipe functions
		var defaults = {
					
			fingers 		: 1,								// int - The number of fingers to trigger the swipe, 1 or 2. Default is 1.
			threshold 		: 75,								// int - The number of pixels that the user must move their finger by before it is considered a swipe. Default is 75.
			
			swipe 			: null,		// Function - A catch all handler that is triggered for all swipe directions. Accepts 2 arguments, the original event object and the direction of the swipe : "left", "right", "up", "down".
			swipeLeft		: null,		// Function - A handler that is triggered for "left" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeRight		: null,		// Function - A handler that is triggered for "right" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeUp			: null,		// Function - A handler that is triggered for "up" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeDown		: null,		// Function - A handler that is triggered for "down" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeStatus		: null,		// Function - A handler triggered for every phase of the swipe. Handler is passed 4 arguments: event : The original event object, phase:The current swipe face, either "start”, "move”, "end” or "cancel”. direction : The swipe direction, either "up”, "down”, "left " or "right”.distance : The distance of the swipe.
			click			: null,		// Function	- A handler triggered when a user just clicks on the item, rather than swipes it. If they do not move, click is triggered, if they do move, it is not.
			
			triggerOnTouchEnd : true,	// Boolean, if true, the swipe events are triggered when the touch end event is received (user releases finger).  If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
			allowPageScroll : "auto" 	/* How the browser handles page scrolls when the user is swiping on a touchSwipe object. 
											"auto" : all undefined swipes will cause the page to scroll in that direction.
 											"none" : the page will not scroll when user swipes.
 											"horizontal" : will force page to scroll on horizontal swipes.
 											"vertical" : will force page to scroll on vertical swipes.
										*/
		};
		
		
		//Constants
		var LEFT = "left";
		var RIGHT = "right";
		var UP = "up";
		var DOWN = "down";
		var NONE = "none";
		var HORIZONTAL = "horizontal";
		var VERTICAL = "vertical";
		var AUTO = "auto";
		
		var PHASE_START="start";
		var PHASE_MOVE="move";
		var PHASE_END="end";
		var PHASE_CANCEL="cancel";
		
		
		
		var phase="start";
		
		if (options.allowPageScroll==undefined && (options.swipe!=undefined || options.swipeStatus!=undefined))
			options.allowPageScroll=NONE;
		
		if (options)
			$.extend(defaults, options);
		
		
		/**
		 * Setup each object to detect swipe gestures
		 */
		return this.each(function() 
		{
			var $this = $(this);
			
			var triggerElementID = null; 	// this variable is used to identity the triggering element
			var fingerCount = 0;			// the current number of fingers being used.	
			
			//track mouse points / delta
			var start={x:0, y:0};
			var end={x:0, y:0};
			var delta={x:0, y:0};
			
			
			/**
			* Event handler for a touch start event. 
			* Stops the default click event from triggering and stores where we touched
			*/
			function touchStart(event) 
			{
				phase = PHASE_START;
		
				// get the total number of fingers touching the screen
				fingerCount = event.touches.length;
				
				//clear vars..
				distance=0;
				direction=null;
				
				// check the number of fingers is what we are looking for
				if ( fingerCount == defaults.fingers ) 
				{
					// get the coordinates of the touch
					start.x = end.x = event.touches[0].pageX;
					start.y = end.y = event.touches[0].pageY;
					
					if (defaults.swipeStatus)
						triggerHandler(event, phase);
				} 
				else 
				{
					//touch with more/less than the fingers we are looking for
					touchCancel(event);
				}
			}

			/**
			* Event handler for a touch move event. 
			* If we change fingers during move, then cancel the event
			*/
			function touchMove(event) 
			{
				if (phase == PHASE_END || phase == PHASE_CANCEL)
					return;
				
				end.x = event.touches[0].pageX;
				end.y = event.touches[0].pageY;
					
				direction = caluculateDirection();
				fingerCount = event.touches.length;
				
				phase = PHASE_MOVE
				
				//Check if we need to prevent default evnet (page scroll) or not
				validateDefaultEvent(event, direction);
		
				if ( fingerCount == defaults.fingers ) 
				{
					distance = caluculateDistance();
					
					if (defaults.swipeStatus)
						triggerHandler(event, phase, direction, distance);
					
					//If we trigger whilst dragging, not on touch end, then calculate now...
					if (!defaults.triggerOnTouchEnd)
					{
						// if the user swiped more than the minimum length, perform the appropriate action
						if ( distance >= defaults.threshold ) 
						{
							phase = PHASE_END;
							triggerHandler(event, phase);
							touchCancel(event); // reset the variables
						}
					}
				} 
				else 
				{
					phase = PHASE_CANCEL;
					triggerHandler(event, phase); 
					touchCancel(event);
				}
			}
			
			/**
			* Event handler for a touch end event. 
			* Calculate the direction and trigger events
			*/
			function touchEnd(event) 
			{
				event.preventDefault();
				
				distance = caluculateDistance();
				direction = caluculateDirection();
						
				if (defaults.triggerOnTouchEnd)
				{
					phase = PHASE_END;
					// check to see if more than one finger was used and that there is an ending coordinate
					if ( fingerCount == defaults.fingers && end.x != 0 ) 
					{
						// if the user swiped more than the minimum length, perform the appropriate action
						if ( distance >= defaults.threshold ) 
						{
							triggerHandler(event, phase);
							touchCancel(event); // reset the variables
						} 
						else 
						{
							phase = PHASE_CANCEL;
							triggerHandler(event, phase); 
							touchCancel(event);
						}	
					} 
					else 
					{
						phase = PHASE_CANCEL;
						triggerHandler(event, phase); 
						touchCancel(event);
					}
				}
				else if (phase == PHASE_MOVE)
				{
					phase = PHASE_CANCEL;
					triggerHandler(event, phase); 
					touchCancel(event);
				}
			}
			
			/**
			* Event handler for a touch cancel event. 
			* Clears current vars
			*/
			function touchCancel(event) 
			{
				// reset the variables back to default values
				fingerCount = 0;
				
				start.x = 0;
				start.y = 0;
				end.x = 0;
				end.y = 0;
				delta.x = 0;
				delta.y = 0;
			}
			
			
			/**
			* Trigger the relevant event handler
			* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
			*/
			function triggerHandler(event, phase) 
			{
				//update status
				if (defaults.swipeStatus)
					defaults.swipeStatus.call($this,event, phase, direction || null, distance || 0);
				
				
				if (phase == PHASE_CANCEL)
				{
					if (defaults.click && fingerCount==1 && (isNaN(distance) || distance==0))
						defaults.click.call($this,event, event.target);
				}
				
				if (phase == PHASE_END)
				{
					//trigger catch all event handler
					if (defaults.swipe)
				{
						
						defaults.swipe.call($this,event, direction, distance);
						
				}
					//trigger direction specific event handlers	
					switch(direction)
					{
						case LEFT :
							if (defaults.swipeLeft)
								defaults.swipeLeft.call($this,event, direction, distance);
							break;
						
						case RIGHT :
							if (defaults.swipeRight)
								defaults.swipeRight.call($this,event, direction, distance);
							break;

						case UP :
							if (defaults.swipeUp)
								defaults.swipeUp.call($this,event, direction, distance);
							break;
						
						case DOWN :	
							if (defaults.swipeDown)
								defaults.swipeDown.call($this,event, direction, distance);
							break;
					}
				}
			}
			
			
			/**
			 * Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring.
			 * This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object.
			 */
			function validateDefaultEvent(event, direction)
			{
				if( defaults.allowPageScroll==NONE )
				{
					event.preventDefault();
				}
				else 
				{
					var auto=defaults.allowPageScroll==AUTO;
					
					switch(direction)
					{
						case LEFT :
							if ( (defaults.swipeLeft && auto) || (!auto && defaults.allowPageScroll!=HORIZONTAL))
								event.preventDefault();
							break;
						
						case RIGHT :
							if ( (defaults.swipeRight && auto) || (!auto && defaults.allowPageScroll!=HORIZONTAL))
								event.preventDefault();
							break;

						case UP :
							if ( (defaults.swipeUp && auto) || (!auto && defaults.allowPageScroll!=VERTICAL))
								event.preventDefault();
							break;
						
						case DOWN :	
							if ( (defaults.swipeDown && auto) || (!auto && defaults.allowPageScroll!=VERTICAL))
								event.preventDefault();
							break;
					}
				}
				
			}
			
			
			
			/**
			* Calcualte the length / distance of the swipe
			*/
			function caluculateDistance()
			{
				return Math.round(Math.sqrt(Math.pow(end.x - start.x,2) + Math.pow(end.y - start.y,2)));
			}
			
			/**
			* Calcualte the angle of the swipe
			*/
			function caluculateAngle() 
			{
				var X = start.x-end.x;
				var Y = end.y-start.y;
				var r = Math.atan2(Y,X); //radians
				var angle = Math.round(r*180/Math.PI); //degrees
				
				//ensure value is positive
				if (angle < 0) 
					angle = 360 - Math.abs(angle);
					
				return angle;
			}
			
			/**
			* Calcualte the direction of the swipe
			* This will also call caluculateAngle to get the latest angle of swipe
			*/
			function caluculateDirection() 
			{
				var angle = caluculateAngle();
				
				if ( (angle <= 45) && (angle >= 0) ) 
					return LEFT;
				
				else if ( (angle <= 360) && (angle >= 315) )
					return LEFT;
				
				else if ( (angle >= 135) && (angle <= 225) )
					return RIGHT;
				
				else if ( (angle > 45) && (angle < 135) )
					return DOWN;
				
				else
					return UP;
			}
			
			

			// Add gestures to all swipable areas if supported
			try
			{
				this.addEventListener("touchstart", touchStart, false);
				this.addEventListener("touchmove", touchMove, false);
				this.addEventListener("touchend", touchEnd, false);
				this.addEventListener("touchcancel", touchCancel, false);
			}
			catch(e)
			{
				//touch not supported
			}
				
		});
	};
	
	
	
	
})(jQuery);
