/*
 * jQuery autoResize (textarea auto-resizer)
 * @copyright James Padolsey http://james.padolsey.com
 * @version 1.04
 */

(function(a){a.fn.autoResize=function(j){var b=a.extend({onResize:function(){},animate:true,animateDuration:150,animateCallback:function(){},extraSpace:20,limit:1000},j);this.filter('textarea').each(function(){var c=a(this).css({resize:'none','overflow-y':'hidden'}),k=c.height(),f=(function(){var l=['height','width','lineHeight','textDecoration','letterSpacing'],h={};a.each(l,function(d,e){h[e]=c.css(e)});return c.clone().removeAttr('id').removeAttr('name').css({position:'absolute',top:0,left:-9999}).css(h).attr('tabIndex','-1').insertBefore(c)})(),i=null,g=function(){f.height(0).val(a(this).val()).scrollTop(10000);var d=Math.max(f.scrollTop(),k)+b.extraSpace,e=a(this).add(f);if(i===d){return}i=d;if(d>=b.limit){a(this).css('overflow-y','');return}b.onResize.call(this);b.animate&&c.css('display')==='block'?e.stop().animate({height:d},b.animateDuration,b.animateCallback):e.height(d)};c.unbind('.dynSiz').bind('keyup.dynSiz',g).bind('keydown.dynSiz',g).bind('change.dynSiz',g)});return this}})(jQuery);

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

jQuery.fn.outerHTML = function(s) {
	return (s)
	? this.before(s).remove()
	: jQuery("<p>").append(this.eq(0).clone()).html();
}
jQuery.fn.slideLeftHide = function( speed, callback ) {
	sbo.animationInProgress = true;
	var width = -jQuery('#showcase').width();
	this.animate( {
		left: width/*,
		paddingLeft: "hide",
		paddingRight: "hide", 
		marginLeft: "hide", 
		marginRight: "hide" */
	}, speed, callback ); 
};

jQuery.fn.formValidation = function() {
	$ = jQuery;
	$(this).bind('submit', function(){
		var opts = '';
		var errors = 0;
		$('input[type=text][class$=jreq], textarea[class$=jreq]:not([tabindex=-1])', this).each(function(){
			$(this).parent().removeClass('i-error');
			$('.tx-thmailformplus-pi1 p.i-error').hide();
			if($(this).attr('name') == 'email') {
				if(!isValidEmailAddress($(this).val())) {
					$(this).parent().addClass('i-error');
					errors = 1;
				}
			} else {
				if($(this).val() == '') {
					$(this).parent().addClass('i-error');
					errors = 1;
				}
			}
		});
		if(errors) {
			$('.tx-thmailformplus-pi1 p.i-error').fadeIn();
			return false;
		}
		$('input:not([name=id][name=type]), textarea:not([tabindex=-1])', this).each(function(){
			opts += '&'+this.name+'='+escape(this.value);
		});
		
		var pageId = $(this).find('input[name="id"]');
		
		$('.tx-thmailformplus-pi1').animate({ opacity: 0.3 });

		$.get('index.php?id='+pageId.attr('value')+'&type=125'+opts, function(data){
			$('.tx-thmailformplus-pi1').html(data);
		});
		
		$('.tx-thmailformplus-pi1').ajaxSuccess(function(evt, request, settings){
			$(this).animate({ opacity: 1 });
		});

		return false;
	});
}

