String.prototype.replaceAll = function(search, replace){
  return this.split(search).join(replace);
}

$(function(){
	
	
	//добавлять к каждой форме <input type=hidden name=no_robot value=1>
	//защиты от автоматических отправок
	$('form').each(function(index,value)
			{
				$(this).prepend('<input type="hidden" name="no_robot" value="1"/>');
			});
	
	//------------------------------------
	
	$('.tel-location').click(function(){
		$("#call-form_input").val('');
		$("#call-form-answer").hide();
		$('#call-form form').show();
		$('#call-form').css('display','block');
	    $('#call-form_input').focus();
	    return false;
	        
	});
	$('.tel-ico').click(function(){
		$("#call-form-answer").hide();
		$("#call-form_input").val('');
		$('#call-form form').show();
		$('#call-form').css('display','block');
	        $('#call-form_input').focus();
	});
	$('#call-form').mouseleave(function(){
		$(this).css('display','none');
	});		/* show overlay */	$("#form_seo_close").click(function(){		$("#form_seo_close").css('display','none').css('z-index','1');		$("#OverLay").remove();		$("#seo_form").css("z-index","1");		$("#seo_form").removeClass();		return;	});	$("#siteAdress").click(function(){		$("#person").click();	});	$("#phoneNumber").click(function(){		$("#person").click();	});	$("#email").click(function(){		$("#person").click();	});	$("#person").click(function(){		$(".wrapper").before('<div id="OverLay"></div>');		$("#form_seo_close").css('display','block').css('z-index','1201');		$("#OverLay").css("display","block").css("height", $('#wrapper').height());		$("#seo_form").css("z-index","1200");		$("#seo_form").addClass("seo_form_over");	});	/* end overlay */
	//function when click on call button
	
	$("#call-button").click(function(){
		var tel = $("#call-form_input").val();
		tel=tel.replaceAll('8 (','8');
		tel=tel.replaceAll('-','');
		tel=tel.replaceAll(') ','');
		$("#call-form_input").val(tel);
		$("#number_client").val(tel);
		if (tel!='' && tel!=$("#call-form_input").attr('title'))
			{
				$('#call-form form').hide();
				$('#call-form-answer').show();
				$.post('', $('#call-form form').serialize(), function(respond){
					
					});
			}else
				{
				   alert("Нужно заполнить "+$("#call-form_input").attr('title')+'.');
				}
		
		
	});
	
	if($(".telephone").length)
		{
			$(".telephone").focusin(function(){
				$(".telephone").mask('8 (999) 999-99-99');
			});
			
		}
	
	$('#call-form_input').mask('8 (999) 999-99-99');
	$('#call-form_input').focus(function(){
		$(this).css('color','#000000');
	})
	.change(function(){
		if($(this).val()=='')
		{
			$(this).val('Телефон');
			$(this).css('color','#999999');
		}
	});
	/***** Sites portfolio elements behavior *****/
	$(".b-work")
	.hover(
		function(){$(this).addClass('b-work-active')},
		function(){$(this).removeClass('b-work-active')}
	)
	.click(function(){
		location = $('.b-work-active h3 a').attr("href");
	})
	/*********************************************/
	
	/***** Sites portfolio paginator *****/
	$('.num-nav li').click(function(){
		if( !$(this).hasClass('active') ){
			$.cookie('pagination', $(this).children('a').text());
		}
	});
	/*************************************/
	
	/***** SEO portfolio toggle *****/
	$('ul.sub-nav.positions li').click(function(){
		if($(this).hasClass('inactive')){
			window.location.hash = $(this).attr('title');
			seoPortfolioToggle();
		}
	})
	/********************************/
	
	/***** Clients-reports catalogue toggle *****/
	$('ul.sub-nav#categories li').click(function(){
		if($(this).hasClass('inactive')){
			changeSubnavClasses($(this));
			listDisplayToggleByTitle($(this).attr('title'), $('ul.clients'));
		}
	})
	/********************************************/
	
	/***** Positions carousel *****/
	$(".b-pos .vcarousel").jCarouselLite({
							visible: 5,
							vertical: true,
						    auto: 1200,
						    speed: 1000}).css({'height': 267, 'z-index':1});
	/******************************/
	
	/***** Phone numbers fields masking *****/
	if($('#phoneNumber').length)
		{
			$('#phoneNumber').focusin(function(){
				$('#phoneNumber').mask("8 (999) 999-99-99");
			});
		}
	//$('input[name=phoneNumber]').mask("8 (999) 999-99-99");
	/****************************************/
	
	
	/***** Partners carousel *****/
	$(".carusel2 .carusel2-in").jCarouselLite({
	    btnNext: ".ar-r2 i",
	    visible: 1,
	    mouseWheel: true
	});
	$('li.partner').click(function(){location = "/sertificates/"});
	/*****************************/
	
	/***** Clients-reports carousels *****/
	$('.carusel#clients .carusel-in').jCarouselLite({
								visible: 4,
								btnNext: ".ar-r1 i",
								cicle: true,
								mouseWheel: true
	});
	
	$('.carusel#reports .carusel-in').jCarouselLite({
		visible: 4,
		mouseWheel: true,
		btnNext: ".rep i"
	}).parent().hide();
	$('.fancybox').fancybox({mouseWheel: true});
	//$('.carusel#reports img').click(function(){console.log($(this).attr('src')); $.fancybox({href: $(this).attr('src'), type: 'image'});});
	/****************************/
	
	/***** Sites portfolio list *****/
	$(".b-work").hover(
			function(){
				$(this).addClass("b-work-active");
				 return false;
			}, function() {
		        $(this).removeClass("b-work-active");

		    });
	/*******************************/
	
	/***** Corousels on main page toggle *****/
	$('ul.sub-nav.main_page li').click(function(){
		if($(this).hasClass('inactive')){
			$(this).removeClass('inactive').siblings().addClass('inactive')
					.parent().siblings('.carusel').toggle();
		}
	})
	/*****************************************/
	
	/***** Black-white images behavior *****/
	$('img.bw').hover(
			function(){$(this).data('bwpic', $(this).attr('src')); $(this).attr('src', $(this).attr('src').replace('_bw', '_color'));},
			function(){$(this).attr('src', $(this).data('bwpic'));}
	);
	/***************************************/
	
	/***** Form fields behavior *****/
	$('input[type=text][title], textarea[title]').focusin(function(){if($(this).val() == $(this).attr('title')){$(this).val('');}})
								.focusout(function(){if($(this).val() == ""){$(this).val($(this).attr('title'));}});
	/********************************/
	
	/***** Calculator form behavior *****/
	$('form[name=calculator] #person').change(function(){fieldValueIsValid($(this), 'text', true);});
	$('form[name=calculator] #siteAdress').change(function(){fieldValueIsValid($(this), 'site', true);});
	$('form[name=calculator] #email').change(function(){fieldValueIsValid($(this), 'email', true);});
	$('form[name=calculator] input[type=button]').click(function(){	
		if($('#first_step').css('display') != 'none'){
			var personNameIsValid = fieldValueIsValid($('#first_step #person'), 'text');
			var siteNameIsValid = fieldValueIsValid($('#first_step #siteAdress'), 'site');
			var emailIsValid = fieldValueIsValid($('#first_step #email'), 'email');
			
			if(personNameIsValid && (siteNameIsValid || emailIsValid)){
				$(this).val('Рассчитать');
				$('#first_step').hide(); $('#second_step').show(); $('#phoneNumber').focus();
			} else {
				if(! personNameIsValid){
					$('form[name=calculator] #person').css({color: 'red'});
				}
				if(! siteNameIsValid){
					$('form[name=calculator] #siteAdress').css({color: 'red'});
				}
				if(! emailIsValid){
					$('form[name=calculator] #email').css({color: 'red'});
				}
			}
		} else {

			//alert($('#phoneNumber').val());

			var phoneNumberIsValid = fieldValueIsValid($('#phoneNumber'), 'phone');
			//console.log(phoneNumberIsValid);
			if(phoneNumberIsValid){
				$('form[name=calculator]').hide(); $('#calculator-answer').show();
				$.post("", $('form[name=calculator]').serialize(), function(respond){
					
					});
			} else {$('#phoneNumber').css({color: 'red'});}
		}	
	});
	/********************************/
	
	/***** Feedback form behavior *****/
	$('form#feedback #feedback-person').change(function(){fieldValueIsValid($(this), 'text', true, true);});
	$('form#feedback #feedback-email').change(function(){fieldValueIsValid($(this), 'email', true, true);});
	$('form#feedback #feedback-phoneNumber').change(function(){fieldValueIsValid($(this), 'phone', true, true);});
	$('form#feedback #feedback-message').change(function(){fieldValueIsValid($(this), 'text', true, true);});
	$('form#feedback input[type=button]').click(function(){
		var personIsValid = fieldValueIsValid($('form#feedback #feedback-person'), 'text', true, true);
		var emailIsValid = fieldValueIsValid($('form#feedback #feedback-email'), 'email', true, true);
		var phoneIsValid = fieldValueIsValid($('form#feedback #feedback-phoneNumber'), 'phone', true, true);
		var messageIsValid = fieldValueIsValid($('form#feedback #feedback-message'), 'text', true, true);
		console.log(personIsValid, emailIsValid, phoneIsValid, messageIsValid);
		if(personIsValid && emailIsValid && phoneIsValid && messageIsValid){
			
			$('#feedback-body').hide();
			$('#feedback-answer').show();
			$.post('', $('form#feedback').serialize(), function(respond){
				
				});
		}
	});
	/**********************************/
	
	/***** Contacts toggle *****/
	$('ul.sub-nav.contacts li').click(function(){
		if($(this).hasClass('inactive')){
			$('div#' + $(this).attr('title')).show().siblings('div.contacts_info').hide();
			
			if($(this).attr('title')=="msk")
				{
					$("#address_msk").show();
					$("#address_spb").hide();
				}else
					{
						$("#address_msk").hide();
						$("#address_spb").show();
					}
			
			$(this).removeClass('inactive').siblings().addClass('inactive');
                        initMaps(mapCities[$(this).attr('title')],$(this).attr('title'));
//			changeMap(maps[$(this).attr('title')]);
		}
	}); 
	/***************************/
	
	$('#advpartners .carusel-in').jCarouselLite({visible: 4,
		btnNext: ".ar-r1 i",
		cicle: true,
		mouseWheel: true});

});

