// DOM load page init
$(function(){
	initGalleryVideo();
	initNavHover();
	initApproccioDrag();
	initLavoryGallery();
	hoverSocialLink();
	
	mapBlock();
	clearForms();
	initValideteContactPage()
});

// window load page init
$(window).load(function(){
	//createTwittGallery();
	initLavotiLavoroScreen();
	contactForm();
});

// if Internet Explorer
ie = jQuery.browser.msie && jQuery.browser.version < 9;

// clear form fields
function clearForms(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
}

function initValideteContactPage(){
	
	$('form.contact-form').each(function(){
		var _form = $(this);
		var formBox = _form.find('.form-holder');
		var loadingBox = _form.find('.loading-box');
		var completeBox = _form.find('.complite');
		var linkClose = _form.find('input:reset');
		
		if(ie){
			completeBox.css({display:'none'});
			loadingBox.css({display:'none'});
		}
		else{
			completeBox.css({display:'block', opacity:0});
			loadingBox.css({display:'block', opacity:0});
		}
		
		initValidation(_form, formBox, completeBox, loadingBox);
		
		linkClose.click(function(){
			_form.find('.done').removeClass('done');
			_form.find('.error').removeClass('error');
		});
	});
	
	function initValidation(_form, formBox, completeBox, loadingBox){
		var _errorClass = 'error';
		var _doneClass = 'done';
		var _regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		function checkFields() {
			var _flag = false;
			_form.find('.'+_errorClass).removeClass(_errorClass).find('.'+_doneClass).removeClass(_doneClass);

			// fields validation
			_form.find('input.required-email').each(function(){
				if(!_regEmail.test($(this).val())) addError($(this));
				else addDone($(this));
			});
			_form.find('input.required, textarea.required').each(function(){
				if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
				else addDone($(this));
			});
			// error class adding
			function addError(_obj) {
				_obj.parents('.cell').addClass(_errorClass);
				_flag=true;
			}
			// done class adding
			function addDone(_obj) {
				_obj.parents('.cell').addClass(_doneClass);
			}
			return _flag;
		}
		
		// error class adding
		function addError(_obj) {
			_obj.parents('.cell').addClass(_errorClass);
			_flag=true;
		}
		// done class adding
		function addDone(_obj) {
			_obj.parents('.cell').addClass(_doneClass);
		}

		_form.find('input:text, textarea').focus(function(){
			$(this).parents('.cell').removeClass(_doneClass).removeClass(_errorClass);
		}).blur(function(){
			if($(this).hasClass('required-email')){
				if(!_regEmail.test($(this).val())) addError($(this));
				else addDone($(this));
			}
			if($(this).hasClass('required')){
				if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
				else addDone($(this));
			}
		});
		// catch form submit event
		_form.submit(function(){
			if(!checkFields()) {
				// send data with ajax
				sendData(_form, formBox, completeBox, loadingBox);
				return false;
			}
			return false;
		});
	}
	
	// send data with ajax
	function sendData(_form, formBox, completeBox, loadingBox){
		$.ajax({
			url: _form.attr('action'),
			data: {name: $("#name").val(), mail: $("#mail").val(), comment: $("#comment").val()},
			dataType: ($.browser.msie) ? 'text' : 'xml',
			success: function(xmlData){
				var _loadData;
				if (typeof xmlData == 'string') {
					_loadData = new ActiveXObject('Microsoft.XMLDOM');
					_loadData.async = false;
					_loadData.loadXML(xmlData);
				} else _loadData = xmlData;

				if($(_loadData).find('code').text() == '1'){
					formBox.animate({opacity:0}, {queue:false, duration:300, complete: function(){
						var srcImg = completeBox.find('img').attr('src');
						var newSrc = 'bg-complitebig.jpg';
						srcImg = srcImg.replace(/bg-complitekobig.jpg/g, newSrc);
						completeBox.find('img').attr('src', srcImg);
						completeBox.find('h3').text($(_loadData).find('code').parent().find('message').text()).end().find('p').text($(_loadData).find('code').parent().find('description').text());
						// reset form
						formBox.css({opacity:1, display:'none'});
						_form.find('input:reset').trigger('click');
						loadingBox.find('ul.switcher > li span').css({width: '', left: ''});
						// reset main height
						if(!ie){
							loadingBox.css({'opacity':0, 'display':'block'}).animate({opacity:1}, {queue: false, duration:300, complete:function(){
								startSwitcher(formBox, loadingBox, completeBox);
							}});
						}
						else{
							loadingBox.css({'opacity':'auto', 'display':'block'});
							startSwitcher(formBox, loadingBox, completeBox);
						}
					}})
				} else {
					_form.addClass('send-error');
					formBox.animate({opacity:0}, {queue:false, duration:300, complete: function(){
						var srcImg = completeBox.find('img').attr('src');
						var newSrc = 'bg-complitekobig.jpg';
						srcImg = srcImg.replace(/bg-complitebig.jpg/g, newSrc);
						completeBox.find('img').attr('src', srcImg);
						// reset form
						formBox.css({opacity:1, display:'none'});
						loadingBox.find('ul.switcher > li span').css({width: '', left: ''});
						_form.find('input:reset').trigger('click');
						
						// reset main height
						if(!ie){
							loadingBox.css({'opacity':0, 'display':'block'}).animate({opacity:1}, {queue: false, duration:300, complete:function(){
								startSwitcher(formBox, loadingBox, completeBox);
							}});
						}
						else{
							loadingBox.css({'opacity':'auto', 'display':'block'});
							startSwitcher(formBox, loadingBox, completeBox);
						}
					}})
				}
			},
			error:function(){alert('AJAX Error!')}
		});
	}
	
	// animate loading
	function startSwitcher(formBox, _obj, completeBox){
		var items = _obj.find('ul.switcher > li');
		var i = 0;
		var wait = setInterval(function(){
			items.eq(i).find('span.mask').animate({width:'100%'}, {queue: false, duration:300, complete: function(){
				$(this).animate({left:2}, {queue:false, duration:300});
				items.eq(i).find('span.l').animate({left:0}, {queue:false, duration:300});
				i++;
			}})
			if(i == items.length) {
				clearInterval(wait);
				completeBox.css({opacity:0, 'display':'block'}).animate({opacity:1}, {queue: false, duration:300, complete: function(){
					setTimeout(function(){
						completeBox.animate({opacity:0}, {queue:false, duration:300, complete: function(){
							completeBox.css({opacity:0});
							formBox.fadeIn()
						}});
					}, 4000);
				}});
				_obj.animate({opacity:0}, {queue: false, duration:300, complete:function(){
					$(this).hide();
				}});
			}
		}, 500);
	}
}

