var first =  1, currentUrl = location.href, project = {
	isScroll:0,
	cx:0,
	cy:0,
	scrollSpeed:20,
	slice:function(text, i){
		return text.length >= i ? text.substr(0, i)+'...' : text
	},
	linkEqual:function(l1, l2){
		var p1 = parseInt(/\d+/.exec(l1)||'1'), p2 = parseInt(/\d+/.exec(l2)||'1');
		return (l1 == l2) && (p1 == p2);
	},
	showImage:function(src, currentImg, images, callback){
		$('#work').css({
			'height':'auto'
		});
		$('#spinner div').fadeIn('slow', function(){
			
			$('#load-img').unbind('load').bind('load', function(){
						if(callback)callback();
						$('#spinner div').hide();
						var setup = $.browser.msie && $.browser.version <= 7 ? {opacity:'0', filter:'alpha(opacity=0)'}:{opacity:'0'}, setup2 = $.browser.msie && $.browser.version <= 7 ? {opacity:'1', filter:'alpha(opacity=100)'}:{opacity:'1'}
						$('#work > img:first-child').animate(setup,
						{
							duration:'slow',
							complete:function(){
								$('#work > img:first-child').attr('src', src);
								$('#work > img:first-child').animate(setup2, {duration:'slow'});
									$('#vow')[(($('#works-list a.act input').val())?'remove':'add')+'Class']('dis');
									var imageCount = 0;
									$.each(images, function(){
										imageCount++
									});
									$('div.number span:first-child').html(currentImg+1);
									$('div.number span:nth-child(2)').html(imageCount);
									$('#vow').attr('href', $('#works-list a.act input').val()?'http://'+$('#works-list a.act input').val():'#');
									$('#work').css({
										'height':'auto'
									});
									$('#pw, #nw')[(imageCount>1?'remove':'add')+'Class']('dis');
									$('div.number').css({
										'opacity':imageCount>1?'1':'0.1',
										'filter':'alpha(opacity='+(imageCount>1?'100':'10')+')',
									});
									if(callback)callback();
							}
						});
						
					}).attr('src', src);
			
			
		})
	},
	scr: function(){
		var diff = $('#work > img').offset().top + $('#work > img').height() - ($(document).scrollTop() + $(window).height()), down = diff<=10 && $(':visible').index();
		$('#nav-panel').css({
			position:'fixed',
			bottom:diff>10?'10px':($(document).scrollTop() + $(window).height()) - ($('#work > img').offset().top + $('#work > img').height()) +'px',
			left:$('#work').offset().left+238+'px',
		});
		
	},
	loadWork:function(link){
		var pnum = /\d+/.exec(link.substring(link.length-1, link.length));
		if(first && project.linkEqual(location.href.replace(/#.*/, ''), link))return;
		if(first && link == location.href.replace('http://'+document.domain, '').replace(/#.*/, ''))return;
		currentUrl = link;
		if(!link){
			link = location.href.replace(/\/$/, '');
			if(first)return;
		}
		var null_tag = /\/[^\/]*$/.exec($('#works-list a')[0].href);
		var tag = /\/[^\/]*$/.exec((/portfolio$/.test(link))?$('#works-list a')[0].href:link).toString(), activeLink = $('#works-list a[href$='+tag+']');
		if(activeLink.length == 0)return;
		if(first && tag == /\/[^\/#]*/.exec($('#works-list a.act').attr('href')))return;
		$('#works-list a').removeClass('act');
		activeLink.addClass('act');
		images = eval('('+activeLink.attr('rel')+')');
		currentImg = 0;
		project.moveScroll(activeLink);
		project.showImage('images/portfolio/'+images[currentImg], currentImg, images, project.scr);
	},
	moveScroll:function(activeLink){
		var x = (activeLink.offset().left + activeLink.width()) - ($('#works-list').offset().left + $('#works-list').width()), x2 = $('#works-list').offset().left - activeLink.offset().left, complete = function(){
					if(x>0 || x2>0)
						$('.track').animate({
							marginLeft:Math.max(7, $('.scroll').width()*(Math.abs(parseInt($('#works-list > div:first-child div').css('marginLeft')))/$('#works-list > div:first-child div').width()))+'px'
						}, {
							'duration':'slow',
							'complete':function(){
								project.setOpacity();
							}
						});
				};
		if(x>0)
			$('#works-list > div:first-child div').animate({
				marginLeft:parseInt($('#works-list > div:first-child div').css('marginLeft'))-x+'px'
			}, {
				'duration':'slow',
				'complete':complete
			});
		else if(x2>0)
			$('#works-list > div:first-child div').css({
				marginLeft:parseInt($('#works-list > div:first-child div').css('marginLeft'))+x2+'px'
			}, {
				'duration':'slow',
				'complete':complete
			});
		if(x2>0)complete()
	},
	setScroll:function(){
		$('.scroll .track').css({
			width:$('.scroll').width()*($('#works-list').width()/($('#works-list div:first-child div').width()))+'px',
		});
	},
	scrollContent:function(content, step, dir, callback){
		if(this.is_scroll)return;
		this.is_scroll = 1;
		var prnt = content.parents()[0], func = 'min', offset = content.width() - $(prnt).width(), val = parseInt(content.css('marginLeft'))
		if(dir == 'right'){
			step = -step;
			offset = -offset;
			func = 'max';
		}else
			offset = 0;
		var stp = Math[func](offset, val+step);
		var off_right = $(prnt).width()+Math.abs(stp) == content.width();
		$('.sh-right, .asr', $(prnt).parents('#works-list')[0])[off_right && dir=="left"?'hide':'show']();
		$('.sh-left, .asl', $(prnt).parents('#works-list')[0])[stp == 0 && dir=="right"?'hide':'show']();
		content.animate({marginLeft:stp+'px'}, {
			duration:'slow',
			complete:function(){
				$('.sh-right, .asr', $(prnt).parents('#works-list')[0])[off_right?'hide':'show']();
				$('.sh-left, .asl', $(prnt).parents('#works-list')[0])[stp == 0?'hide':'show']();
				project.is_scroll = 0;
				if(callback)callback();
			},
			step:function(){
				$('.scroll .track').css({
					marginLeft:Math.abs(parseInt($('#works-list div:first-child > div').css('marginLeft')))*$('.track').width()/$('#works-list').width()+'px',
				});
				project.setOpacity()
			}
		});
		return stp;
	},
	scroll:function(){
		var cl = $('#clients p:first-child').clone();
		$('img', cl[0]).removeClass('first');
		cl.appendTo('#container');
		setInterval(function(){
			$('#clients p:first-child').each(function(){
				var t = this;
				var nm = (parseInt($(t).css('marginLeft'))-1);
				if(nm == -($(this).width()))
					nm = 0;
				$(this).css({
					marginLeft:nm+'px'
				});
			})
		}, project.scrollSpeed);
	},
	scroller:function(e){
		if($('.track, .track div').index(e.target||e.srcElement)+1 && !(/move/.test(e.type)))return
		var x = (e.X||e.pageX) - $('.scroll').offset().left;
		if(!(/down/.test(e.type)))x -= project.cx;
		if(project.isScroll || /down/.test(e.type)){
			var margin = Math.min($('.scroll').width() - $('.track').width(), Math.max(7, x));
				if(/down/.test(e.type) && ($('.scroll').width() - $('.track').width() - margin) > $('.track').width()/2){
					margin -= $('.track').width()/2;
					margin = Math.min($('.scroll').width() - $('.track').width(), Math.max(7, margin));
				}
				if((/down/.test(e.type)))
				$('.track').animate({
					marginLeft:margin+'px'
				}, {
				'duration':'slow',
				'step':function(){
					project.setOpacity();
				}
			});
			else{
				$('.track').css({
					marginLeft:margin+'px'
				}
			);
			project.setOpacity();
			}
			var worksPos = -$('#works-list').width()/($('.track').width()-2)*(parseInt(margin)-7), diff = -($('#works-list div:first-child div').width() - $('#works-list').width());
			//var step = $('.scroll').width()/parseInt($('.track').css('marginLeft'), workPos = -;
				if((/down/.test(e.type)))
				$('#works-list div:first-child div').animate({
					marginLeft:Math.max(diff, worksPos)+'px'
				}, {
				'duration':'slow'
				/*'step':function(){
					project.setOpacity();
				}*/
			});
			else
				$('#works-list div:first-child div').css({
					marginLeft:Math.max(diff, worksPos)+'px'
				});
			//project.setOpacity()
			$('#works-list .sh-left')[worksPos == 0?'hide':'show']();
			$('#works-list .sh-right')[worksPos <= diff+10?'hide':'show']();
		}
	},
	centerSpinner:function(){
		
	},
	loadService:function(link){
		if(!link)link = /\/[^\/]*$/.exec(location.href);
		if(link == '/services')
			link = /\/[^\/]*$/.exec($('#services a')[0].href).toString();
		$('#services a').removeClass('act');
		$('#services a[href$='+link+']').addClass('act');
		$('#content-left').fadeOut('fast', function(){
		$.ajax({
			url:'services'+link+'/json',
			type:'GET',
			dataType:'json',
			success:function(json){
				$('#content-left').html('<h1>'+json['service']['head']+'</h1>'+json['service']['description']+'<img src="images/diag/'+json['service']['diagram']+'" alt="" class="diagram"'+(json['service']['tag'] == 'support'?' style="top:283px"':'')+' />');
				$('#content-left').fadeIn('fast');
			}
		});
	})
	},
	setOpacity: function(){
		$('.scroll div.category').each(function(){
			var distance = Math.max(parseInt($('.track').css('marginLeft')) - parseInt($(this).css('left')), (parseInt($(this).css('left'))) - (parseInt($('.track').css('marginLeft')) + $('.track').width())), 
			maxDistance = /*Math.max(parseInt($(this).css('left')) - $('.track').width(), $('.scroll').width() - (parseInt($(this).css('left')) + $(this).width()) - $('.track').width())*/Math.max(parseInt($('.track').css('marginLeft')), $('.scroll').width() - (parseInt($('.track').css('marginLeft')) + $('.track').width())), 
			step = 60/maxDistance;
			if(distance < 0 )distance = 0;
			var opacity = Math.max(40, Math.abs(100 - (step*distance)));
			$(this).css({opacity:opacity/100, filter:'alpha(opacity='+opacity+')'});
		});
	},
	filesize:function(bytes){
		kb = parseFloat(/\d+/.exec(bytes/1024).toString());
		mb = parseFloat(/\d+(?:\.\d{0,2}|)/.exec(bytes/1024/1024).toString());
		gb = parseFloat(/\d+(?:\.\d{0,2}|)/.exec(bytes/1024/1024/1024).toString());
		return gb > 1 ? gb+"G" : (mb > 1 ? mb+"M" : kb+"K");
	},
	clientDetect:function(){
		$.each({
			'Chrome':4,
			'Safari':3,
			'Opera':10,
			'Firefox':3,
			'Explorer':8,
		}, function(i,v){
			var version = $.client.version, browser = $.client.browser;
			if($.browser.msie){
				browser = 'Explorer';
				version = $.browser.version;
			}
			if(browser == i && parseInt(/\d+/.exec(version)) < v){
				$('#overlay').css({'width':$(document).width()+'px', 'height':$(document).height()+'px',}).show();
			}
		});
	}
}

$(function(){
	
	$('a[href*=#]').click(function(){return false});
	$('a').click(function(){if(/^(?:dis|act)/.test(this.className))return false});
	$('.feedback textarea').keyup(function(){
		$('a.button', $(this).parents('.feedback')[0])[(this.value?'remove':'add')+'Class']('dis');
	});
	var empty = 1;
	$('.feedback textarea').blur(function(){
		empty = this.value?0:1;
		this.style.color = empty?'#999':'#000';
		this.value = empty?tarea_title:this.value;
	});
	/*$('.feedback textarea').each(function(){
		empty = this.value?0:1;
		this.style.color = empty?'#999':'#000';
		this.value = empty?tarea_title:this.value;
	});*/
	$('.feedback textarea').focus(function(){
		if(empty)this.value = '';
		this.style.color = '#000';
		$('.balloon').animate({
			opacity:'0',
			filter:'alpha(opacity=0)'
		}, 'slow', function(){$(this).css('visibility', 'hidden')});
	});
	$('.feedback a.button .balloon').click(function(){return false});
	$('.feedback a.button').click(function(){
		var t = this, txt = $('textarea', $(this).parents('.feedback')[0]), phone = /(\+380|\+38)?[ -.]?(\()?\d{2,3}(\))?[ -.]?\d{2,3}[ -.]?\d{2,3}[ -.]?\d{2,3}/gi, email = /[\w\.]+@\w+(\.\w{2,3}){1,2}/gi;
		if(/dis/.test(this.className))return false;
		if(!(phone.test(txt.val()) || email.test(txt.val())))
			if($('.balloon').css('visibility') == 'hidden'){
				$('.balloon').css('visibility', 'visible').animate({
					opacity:'1',
					filter:'alpha(opacity=100)'
				}, 'slow');
				return false
			}
		$('.balloon').animate({
			opacity:'0',
			filter:'alpha(opacity=0)'
		}, 'slow', function(){$(this).css('visibility', 'hidden')});
		$(this).addClass('dis');
		var data = $(t).parents('form').serialize();
		txt.attr({
			'readonly': 'readonly',
			'disabled': 'disabled'
		}).css({
		'color': '#999',
		'background':'#fff'
			});
		$('#spinner div', $(this).parents('.feedback')[0]).fadeIn('fast', function(){
			var frm = $(t).parents('form'), fd = $(t).parents('.feedback')[0];
			$.ajax({
				url:frm.attr('action'),
				type:'POST',
				dataType:'json',
				data:data,
				success:function(json){
					$('.low > div:nth-child(2)', fd).fadeOut('slow', function(){
						$('.low #response', fd).fadeIn('slow', function(){
							$('.files tr:visibile').remove();
							$('#attachments').hide();
							setTimeout(function(){$('.low #response', fd).hide(); $('.low > div:nth-child(2)', fd).fadeIn('slow')}, 1000);
						}).html(json['message']);
					});
					$('#spinner div', fd).fadeOut('fast');
					$('.feedback textarea').val(tarea_title).css('color', '#999').attr({'readonly': '', 'disabled':''});
					$(this).removeClass('dis');
					empty = 1;
				}
			});
		});
	});
	if(!($('#splash').length))project.scroll();
	//$('#big-btn a:nth-child(2)').click(function(){return false}).css('cursor', 'default');
	$('#big-btn a').click(function(){$(this).addClass('act')});
	$('.feedback textarea').val(tarea_title);
	$('#menu a').click(function(){if(/act/.test(this.className))return false; $('#menu a').removeClass('act');$(this).addClass('act'); location = this.href; return false});
	$('.opensite').click(function(){
		$('#overlay').hide();
		$.ajax({
			url:'counter',
			type:'POST',
			dataType:'json',
			success:function(){},
		});
	});
	
	$('.team-row .feedback .low span').each(function(){
		//this.innerHTML = project.slice(this.innerHTML, 15)
	});
	$('#vow').remove('click').click(function(){
		if(/#/.test(this.href))return false;
		window.open(this.href);
	});
	$('#vow img[src*=ru]').parents('span').css('width', '82px');
	
	if($('#works-list').length)$('#works-list').mousewheel(function(e, delta){
		var stp = project.scrollContent($('div:first-child > div', this), $(this).width(), delta>0?'left':'right');
		return false;
	});
	
	$('#services a').mousedown(function(){$(this).addClass('act')});
	
	$('.product a[href!=#]').attr('target', 'top');
})

$('.cpt_category_tree li[class*=parent] a').click(function(){
	var t = $(this).parents('li')[0], toggle = function(){
		$('.cpt_category_tree li[class*=parent]').removeClass('parent_current').addClass('parent');
		$(t).addClass('parent_current').removeClass('parent');
		$(t).nextUntil('.parent').slideToggle();
		$('.parent').nextUntil('.parent').slideUp();
	}
	if(!($(t).next('.child').length)){
		$(t).load(this.href + ' li.parent_current, li.child', null, toggle);
	}else
		toggle();
	return false;
});