/*var spinner={
	init: function(){
		jQuery('body').append('<div id="user_spinner" style="overflow: hidden; position: absolute; top: 0; left: 0; z-index: 10001; width: 32px; height: 32px; display: none;"><img src="typo3conf/ext/imp_template/images/spinner.gif" alt="spinner" /></div>');
	},
	show: function(){
		jQuery('#user_spinner')
			.css({ top:(jQuery(window).height()/2 - 12 + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)), left:(jQuery(window).width()/2 - 12) })
		.show();
	},
	hide: function(){
		jQuery('#user_spinner').hide();
	}
};*/
var sbo = {
	startSlideAfter: 7000,
	sliderDelay: 7000,
	animationDuration: 1200,
	currentShowcase: null,
	animationInProgress: false,
	requestedSet: -1,
	slideSetHandle: null,
	total: 0,
	thumbWidth: 0
};
$(document).ready(function($) {
	if($('.showcase').length>1 && typeof(showcase)!='undefined') {
		for(key in showcase) sbo.total++;
		sbo.thumbWidth = $('.thumbnails li').not('#thumbact').eq(0).outerWidth();
		//spinner.init();
		
		sbo.currentShowcase = $('#showcase1');
		sbo.currentShowcase.parent().children().filter('.showcase').each(function(i,el){this.itemIndex = i;});

		function callbackSet(obj){
			//spinner.hide();
			obj.parent().children().filter('.showcase').not(obj.get(0)).not(sbo.currentShowcase.get(0)).hide().css({'z-index':'28', left: 0});
			sbo.currentShowcase.css({'z-index':'29'}).slideLeftHide(sbo.animationDuration, function(){
				sbo.currentShowcase = obj;
				sbo.animationInProgress = false;
				if(sbo.requestedSet>0){
					var t = sbo.requestedSet;
					sbo.requestedSet = -1;
					setTimeout(function(){ runSet(t, callbackSet); }, 10);
				}
			});
			obj.css({'z-index':'28', left: 0}).show();
			
		}
		
		function runSet(i, func, delay){//i=0,1,2,3
			if(sbo.currentShowcase.get(0).itemIndex == i)
				return;
			if(sbo.animationInProgress){
				sbo.requestedSet = i;
				return;
			}
			thumbs(i);
			var realId = 'showcase'+(i+1);
			if(showcase && typeof(showcase[realId])!='undefined' && typeof(showcase[realId].loaded)=='undefined'){//load
				var imgs = showcase[realId];
				//spinner.show();
				$.preLoadImages([imgs.img1,	imgs.img2],function(list){
					showcase[realId].loaded = true;
					//spinner.hide();
					var div1 = $('#'+realId);
					if(div1.length)
						div1.get(0).style.backgroundImage = 'url(' + list[0] +')'; 
						
					var div2 = div1.find('.image');
					if(div2.length)
						div2.get(0).style.backgroundImage = 'url(' + list[1] +')'; 

					if(delay)
						setTimeout(function(){ func && func(div1); }, delay);
					else
						func && func(div1);
				});
			}else{//loaded
				func && func($('#'+realId));
			}	
		}
		function slideSet(reinit){		
			if(!reinit){
				if(callbackSet){
					var next = sbo.currentShowcase.get(0).itemIndex+1;
					runSet(next<=sbo.total?next:0, callbackSet);				
				}else{
					runSet(1, callbackSet);
				}
			}
			clearTimeout(sbo.slideSetHandle);
			sbo.slideSetHandle = setTimeout(slideSet, reinit ? reinit : sbo.sliderDelay);
		}
		function thumbs(index){
			//$('.thumbnails li').removeClass('act').filter(function(){return this.itemIndex==index; }).addClass('act');		
			$('#thumbact').animate({left: index*sbo.thumbWidth }, 'slow'); 
		}
		$('.thumbnails li').not('#thumbact').each(function(i,el){this.itemIndex = i;}).click(function(){
			runSet(this.itemIndex, callbackSet);
			slideSet(15000);
		});//.eq(0).addClass('act');
		setTimeout(slideSet, sbo.startSlideAfter);
	}
	
	
	

	$('.i-text.trigger').focus(function(){
		if($(this).attr('title') == $(this).val()) $(this).val('');
	}).blur(function(){
		if($(this).val() == '') $(this).val($(this).attr('title'));
	});
	
	$('select.jqtransform').jqTransSelect();
	
	$('.slider').each(function(){
		$(this).scrollable({
			size: 1,
			clickable: false,
			easing: 'easeInOutExpo',
			circular: true,
			next: '.nextPage', 
			prev: '.prevPage'
		}).each(function(){
			if($(this).hasClass('auto-1')) {
				$(this).autoscroll({ autoplay: true, interval: 5000 });
			}
		});
	});
	
	
	var hoverHandle = null;
	
	$('.project-w .project-i').hover(function(){
		var image = $(this);
		var layer = $(this).next();
		layer.addClass('locked');
		setTimeout(function() {
			if(image.next().hasClass('locked')) {
				layer.find('p, div').css({ opacity: 0 });
				layer.animate({ left: 0 }, 400, function(){ $(this).find('p, div').animate({ opacity: 1 }, 300) });
			}
		}, '400');
	}, function(){
		$(this).next().removeClass('locked');
		var layer = $(this).parent().find('.project-t');
		hoverHandle = setTimeout(function(){			
			tHoverFunc(layer);
		}, 1000);	
	});
	
	var tHoverFunc = function(layer){
		setTimeout(function() {
			layer.animate({ left: 224 }).find('p, div').animate({ opacity: 0 });
		}, '400');
	}
	$('.project-w .project-t').hover(function(){
	}, function(){
		var layer = $(this);
		tHoverFunc(layer);
	});
	$('.project-w .project-t').bind('mouseover', function(){
		if(hoverHandle) clearTimeout(hoverHandle);
	});
	
	function inputFileTransform(){
		var strButtonTitle = '';
		var lang_lable = {"uploadFile":"Browse","uploadFile_ua":"Додати","uploadFile_ru":"Добавить"};
		strButtonTitle = lang_lable['uploadFile']
		if($('body').hasClass('ua')) {
			strButtonTitle = lang_lable['uploadFile_ua'];
		} else if($('body').hasClass('ru')) {
			strButtonTitle = lang_lable['uploadFile_ru'];
		}
		$('input[name=file]').each(function(){
			$(this)
				.wrap('<span class="fake-input-file"></span>')
				.after('<input type="text" readonly="readonly" class="i-text" /><span class="i-button">' + strButtonTitle + '</span>')
				.change(function(){
					$(this).siblings('input[type=text]').val($(this).val());
				});
		});
		$('.box .l, .box .b').css('bottom', '-1px');
	}

	function linkHandler() {
		var objLinksArr = $('a:not([href^=#])');
		var currentDomain=top.location.hostname;
		var seqURL='';
		for (eachLink in objLinksArr){
			if(objLinksArr[eachLink].href){
				if(objLinksArr[eachLink].href.indexOf('javascript') == -1){
					seqURL = objLinksArr[eachLink].href;
					seqURL = seqURL.replace(/http:\/\//gi,'');
					seqURL = seqURL.replace(/https:\/\//gi,'');
					seqURL = seqURL.split('/');
					if(seqURL[0] != currentDomain){
						$(objLinksArr[eachLink]).click(function() {
							window.open(this.href);
							return false;
						});
					}
				}
			}
		}
	}
	  // project list
	$('.project-t').each(function(){
		var link = $(this).find('.more a')[0].href;
		$(this).click(function(){ location.href = link; });
	});
	
		// textarea auto resizer
	$('#fqr-question').autoResize();
	inputFileTransform();
	linkHandler();
	$('#form-fqr').formValidation();
});