// the pins on map
function mapBlock(){
	$('.map-block').each(function(){
		var _this = $(this);
		var list = _this.find('.ico-list > li');
		list.each(function(){
			var b = parseInt($(this).css('bottom'));
			$(this).data('bottom', b);
			var h = $(this).height();
			if(!ie) $(this).css({bottom: b+h, opacity:0});
			else $(this).css({bottom: b+h, 'display':'none'});
			list.mouseenter(function(){
				$(this).animate({bottom:'+=5'}, {queue:false, duration:100, complete: function(){
					$(this).animate({bottom:'-=5'}, {queue:false, duration:100});
				}});
			});
		});
		var i = 0;
		var wait = setInterval(function(){
			if(!ie) list.eq(i).animate({opacity:1, bottom:list.eq(i).data('bottom')}, {queue:false, duration:500, easing:'easeOutBounce', complete: function(){
				list.eq(0).find('.address-block').animate({width:'196'}, {queue:false, duration:300});
			}});
			else list.eq(i).css({'display':'block'}).animate({bottom:list.eq(i).data('bottom')}, {queue:false, duration:500, easing:'easeOutBounce', complete:function(){
				list.eq(0).find('.address-block').animate({width:'196'}, {queue:false, duration:300});
			}});
			i++;
			if(i == list.length) clearInterval(wait);
		}, 200);
	});
}