$(window).load(function(){
		$('.work-big-im div').jCarouselLite(
				   {visible: 1,
					btnNext: '#bigImgNext i',
					cicle: true,
					mouseWheel: true}).css({'margin-left': '60px'});
					
    var h_vc = $('.leftblock').height()-$('.calculation').height()-130;
        h_vc = $.trim($('.calculation').attr('class')) == 'calculation' ? $('.leftblock').height() - 61 : h_vc;
        h_vc = (h_vc > 267) ? h_vc : 267;
	$('.b-pos .vcarousel').css('height', h_vc);
});

function seoPortfolioToggle(){
	var searchEngines = ['Google', 'Yandex']
	if(window.location.hash && (se = $.inArray(strFirstUpper(window.location.hash.toLowerCase().substr(1)), searchEngines)) > -1){
		se = searchEngines[se];
	} else {return;}
	
	$seNavLi = $('ul.sub-nav li[title=' + se + ']');
	
	listDisplayToggleByTitle(se, $('ul.b-places'));
	changeSubnavClasses($seNavLi);
}

function listDisplayToggleByTitle(title, $ulGroup){
	if(!$ulGroup){$ulGroup = $('ul');}
	$ulGroup.not($('ul#' + title).show()).hide();
}

function changeSubnavClasses($clicked){
	$clicked.removeClass('inactive').siblings().addClass('inactive');
}

