(function($){
	
	$.fn.inputValue = function(settings) {
		
		var $field = $(this);
		var default_value = settings['default_value'];
		var default_color = settings['default_color'];
		var active_color = settings['active_color'];
		
		if ($field.val() == '') {
			$field.val(default_value);
		};
		
		$field.css({'color' : default_color})
		.focus(function(){
			clearValue();
		})
		.blur(function(){
			fillValue();
		});
		
		function clearValue() {
			if ($field.val() == default_value) {
				$field.val('');
			};
			$field.css({'color' : active_color});
		};
		
		function fillValue() {
			if ($field.val() == '') {
				$field.val(default_value);
			};
			$field.css({'color' : default_color});
		};
	};
	
	$.fn.billboard = function(num) {
		var size = $('li', this).size()-1;
		var position = 0;
		var $piclist = $('li', this);
		var movingTime = 500;
		
		$piclist.eq(0).show();
		
		var $next = $('.next', this);
		var $prev = $('.prev', this);
		
		
		function checkFirst(){
			if (position == 0){
				$prev.hide();
				return false;
			} else {
				$prev.css({'display':'block'});
				return true;
			}
		}
		function checkLast(){
			if (position == size){
				$next.hide();
				return false;
			} else {
				$next.css({'display':'block'});
				return true;
			}
		}
		function checkBorders(){
			checkFirst()
			checkLast()
		}
		checkBorders()
		
		
		function forward(){
			$piclist.eq(position).fadeOut(movingTime);
			if (checkLast()){
				$piclist.eq(position+1).fadeIn(movingTime);
				position++;
			} else {
				position = 0;
				$piclist.eq(position).fadeIn(movingTime);
			}
			checkBorders()
		}
		function backward(){
			$piclist.eq(position).fadeOut(movingTime);
			if (checkFirst()){
				$piclist.eq(position-1).fadeIn(movingTime);
				position--;
			} else {
				position = size;
				$piclist.eq(position).fadeIn(movingTime);
			}
			checkBorders()
		}
		
		
		$next.click(function(){
			forward()
		})
		
		$prev.click(function(){
			backward()
		})
		
	};
	
	$.fn.indexBillboard = function() {
		
		var $pics = $('ul.pics li', this);
		var picsNum = $pics.size();
		var $holesWrap = $('ul.holes', this);
		$pics.each(function(index){
			$('<li></li>').appendTo($holesWrap)
		});
		var $holes = $('ul.holes li', this);
		$holes.each(function(index){
			$(this).data('position',index)
		});
		var pos = 0;
		var $dot = $('.dot', this);
		//var $next = $('.next');
		//var $prev = $('.prev');
		var timeout = 8000;
		var switchTime = 1000;
		$pics.eq(0).css('zIndex', 1)
		
		$holes.click(function(){
			pos = $(this).data('position');
			changePic();
			moveDot();
		});
		
		function changePic(){
			$pics.not($pics.eq(pos)).fadeOut(switchTime);
			$pics.eq(pos).fadeIn(switchTime);
			clearInterval(timeoutId);
			timeoutId = setInterval(moveForward, timeout)
		};
		
		function moveDot(){
			$dot.animate({
				left:20*pos
			},switchTime)
		};
		
		function checkEdge(){
			if (pos == picsNum - 1){
				return 'rightEdge';
			} 
			if (pos == 0){
				return 'leftEdge';
			}
		};
		
		/*
		$next.click(function(){
			moveForward();
		});
		$prev.click(function(){
			moveBackward();
		});
		*/
		function moveForward(){
			if (checkEdge() != 'rightEdge'){
				pos++;
				moveDot();
				changePic();
			} else {
				pos = 0;
				moveDot();
				changePic();
			}
		};
		function moveBackward(){
			if (checkEdge() != 'leftEdge'){
				pos--;
				moveDot();
				changePic();
			} else {
				pos = picsNum - 1;
				moveDot();
				changePic();
			}
		};
		
		
		timeoutId = setInterval(moveForward, timeout);
	};
	
	$.fn.autoChange = function(num) {
		var $pictures = $(this).find("li");
		var numbr = $pictures.size();
		var fadingTime = 1000;
		var pause = 5000;
		var index = 0;
		$pictures.hide();
		$pictures.eq(index).show();
		function autoChange(){
			if (index < numbr) {
				$pictures.eq(index).fadeOut(fadingTime);
				$pictures.eq(index + 1).fadeIn(fadingTime);
				index++;
			}
			if (index == numbr) {
				$pictures.eq(index).fadeOut(fadingTime);
				index = 0;
				$pictures.eq(index).fadeIn(fadingTime);
			}
		}
		setInterval(autoChange, pause)
	};
	
	
	
	function popupArrange(){
		var $form = $('.popup');
		var $html = $('html');
		var pos = $form.css('position');
		var top;
		if (pos == 'fixed'){
			top = ($html.height() - $form.innerHeight())/2;
		} else {
			top = document.getElementsByTagName("html")[0].scrollTop + ($html.height() - $form.innerHeight())/2;
		}
		$form.css({'top':top});
	}
	
	function dlForm(){
		var target;
		var type;
		var down;
		var $form = $('.popup');
		var $cover = $('.cover');
		var $footer = $('.footer');
		var down; // download
		$cover.click(function(){
			$form.hide();
			$cover.hide();
			$footer.css({'position':'relative'});
		});
		$('html').keyup(function(e){
			if(e.keyCode == 27 || e.charCode == 27 || e.which == 27){
				$form.hide();
				$cover.hide();
			};
		});
		$('.dl,.invite a').click(function(e){
			target = 0;
			target = $(this).attr('rel');
			type = $(this).attr('type');
			$form.show();
			$cover.show();
			popupArrange();
			$footer.css({'position':'static'});
			
			e.preventDefault();
			
			if (target) {
				$('.popup .target').val(target);
			}
			if (type){
				$('.popup .type').val(type);
			}
			if (type == 'service'){
				down = 0;
				$('.popup h4').text('In order to order, please fill the form.');
			}
			if (type == 'presentation' || $(this).parents('.invite').size()){
				down = 0;
				$('.popup h4').text('In order to invite us for presentation, please fill the form.');
			}
			if (type == 'presentation_dl'){
				down = 1;
				$('.popup h4').text('In order to download the presentation, please fill the form.');
			}
			if (type == 'material'){
				down = 1;
				$('.popup h4').text('In order to download the material, please fill the form.');
			}
			if (type == 'registration'){
				down = 0;
				$('.popup h4').text('In order to register for the event, please fill the form.');
			}
			if (type == 'portfolio'){
				down = 1;
				$('.popup h4').text('In order to download our portfolio, please fill the form.');
			}
			if (type == 'offer'){
				down = 0;
				$('.popup h4').text('In order to request free quote, please fill the form.');
			}
			if (type == 'comment'){
				down = 0;
				$('.popup h4').text('In order to get a short comment, please fill the form.');
			}
			
		});
		$('.popup .close').click(function(){
			$form.hide();
			$cover.hide();
			$footer.css({'position':'relative'});
		});
		
		$('.popup .submit').click(function(){
			var testForm = $(this).parents('form').checkForm();
			var $ourForm = $(this).parents('form');
			if (testForm){
				try {
					_gaq.push (['_trackEvent',location.href,type,target]);
					_gaq.push (['_trackPageview', '/formsubmit/'+type+'/']);
				} catch (error) {
				
				}
			    var name = $('#dl_name').val();
                var company = $('#dl_company').val();
                var phone = $('#dl_phone').val();
                var mail = $('#dl_email').val();
                var comment = $('#dl_comment').val();
                $.post("/push2Highrise.php", { name:name, company:company, phone:phone, mail:mail, comment:comment });
				if(down == 1){
					$ourForm.submit();
					$form.hide();
					$cover.hide();
					$footer.css({'position':'relative'});
				}
				if (down == 0){
					$ourForm.html('<h3 style="text-align:center;color:#000;font-size:30px;font-weight:normal">Спасибо за обращение, мы свяжемся с вами в ближайшее время.</h3>');
				}
				
			}
		});
		
		
	}
	$.fn.checkForm = function(){
		var error = false;
		var email = new RegExp("[0-9a-z_.-]+@[0-9a-z_^.]+\\.[a-z]{2,4}", 'i');
		var $form = $(this);
		
		$form.find('.text').each(function(){
			if((this.value.length < 3) || ($(this).hasClass('phone') && this.value.length < 7) || ($(this).hasClass('email') && !email.test(this.value))){
				error = true;
				$(this).addClass('err');
			} else {
				$(this).removeClass('err');
			}
		});
		return !error;
	}
	
	$.fn.checkForm2 = function(){
		var error = false;
		var email = new RegExp("[0-9a-z_.-]+@[0-9a-z_^.]+\\.[a-z]{2,4}", 'i');
		var $form = $(this);
		
		$form.find('.req').each(function(){
			if((this.value.length < 3) || ($(this).hasClass('phone') && this.value.length < 7) || ($(this).hasClass('email') && !email.test(this.value))){
				error = true;
				$(this).parent('p').addClass('err');
			} else {
				$(this).parent('p').removeClass('err');
			}
		});
		return !error;
	}
	
	
	

	
	$(document).ready(function(){
		$('.footer #search').inputValue({
			default_value: 'Search',
			default_color: '#7c7f81',
			active_color: '#000'
		});
		$('.footer #subscribe').inputValue({
			default_value: 'subscribe@email',
			default_color: '#979b9f',
			active_color: '#000'
		});
		$('.billboard').billboard();
		$('.index-billboard').indexBillboard();
		$('.autochange').autoChange();
		dlForm();
		$('form.post').submit(function(){
			return ($(this).checkForm2());
		});
		
		$('.results .switcher').show().click(function(){
			if ($('.chart:visible').size()){
				$('.chart').fadeOut();
				$('.results .before, .results .after').fadeIn();
				$(this).html('<span>Результаты</span> &rarr;');
			} else {
				$('.chart').fadeIn();
				$('.results .before').add('.results .after').fadeOut();
				$(this).html('&larr; <span>Изменения</span>');
			}
		})
	})
	
	$(window).resize(function(){
		popupArrange();
	}).scroll(function(){
		popupArrange();
	});
	
	
	
})(jQuery);