// contact form
function contactForm(){
	$('.contact-content').each(function(){
		var _this = $(this);
		_this.data('thisH', _this.height());
		var form = _this.find('form');
		form.show();
		var formH = form.outerHeight();
		var mainH = $('#main').height();
		form.hide();
		var linkOpen = _this.find('a.open');
		var linkClose = _this.find('input:reset');
		linkClose.data('animated', true);
		
		// init validate form
		initValidation(form);
		
		linkOpen.click(function(){
			if(!form.data('open')){
			
				if($('#sidebar').height() + formH > mainH){
					
					$('#main').animate({height:$('#sidebar').height() + formH}, {queue:false, duration:300, complete: function(){
						if(!ie) linkOpen.animate({opacity:0}, {queue:false, duration:300});
						else linkOpen.hide();
						form.fadeIn();
					}});
				}else{		
					if(!ie) linkOpen.animate({opacity:0}, {queue:false, duration:300});
					else linkOpen.hide();
					form.fadeIn();
				}
				
				_this.animate({height:formH}, {queue: false, duration:300});
				form.data('open', true);
			}
			return false;
		});
		linkClose.click(function(){
			if(linkClose.data('animated')){
				form.data('open', false);
				form.find('.done').removeClass('done');
				form.find('.error').removeClass('error');
				if(!ie) linkOpen.animate({opacity:1}, {queue:false, duration:300});
				else linkOpen.show();
				form.fadeOut(300, function(){
					form.slideUp();
					_this.animate({height:_this.data('thisH')}, {queue: false, duration:300})
					$('#main').animate({height:mainH}, {queue:false, duration:300});
					linkClose.data('animated', true);
				});
			}
			
		});
	});
	
	// validate form
	function initValidation(form){
		var _errorClass = 'error';
		var _doneClass = 'done';
		var _regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		form.each(function(){
			var _form = $(this);
			function checkFields() {
				var _flag = false;
				_form.find('.'+_errorClass).removeClass(_errorClass).find('.'+_doneClass).removeClass(_doneClass);

				// fields validation
				_form.find('input.required-email').each(function(){
					if(!_regEmail.test($(this).val())) addError($(this));
					else addDone($(this));
				});
				_form.find('input.required, textarea.required').each(function(){
					if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
					else addDone($(this));
				});
				// error class adding
				function addError(_obj) {
					_obj.parents('.wrapper').addClass(_errorClass);
					_flag=true;
				}
				// done class adding
				function addDone(_obj) {
					_obj.parents('.wrapper').addClass(_doneClass);
				}
				return _flag;
			}
			
			// error class adding
			function addError(_obj) {
				_obj.parents('.wrapper').addClass(_errorClass);
				_flag=true;
			}
			// done class adding
			function addDone(_obj) {
				_obj.parents('.wrapper').addClass(_doneClass);
			}

			_form.find('input:text, textarea').focus(function(){
				$(this).parents('.wrapper').removeClass(_doneClass).removeClass(_errorClass);
			}).blur(function(){
				if($(this).hasClass('required-email')){
					if(!_regEmail.test($(this).val())) addError($(this));
					else addDone($(this));
				}
				if($(this).hasClass('required')){
					if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
					else addDone($(this));
				}
			});
			// catch form submit event
			_form.submit(function(){
				if(!checkFields()) {
					// send data with ajax
					sendData(_form);
				}
				return false;
			});
		});
	}
	
	// send data with ajax
	function sendData(_form){
		var loadBox = _form.parent().find('.loading-box');
		loadBox.show();
		var loadBoxH = loadBox.outerHeight();
		loadBox.hide();
		var linkOpen = _form.parent().find('a.open');
		$.ajax({
			url: _form.attr('action'),
			data: {mail: $("#mail").val(), comment: $("#comment").val()},
			dataType: ($.browser.msie) ? 'text' : 'xml',
			success: function(xmlData){
				var _loadData;
				if (typeof xmlData == 'string') {
					_loadData = new ActiveXObject('Microsoft.XMLDOM');
					_loadData.async = false;
					_loadData.loadXML(xmlData);
				} else _loadData = xmlData;

				var code = $(_loadData).find('code').text();
				if(code == '1' || code == '0'){
					_form.parent().animate({height: loadBoxH}, {queue:false, duration:300});
					if(code == '0'){
						_form.parent().addClass('send-error');
					}else{
						_form.parent().removeClass('send-error');
					}
					if(!ie){
						_form.animate({opacity:0}, {queue:false, duration:300, complete: function(){
							_form.parent().find('.complite-box').find('h3').text($(_loadData).find('code').parent().find('message').text()).end().find('p').text($(_loadData).find('code').parent().find('description').text());
							// reset form
							_form.css({opacity:1, display:'none'});
							_form.find('.done').removeClass('done');
							_form.find('.error').removeClass('error');
							_form.parent().find('ul.switcher > li span').css({width: '', left: ''});
							_form.find('input:reset').data('animated', false).trigger('click');
							
							
							/*/ Commented because it doesn't work when the sidebar is lower then the content.... reset main height
							if($('#sidebar').height() < $('#main').height()){
								$('#main').animate({height:$('#sidebar').height()}, {queue:false, duration:300});
							}
							/*/
														
							loadBox.css({'opacity':0, 'display':'block'}).animate({opacity:1}, {queue: false, duration:300, complete:function(){
								startSwitcher(_form.parent().find('.loading-box'));
								_form.find('input:reset').data('animated', true)
							}});
						}})
					}else{
						_form.hide();
						_form.parent().find('.complite-box').find('h3').text($(_loadData).find('code').parent().find('message').text()).end().find('p').text($(_loadData).find('code').parent().find('description').text());
						// reset form
						_form.find('.done').removeClass('done');
						_form.find('.error').removeClass('error');
						_form.find('input:reset').data('animated', false).trigger('click');
						_form.parent().find('ul.switcher > li span').removeAttr('style');
						// reset main height
						if($('#sidebar').height() < $('#main').height()){
							setTimeout(function(){
								$('#main').animate({height:$('#sidebar').height()}, {queue:false, duration:300});
							}, 300);
							
						}
						
						loadBox.css({'opacity':'auto', 'display':'block'});
						startSwitcher(_form.parent().find('.loading-box'));
						_form.find('input:reset').data('animated', true)
					}
				}
			},
			error:function(){alert('AJAX Error!')}
		});
	}
	
	// animate loading
	function startSwitcher(_obj){
		var items = _obj.find('ul.switcher > li');
		var i = 0;
		var wait = setInterval(function(){
			items.eq(i).find('span.mask').animate({width:'100%'}, {queue: false, duration:300, complete: function(){
				$(this).animate({left:2}, {queue:false, duration:300});
				items.eq(i).find('span.l').animate({left:0}, {queue:false, duration:300});
				i++;
			}})
			if(i == items.length) {
				clearInterval(wait);
				_obj.parent().find('.complite-box').css({opacity:0, 'display':'block'}).animate({opacity:1}, {queue: false, duration:300, complete: function(){
					setTimeout(function(){
						_obj.parent().find('.complite-box').animate({opacity:0}, {queue:false, duration:300});
						_obj.parent().animate({height:_obj.parent().find('a.open').height()}, {queue:false, duration:300})
						if(!ie) _obj.parent().find('a.open').animate({opacity:1}, {queue:false, duration:300});
						else _obj.parent().find('a.open').show();
						_obj.parent().find('form').data('open', false);
						_obj.parents('form').parent().removeClass('send-error');
						_obj.parents('form').find('input:reset').data('animated', true);
					}, 4000);
				}});
				_obj.animate({opacity:0}, {queue: false, duration:300, complete:function(){
					$(this).hide();
				}});
			}
		}, 500);
	}
}

// social link hover
function hoverSocialLink(){
	$('ul.social2 > li').each(function(){
		var _this = $(this);
		var over = _this.find('.rollover');
		var h = over.height();
		over.css('top', h/3);
		_this.mouseenter(function(){
			over.animate({top:-h/3}, {queue:false, duration:300});
		}).mouseleave(function(){
			over.animate({top:h/3}, {queue:false, duration:300});
		});
	});
}