function strFirstUpper(str){
	return str[0].toUpperCase() + str.substr(1);
}

function fieldValueIsValid(field, type, markDefault, markInvalid) {
	if (field.val() != undefined) {
		var types = ['text', 'email', 'phone', 'site'];
		type = $.inArray(type, types) > -1 ? type : types[0];
		if(! markDefault){ markDefault = false;}
		var firstCondition, secondCondition;
		firstCondition = field.val().toLowerCase() != field.attr('title').toLowerCase();
		switch(type){
			case 'text':
				secondCondition = true;
				break;
			case 'email':
				secondCondition = emailIsValid(field.val());
				break;
			case 'phone':
				secondCondition = field.val() != '';
				break;
			case 'site':
				secondCondition = siteNameIsValid(field.val());
				break;
		}
		
		if((markDefault && !firstCondition) || (markInvalid && !secondCondition)){
			field.css({color: 'red'});
		} else { field.removeAttr('style');}
		
		return firstCondition && secondCondition;
	} else {
		return false;
	}

}

function emailIsValid(emailStr){
	var regex = /^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/;
	return regex.test(emailStr);
}

function siteNameIsValid(siteName){
	var regex = /^(https?:\/\/)?[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/;
	return regex.test(siteName);
}

function phoneNumberIsValid(phoneNumber){
	//--because i use mask of field number phone
	//var regex10digits = /^((\+\d)?\s?\(?\d{3}\)?\s?)?\d{3}[-\s]?\d{2}[-\s]?\d{2}$/
	//return regex10digits.test(phoneNumber);
	
	return (phoneNumber!="");
}

/***** Share42 social buttons *****/
function share42(f,u,t){if(!u)u=location.href;if(!t)t=document.title;u=encodeURIComponent(u);t=encodeURIComponent(t);document.write('<span id="share42">');var s=new Array('"#" onclick="window.open(\'http://www.facebook.com/sharer.php?u='+u+'&t='+t+'\', \'_blank\', \'scrollbars=0, resizable=1, menubar=0, left=200, top=200, width=550, height=440, toolbar=0, status=0\');return false" title="РџРѕРґРµР»РёС‚СЊСЃСЏ РІ Facebook"','"http://www.livejournal.com/update.bml?event='+u+'&subject='+t+'" title="РћРїСѓР±Р»РёРєРѕРІР°С‚СЊ РІ LiveJournal"','"http://connect.mail.ru/share?url='+u+'&title='+t+'" title="РџРѕРґРµР»РёС‚СЊСЃСЏ РІ РњРѕРµРј РњРёСЂРµ@Mail.Ru"','"#" onclick="window.open(\'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st._surl='+u+'&title='+t+'\', \'_blank\', \'scrollbars=0, resizable=1, menubar=0, left=200, top=200, width=550, height=440, toolbar=0, status=0\');return false" title="Р”РѕР±Р°РІРёС‚СЊ РІ РћРґРЅРѕРєР»Р°СЃСЃРЅРёРєРё"','"#" onclick="window.open(\'http://twitter.com/share?text='+t+'&url='+u+'\', \'_blank\', \'scrollbars=0, resizable=1, menubar=0, left=200, top=200, width=550, height=440, toolbar=0, status=0\');return false" title="Р”РѕР±Р°РІРёС‚СЊ РІ Twitter"','"#" onclick="window.open(\'http://vkontakte.ru/share.php?url='+u+'\', \'_blank\', \'scrollbars=0, resizable=1, menubar=0, left=200, top=200, width=554, height=421, toolbar=0, status=0\');return false" title="РџРѕРґРµР»РёС‚СЊСЃСЏ Р’ РљРѕРЅС‚Р°РєС‚Рµ"','"http://my.ya.ru/posts_add_link.xml?URL='+u+'&title='+t+'" title="РџРѕРґРµР»РёС‚СЊСЃСЏ РІ РЇ.СЂСѓ"');for(i=0;i<s.length;i++)document.write('<a rel="nofollow" style="display:inline-block;vertical-align:bottom;width:24px;height:24px;margin:0 6px 6px 0;outline:none;background:url('+f+'icons.png) -'+24*i+'px 0" href='+s[i]+' target="_blank"></a>');document.write('</span>');};