// Lavoti Lavoro page - Progect Screen
function initLavotiLavoroScreen(){
	$('.toggle-box').each(function(){
		var hold = $(this);
		var title = hold.find('h2.title-txt');
		var link = hold.find('a.screen-button');
		var toggleBox = hold.find('.top-gallery .wrapper');
		var colorBox = toggleBox.find('.color').data('h', toggleBox.find('.color').height());
		var defaultBox = colorBox.clone().prependTo(toggleBox).addClass('bw').data('h', toggleBox.find('.bw').height()/2).css({
			opacity:1, 
			top:colorBox.height()-toggleBox.find('.bw').height()
		});
		defaultBox.find('img').grayscale();
		slideTitle('top');

		// title slide
		function slideTitle(flag, callback){
			var elem = title;
			var h = elem.height();
			var eachSpan;

			var i = 0;
			var count = elem.children().length;
			if(flag == 'top'){
				if(!ie) elem.children().css({opacity:0, top:h/2});
				else elem.children().css({display:'none'});
				eachSpan = setInterval(function(){
					if(ie) elem.children().eq(i).show();
					else elem.children().eq(i).animate({opacity:1, top:0}, {queue:false, duration: 300});
					i++;
					if(i == count) clearInterval(eachSpan);
				}, 200);
			}
			else if(flag == 'bottom'){
				i = count;
				eachSpan = setInterval(function(){
					if(ie) {
						elem.children().eq(i).hide().animate({top:h/2}, {queue:false, duration: 300, complete: function(){
							if(typeof callback === 'function') callback();
						}});
						i--;
					}
					else {
						elem.children().eq(i).animate({opacity:0, top:h/2}, {queue:false, duration: 300, complete: function(){
							if(typeof callback === 'function') callback();
						}});
						i--;
					}
					if(i < 0) clearInterval(eachSpan);
				}, 200);
			}
			else{return}
		}
		
		var gallHolder = $('#main .content-gallery');
		var contHolder = $('#main .content-holder');
		
		$('#main').children().css({
			'position': 'absolute',
			left: parseInt($('#main').css('paddingLeft')),
			top: parseInt($('#main').css('paddingTop'))
		});
		$('#main').css({
			position:'relative',
			height: contHolder.height()
		});
		gallHolder.css({ opacity: 0, display: 'block' });
		
		// init gallery
		var g5 = new initGallery(gallHolder,{
			list: 'ul.gallery',
			prev: '.prev-holder',
			next: '.next-holder',
			disableBtn: true,
			disabledChild: true,
			effect: 'fade',
			onStart: function(obj, bb, cc){
				obj.list.animate({ height: obj.list.children().eq(obj.active).height()}, {queue:false, duration:300});
			},
			onChange: function(obj){
				// auto height
				obj.list.animate({height:obj.list.children().eq(obj.active).height()}, {queue:false, duration:300});
				$('#main').animate({height:obj.list.children().eq(obj.active).height()}, {queue:false, duration:300});
			}
		});
		gallHolder.css({ opacity: 0, display: 'none' });
		
		link.click(function(){
			if(hold.hasClass('init')){
				hold.removeClass('init');
				gallHolder.hide();
				defaultBox.animate({opacity:0}, {queue:false, duration:300});
				colorBox.animate({opacity:1}, {queue:false, duration:300});
				setTimeout(function(){
					toggleBox.animate({marginTop: 0}, {queue:false, duration: 300});
					hold.animate({height:colorBox.data('h')}, {queue:false, duration:300});
					$('#header').animate({height:colorBox.data('h')}, {queue:false, duration:300, complete: function(){
						defaultBox.css('opacity', 1);
						slideTitle('top');
					}});
				}, 200);
				toggleState(false);
			}
			else{
				slideTitle('bottom', function(){
					hold.addClass('init');
					gallHolder.show();
					toggleBox.animate({marginTop: -colorBox.data('h')+defaultBox.data('h')}, {queue:false, duration: 300});
					hold.animate({height:defaultBox.data('h')}, {queue:false, duration:300});
					$('#header').animate({height:defaultBox.data('h')}, {queue:false, duration:300});
					colorBox.animate({opacity:0}, {queue:false, duration:1000});
					$('#main').css({position:'relative'});
					toggleState(true);
				});
			}
			return false;
		});
		
		// toggle state image
		function toggleState(f){
			if(f){
				contHolder.animate({opacity:0}, {queue:false, duration:700, complete: function(){$(this).hide()}});
				gallHolder.css('display', 'block').animate({opacity:1}, {queue:false, duration:700, complete: function(){$(this).css('opacity', 'auto')}});
				$('#main').animate({height:$('#main .content-gallery').height()}, {queue: false, duration:500});
				g5.holder.bind('mouseenter', function(){
					g5.prev.show();
					g5.next.show();
				}).bind('mouseleave', function(){
					g5.prev.hide();
					g5.next.hide();
				});
				g5.holder.bind('mousemove', function(e){
					var t = e.pageY;
					var minT = g5.holder.offset().top + g5.prev.children().height()/2 + g5.list.children().eq(g5.active).find('.text-box').outerHeight();
					var maxT = g5.holder.offset().top + g5.holder.height() - g5.prev.children().height();
					if(t < maxT && t > minT){
						g5.prev.children().css('top', t - (g5.prev.children().height()/2) - ($('#header').height()+parseInt($('#main').css('paddingTop')) + g5.list.children().eq(g5.active).find('.text-box').outerHeight()));
						g5.next.children().css('top', t - (g5.next.children().height()/2) - ($('#header').height()+parseInt($('#main').css('paddingTop')) + g5.list.children().eq(g5.active).find('.text-box').outerHeight()));
					}
				})
			}
			else{
				$('#main .content-holder').css('display', 'block').animate({opacity:1}, {queue:false, duration:700, complete: function(){$(this).css('opacity', 'auto')}});
				gallHolder.animate({opacity:0}, {queue:false, duration:700, complete: function(){$(this).hide()}});
				$('#main').animate({height:contHolder.height()}, {queue: false, duration:500});
				g5.holder.unbind('mousemove');
			}
		}
	});
}

// Lavory page - Gallery
function initLavoryGallery(){
	var isMobile = (/(ipad|iphone|ipod|android|blackberry)/gi).test(navigator.userAgent);
	// init gallery
	var g4 = new initGallery('.item-holder > .area',{
		list: '.holder .mask ul.item-gallery',
		switcher: '.frame ul.switcher > li',
		prev: '.prev a',
		next: '.next a',
		effect: 'slide',
		disableBtn: true,
		onStart: function(obj){
			if(!ie) obj.switcher.eq(obj.active).find('.act-state').fadeIn(700);
			else obj.switcher.eq(obj.active).find('.act-state').show();
			startAnimation(obj);
			slideHover(obj);
		},
		onChange: function(obj){
			if(!ie && !isMobile) {
				obj.switcher.find('.act-state').animate({}, {queue:false, duration:700, complete:function(){$(this).hide()}});
				obj.switcher.eq(obj.active).find('.act-state').fadeIn(500);
			}
			else{
				obj.switcher.eq(obj.prevActive).find('.act-state').hide();
				obj.switcher.eq(obj.active).find('.act-state').show();
			}
		}
	});
	
	// animate in loading page
	function startAnimation(obj){
		var elems = obj.list.children().filter(':lt('+obj.active+obj.visEl+')');
		elems.each(function(){
			var _this = $(this);
			var tBox = _this.find('.cell:eq(0)');
			var iBox = _this.find('.cell:eq(1)');
			tBox.css({top:-tBox.outerHeight(true)});
			iBox.css({top:iBox.outerHeight(true)});
		});
		var i = 0;
		var tBox_anim = setInterval(function(){
			elems.eq(i).find('.cell:eq(0)').animate({top:0}, {queue:false, duration:200});
			elems.eq(i).find('.cell:eq(1)').animate({top:0}, {queue:false, duration:200});
			i++;
			if(i == elems.length) clearInterval(tBox_anim);
		}, 200);
	}
	
	// open close in hover list item
	function slideHover(obj){
		obj.list.children().find('.cell').bind({
			mouseenter:function(){
				$(this).find('.visual').animate({top:-80}, {queue:false, duration:200});
			},
			mouseleave:function(){
				$(this).find('.visual').animate({top:0}, {queue:false, duration:200});
			}
		});
	}
}

// drag on Approccio page
function initApproccioDrag(){
	$('.intro').each(function(){
		var hold = $(this);
		var areaDrag = hold.find('> .area');
		var dragBox = areaDrag.find('.drag-box');
		var dragLink = areaDrag.find('.drag');
		var goLive = areaDrag.find('.btns-holder .go-live');
		var onLine = areaDrag.find('.btns-holder .online');
		var switcher = areaDrag.find('.switch-elements');
		var l = dragBox.offset().left;
		var w = dragBox.width();
		var slideX = 0;
		var oldInd = 0;
		var mass = [];
		var massBtnLive = [];
		var massBtnLine = [];
		var galleryHold = hold.find('.carousel-area');
		
		switcher.children().each(function(i){
			mass.push(switcher.children().eq(i).position().left + switcher.children().eq(i).width())
		});
		goLive.each(function(i){
			massBtnLive.push({'selector':$(this), 'left':goLive.eq(i).position().left});
		});
		onLine.each(function(i){
			massBtnLine.push({'selector':$(this), 'left':onLine.eq(i).position().left, 'top': 60});
		});
		
		// init gallery
		var g3 = new initGallery(galleryHold,{
			list: 'ul.carousel',
			prev: '.prev a',
			next: '.next a',
			effect: 'fade',
			disableBtn: true,
			onStart: function(obj){
				dragBox.width(0);
				prepareBtns();
				initBtnsLive(switcher.width()+50);
				initBtnsLine(switcher.width());

				
				setTimeout(function(){
					dragBox.animate({width: w-mass[obj.active]}, {queue: false, duration: 1500, step: function(current){
						initBtnsLive(switcher.width()-current+50);
						initBtnsLine(switcher.width()-current);
					}});
				}, 700);
			},
			beforeChange: function(obj, event){
				var act = event.target.rel == 'next' ? obj.active+1 : event.target.rel == 'prev' ? obj.active-1 : 0;
				dragBox.animate({width: w-mass[act]}, {queue: false, duration: 300, step: function(current){
					initBtnsLive(switcher.width()-current+50);
					initBtnsLine(switcher.width()-current);
				}});
			}
		});
		
		// touch on mobile device
		if(dragLink.get(0).addEventListener) {
			dragLink.get(0).addEventListener("touchstart", touchHandler, true);
		}
		
		dragLink.mousedown(function(){
			jQuery('body').bind({
				mousemove: moveSlider,
				mouseup: clearBody
			});
			
			// touch on mobile device
			if(document.body.addEventListener) {
				document.body.addEventListener("touchmove", touchHandler, true);
				document.body.addEventListener("touchend", touchHandler, true);
			}
			document.onselectstart = function(){return false}
			return false;
		});
		
		// prepare btns
		function prepareBtns(){
			goLive.css({opacity:0});
			onLine.css({opacity:0, top:60});
		}
		
		// init btns
		function initBtnsLive(x){
			for(var i = massBtnLive.length-1; i > -1; i--){
				if(!massBtnLive[i].busy && x > massBtnLive[i].left) {
					massBtnLive[i].busy = true;
					massBtnLive[i].selector.stop().animate({opacity:1}, {queue:false, duration:500});
				}
				else if(massBtnLive[i].busy && x < massBtnLive[i].left){
					massBtnLive[i].busy = false;
					massBtnLive[i].selector.css({opacity:0});
				}
			}
		}
		function initBtnsLine(x){
			for(var i = massBtnLine.length-1; i > -1; i--){
				if(!massBtnLine[i].busy && x > massBtnLine[i].left) {
					massBtnLine[i].busy = true;
					massBtnLine[i].selector.stop().animate({opacity:1, top:40}, {queue:false, duration:500});
				}
				else if(massBtnLine[i].busy && x < massBtnLine[i].left){
					massBtnLine[i].busy = false;
					massBtnLine[i].selector.css({opacity:0, top: massBtnLine[i].top});
				}
			}
		}

		// init move slide
		function moveSlider(e){
			slideX = w-(e.pageX-l);
			if(slideX > w) slideX = w
			else if(slideX < 0 ) slideX = 0;
			refreshSwitcher(e.pageX-l);
			initBtnsLive(e.pageX-l);
			initBtnsLine(e.pageX-l);
			dragBox.css('width', slideX);
		}

		// refresh state switcher
		function refreshSwitcher(x){
			for(var i = mass.length-1; i > -1; i--){
				if(x > mass[i]) {
					if(oldInd != i) {
						oldInd = i;
						g3.refreshState(i);
					}
					break;
				}
			}
		}
		
		// unbind events
		function clearBody(){
			jQuery('body').unbind('mousemove', moveSlider).unbind('mouseup', clearBody);
			// touch on mobile device
			if(document.body.removeEventListener) {
				document.body.removeEventListener("touchmove", touchHandler, true);
				document.body.removeEventListener("touchend", touchHandler, true);
			}
			document.onselectstart = null;
		}
	});
}

// twitter gallery
function createTwittGallery(){
	var div = $('#twitter-gallery');
	var users = ['solarsau'];
	var qty = 10;
	var temp = [];
	var mass = [];
	
	//start twitterhelper
	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?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).replace("<a", "<a target='new'");
		});
	},
	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).replace("<a", "<a target='new'");
		});
	},
	parseText: function(text) {
		return twitterHelper.parseHashtag(twitterHelper.parseUsername(twitterHelper.parseURL(text)));
	}
}
	//end twitterhelper
	
	function loadData(ind) {
		if(users[ind]) {
			if(ind == users.length-1) qty = 11; // fix
			twitterHelper.loadTweets(users[ind], qty, function() {
				loadData(++ind);
				createStruct.apply(this, arguments);
			});
		}
	};
	// on-line. turn off to test local
	loadData(0);


	// create structure slideshow
	function createStruct(data){
		mass = [];
		for(var i = 0; i < data.length; i++) {
			mass.push($('<li><div class="text-box"><p>'+twitterHelper.parseText(data[i].text)+'</p></div><div class="info-box"><em class="time">'+twitterHelper.relativeTime(data[i].created_at)+'</em><div class="user-info"><a href="#" class="avatar"><img src="'+data[i].user.profile_image_url+'" width="30" height="30" alt="" /></a><a target="_new" href="http://www.twitter.com/#!/' + data[i].user.screen_name + '" class="name">'+data[i].user.name+'</a></div></div></li>').data('post-data', new Date(data[i].created_at)))
		}
		temp.push(mass);
		if(temp.length == users.length) prepareData();
	}
	
	function prepareData(){
		var ul = $('<ul class="gallery">');
		
		
		for(var i = 0; i < qty; i++){
			for(var j = 0; j < temp.length; j++){
				var curArr = temp[j];
				var curEl = curArr[0];
				curArr.splice(0,1);
				ul.append(curEl)
			}
		}
		

		// sort by date
		var set = ul.children();
		for(var i = 0; i < set.length; i++) {
			for(var j = 0; j < set.length-1; j++) {
				if(set.eq(j).data('post-data') < set.eq(j+1).data('post-data')) {
					set.eq(j+1).insertBefore(set.eq(j));
					set = ul.children();
				}
			}
		}

		div.find('.social-gallery').append(ul);
		initTwittGallery();
	}
	
	// init gallery
	function initTwittGallery(){
		var g2 = new initGallery(div,{
			list: '.social-gallery ul',
			next: '.next a',
			prev: '.prev a',
			effect: 'slide',
			disableBtn: true,
			onStart: function(obj){
				var elems = obj.list.children().filter(':lt('+obj.active+obj.visEl+')');
				elems.each(function(){
					var _this = $(this);
					var tBox = _this.find('.text-box');
					var iBox = _this.find('.info-box');
					tBox.css({top:-tBox.height()*1.5});
					iBox.css({top:iBox.height()*1.5});
				});
				var i = 0;
				var tBox_anim = setInterval(function(){
					elems.eq(i).find('.text-box').animate({top:0}, {queue:false, duration:200});
					i++;
					if(i == elems.length) {
						clearInterval(tBox_anim);
						i = 0;
						var iBox_anim = setInterval(function(){
							elems.eq(i).find('.info-box').animate({top:0}, {queue:false, duration:200});
							i++;
							if(i == elems.length) clearInterval(iBox_anim);
						}, 200);
					}
				}, 200);
			},
			beforeChange: function(obj, event){
				var act = event.target.rel == 'next' ? obj.active : event.target.rel == 'prev' ? obj.active+obj.visEl-1 : 0;
				var _this = obj.list.children().eq(act);
				var tBox = _this.find('.text-box');
				var iBox = _this.find('.info-box');

				tBox.animate({top:-tBox.height()*2}, {queue:false, duration:700, complete:function(){
					resetElems($(this));
				}});
				iBox.animate({top:iBox.height()*2}, {queue:false, duration:700, complete:function(){
					resetElems($(this));
				}});
			}
		});
		
		function resetElems(_this){
			setTimeout(function(){_this.css('top',0)},200);
		}
	}
}

// main navigation hover
function initNavHover(){
	$('#nav li').each(function(){
		var _this = $(this);
		var line = _this.find('span.mask');
		_this.mouseenter(function(){
			line.animate({left:0}, {queue:false, duration:150});
		}).mouseleave(function(){
			line.animate({left:'100%'}, {queue:false, duration:150, complete: function(){
				line.css('left', '-100%');
			}});
		});
	});
}

// init gallery
function initGalleryVideo(){
	var waitAnimating = false;
	var g1 = new initGallery(jQuery('.gallery-section'),{
		list: 'ul.gallery',
		switcher: '.switcher-holder ul.switcher > li',
		effect: 'fade',
		autoRotation: 10000,
		conditionSwitcher: function(obj, index, callback){
			if(!waitAnimating) callback(index)
		},
		onStart: function(obj){
			resetElements(obj);
			slideTitle(obj);
			resizeImg(obj);
		},
		beforeChange: function(obj){
			initTimer(obj);
		},
		onChange: function(obj){
			slideTitle(obj);
		},
		switcherClick: function(obj){
			resetElements(obj);
		}
	});
	
	// on image resize
	function resizeImg(obj){
		if($(window).width() > 1920) {
			$('body').addClass('max-width');
		}
		else{
			$('body').removeClass('max-width');
		}
		$(window).unbind('resize').bind('resize', function(){
			resizeImg(obj);
		});
	};
	
	// reset
	function resetElements(obj){
		obj.switcher.eq(obj.active).find('.mask, .l').stop().end().find('.mask').css({left:0, width:0, right:'auto'}).end().find('.l').css({left:-3});
		var elem = obj.list.children().find('h2');
		var h = elem.height();
		if(ie) elem.children().hide();
		else {
			elem.children().css({
				'position':'relative',
				opacity:0,
				top:h/3
			});
		}
	}
	
	// title slide
	function slideTitle(obj){
		var elem = obj.list.children().eq(obj.active).find('h2');
		var h = elem.height();

		var i = 0;
		var count = elem.children().length;
		var eachSpan = setInterval(function(){
			waitAnimating = true;
			if(ie) elem.children().eq(i).show();
			else elem.children().eq(i).animate({opacity:1, top:0}, {queue:false, duration: obj.autoRotation/10});
			i++;
			if(i == count) {
				clearInterval(eachSpan);
				setTimeout(function(){
					waitAnimating = false;
				}, obj.autoRotation/10);
			}
		}, 200);
		setTimeout(function(){
			eachSpan = setInterval(function(){
				if(ie) elem.children().eq(i).hide();
				else elem.children().eq(i).animate({opacity:0, top:h/3}, {queue:false, duration: obj.autoRotation/10});
				i--;
				if(i < 0) clearInterval(eachSpan);
			}, 200);
		}, obj.autoRotation*(2/3));
	}
	
	// timer
	function initTimer(obj){
		obj.switcher.eq(obj.active).find('.mask').animate({left:2}, {queue: false, duration:obj.autoRotation/2});
		obj.switcher.eq(obj.active).find('.l').animate({left:0}, {queue: false, duration:obj.autoRotation/2});
		obj.switcher.eq(obj.active).find('span.mask').animate({width:'100%'}, {queue:false, duration:obj.autoRotation, complete: function(){
			var _this = $(this);
			$(this).css({left:'auto', right:-1});
			_this.animate({width:0}, {queue:false, duration:obj.autoRotation/6, complete:function(){
				$(this).css({left:0, right:'auto'});
			}});
			_this.parent().find('span.l').animate({left: '100%'}, {queue:false, duration:obj.autoRotation/6 + 50, complete: function(){
				$(this).css({'left': -3});
			}});
		}});
	}
}

// main gallery module
function initGallery(context, options){this.init(context, options)}
(function( $ ){
	initGallery.prototype = {
		autoRotation: false,
		disableBtn: false,
		disabledChild: false,
		list: 'ul.g1',
		switcher: false,
		prev: false,
		next: false,
		effect: false,
		event:'click',
		onStart: function(){},
		beforeChange: function(){},
		onChange: function(){},
		switcherClick: function(){},
		conditionSwitcher: false,
		activeSlide: 0,
		
		init: function(context, options){
			for ( var i in options ) this[i] = options[i]; 
			this.holder = $(context);
			if(this.holder == undefined) return;
			
			this.list = this.holder.find(this.list);
			this.animation = true, this.active = 0;
			this.prevActive = this.active, this.wait;
			this.count = this.list.children().length,
			this.w = this.list.children().eq(0).outerWidth(true);
			this.holdW = this.list.parent().width();
			this.visEl = Math.ceil(this.holdW/this.w);
			
			if(this.count <= this.visEl) this.animation = false;
			
			if(this.effect == 'fade') this.list.children().css('opacity', 0).eq(this.active).css('opacity', 1).addClass('active');
			else if(this.effect == 'slide') this.list.css('marginLeft', -this.w*this.active);

			this.initControls(this);
			
			this.toggleState.listItem(this);
			if(this.switcher) this.toggleState.switchItem(this);
			
			this.onStart(this, this.list, this.active);
			
			if(this.autoRotation && this.animation) this.runTimer(this);
		},
		initControls: function(_this){
			if(_this.prev && _this.next){
				_this.prev = _this.holder.find(_this.prev).attr('rel', 'prev').click(function(e){
					_this.beforeChange(_this, e);
					_this.refreshState(e);
					return false;
				});
				_this.next = _this.holder.find(_this.next).attr('rel', 'next').click(function(e){
					_this.beforeChange(_this, e);
					_this.refreshState(e);
					return false;
				});
			}
			if(_this.switcher){
				_this.switcher = _this.holder.find(_this.switcher);
				_this.toggleState.switchItem(_this);
				_this.switcher.bind(_this.event, function(){
					var ind = _this.switcher.index($(this));
					if(typeof _this.conditionSwitcher === 'function') {
						_this.conditionSwitcher(_this, ind, funcChange);
					}
					else {
						_this.switcherClick(_this);
						_this.refreshState(ind);
					}
					return false;
				});
				function funcChange(ind){
					_this.switcherClick(_this);
					_this.refreshState(ind);
				}
			}
			if(this.disableBtn) this.disabledConrtol();
		},
		toggleState:{
			listItem: function(_this){
				_this.list.children().eq(_this.prevActive).removeClass('active');
				_this.list.children().eq(_this.active).addClass('active');
			},
			switchItem: function(_this){
				_this.switcher.eq(_this.prevActive).removeClass('active');
				_this.switcher.eq(_this.active).addClass('active');
			}
		},
		disabledConrtol: function(){
			if(this.active == 0) {
				if(this.disabledChild){
					this.prev.attr('rel', 'stop').children().addClass('disabled');
					this.next.attr('rel', 'next').children().removeClass('disabled');
				}
				else{
					this.prev.attr('rel', 'stop').parent().addClass('disabled');
					this.next.attr('rel', 'next').parent().removeClass('disabled');
				}
			}
			else if(this.active == this.count-1 || (this.visEl > 2 && this.active + this.visEl == this.count)) {
				if(this.disabledChild){
					this.prev.attr('rel', 'prev').children().removeClass('disabled');
					this.next.attr('rel', 'stop').children().addClass('disabled');
				}
				else{
					this.prev.attr('rel', 'prev').parent().removeClass('disabled');
					this.next.attr('rel', 'stop').parent().addClass('disabled');
				}
				this.autoRotation = false;
			}
			else {
				if(this.disabledChild){
					this.prev.attr('rel', 'prev').children().removeClass('disabled');
					this.next.attr('rel', 'next').children().removeClass('disabled');
				}
				else{
					this.prev.attr('rel', 'prev').parent().removeClass('disabled');
					this.next.attr('rel', 'next').parent().removeClass('disabled');
				}
			}
		},
		runTimer: function(_this){
			_this.beforeChange(_this);
			this.wait = setTimeout(function(){_this.refreshState('next')}, this.autoRotation)
		},
		stop: function(){
			if(this.wait) clearTimeout(this.wait)
		},
		play: function(){
			if(this.wait) clearTimeout(this.wait);
			if(this.autoRotation) this.runTimer(this);
		},
		changeSlide:{
			fade:function(_this){
				_this.list.children().eq(_this.prevActive).animate({opacity:0}, {queue:false, duration:700});
				_this.list.children().eq(_this.active).animate({opacity:1}, {queue:false, duration:700, complete:function(){
					_this.play();
					_this.onChange(_this, _this.list, _this.active);
				}});
			},
			slide:function(_this){
				if(_this.active + _this.visEl > _this.count) _this.active = 0;
				_this.list.animate({marginLeft:-_this.w*_this.active}, {queue:false, duration:500, complete:function(){
					_this.play();
					_this.onChange(_this, _this.list, _this.active);
				}});
			}
		},
		refreshState: function(e){
			if(this.animation){
				this.prevActive = this.active;
				if(typeof e == 'string' && e == 'next') this.active++;
				else if(typeof e == 'number') this.active=e;
				else{
					if($(e.currentTarget).attr('rel') == 'next') this.active++;
					else if($(e.currentTarget).attr('rel') == 'prev') this.active--;
				}
				if(this.wait) clearTimeout(this.wait);
				if(this.active == this.count) this.active = 0;
				else if(this.active == -1) this.active=this.count - 1;
				
				this.toggleState.listItem(this);
				if(this.switcher) this.toggleState.switchItem(this);
				
				if(this.disableBtn) this.disabledConrtol();
				
				if(this.effect == 'fade') this.changeSlide.fade(this);
				else if(this.effect == 'slide') this.changeSlide.slide(this);
			}
		}	
	}
})( jQuery );

// touch events on mobile device
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();
}

// Share on social
function shareUrl(social, url) {
		if(social=="t") window.open('http://twitter.com/intent/tweet?url='+document.URL,'Share','width=550,height=300,left='+(screen.availWidth/2-275)+',top='+(screen.availHeight/2-150)+'');
		if(social=="f") window.open('http://www.facebook.com/sharer.php?u=='+document.URL,'Share','width=550,height=300,left='+(screen.availWidth/2-275)+',top='+(screen.availHeight/2-150)+'');
		if(social=="g") window.open('http://www.google.com/buzz/post?url='+document.URL,'Share','width=670,height=300,left='+(screen.availWidth/2-335)+',top='+(screen.availHeight/2-150)+'');
	}

// jQuery easing
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

// clear form function
function clearFormFields(o){
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filter) o.filter = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass)) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}

// grayscale plugin
(function($){
	function grayscale(image, bPlaceImage) {
		var myCanvas=document.createElement("canvas");
		var myCanvasContext=myCanvas.getContext("2d");
		var imgWidth=1920;
		var imgHeight=image.height;
		myCanvas.width= imgWidth;
		myCanvas.height=imgHeight;
		myCanvasContext.drawImage(image,0,0);
		var imageData=myCanvasContext.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;
			}
		}
		myCanvasContext.putImageData(imageData,0,0,0,0, imageData.width, imageData.height);

		if (bPlaceImage) {
			var myDiv=document.createElement("div");
			myDiv.appendChild(myCanvas);
			image.parentNode.appendChild(myCanvas);//, image);
		}
		return myCanvas.toDataURL();
	}

	jQuery.fn.grayscale = function(_options){
		var _options = jQuery.extend({
			temp:1
		},_options);
		return this.each(function(){
			// options
			var image = this;
			var _temp = _options.temp;
			if($.browser.msie && $.browser.version < 9) {
				image.style.filter = 'gray'
			} else {
				image.src = grayscale(image);
			}
		});
	}
})(jQuery);
