// JavaScript Document

function doneQuantity(){
	if($('#done').width() >= 1220){
		$('#done > li').css('width', '25%');
		$('#done > li:first-child').css('width', '24.9%');
		$('#done > li:last').css('display', '');
	}
	else{
		$('#done > li:last').css('display', 'none');
		$('#done > li').css('width', '');
	}
}

function roundCorners(jQSelector){
	// jQSelector - jquery selector of the container whose corners are to be rounded
	// wh - a dimensions array 
	var wh = [
		[325, 10],
		[245, 10],
		[212, 10],
		[188, 9],
		[168, 9],
		[154, 9],
		[140, 7],
		[130, 8],
		[120, 9],
		[110, 9],
		[100, 10],
		[90, 11],
		[80, 12],
		[70, 13],
		[60, 15],
		[50, 17],
		[40, 20],
		[30, 24],
		[20, 31],
		[10, 82]
	];
	
	var left = 0;
	var right = 0;
	var top = 0;
	var bottom = 0;
	
	var width = 0;
	var height = 0;
	
	var bgx = 0;
	var bgy = 0;
	
	for(var i = 0; i < wh.length * 4; i++){
		
		if(i % 2 == 0){
		    left = 0;
			right = 'auto';
			bgx = 0;
		}
		else{
			left = 'auto';
			right = 0;
			bgx = '100%';
		}
		
		if(i >= 0 && i < 40){
			
			if(i % 2 == 0){
				top = (i == 0) ? 0 : top + wh[i / 2 - 1][1];
				bgy = (i == 0) ? 0 : bgy - wh[i / 2 - 1][1];
				width = wh[i / 2][0];
				height = wh[i / 2][1];
			}
			
			bottom = 'auto';
		}
		else{
			if(i % 2 == 0){
				bottom = (i == 40) ? 0 : bottom + wh[i / 2 - 21][1];
				width = wh[i / 2 - 20][0];
				height = wh[i / 2 - 20][1];
				bgy = -650 + height + bottom;
			}
			
			top = 'auto';
		}
		
		var div = '<div style="z-index:100; position:absolute; ' +
				  'left:' + left + ';' +
				  'right:' + right + ';' +
				  'top:' + (top == 'auto' ? (top + ';') : (top + 'px;')) +
				  'bottom:' + (bottom == 'auto' ? (bottom + ';') : (bottom + 'px;')) +
				  'width:' + width + 'px;' +
				  'height:' + height + 'px;' +
				  'background:url(/images/map.png) no-repeat ' +
				  bgx + ' ' +
				  bgy + 'px;' +
				  '"></div>';
		
		$(jQSelector).append(div);
	}
}

// Switcher accordion
function subMenuSwitch(jQMenu, jQSlides, time){
	$(jQMenu + ' a').click(function(ev){
		ev.preventDefault();
		
		var i = $(jQMenu + ' a').index($(ev.target));
		
		$(ev.target).parent().siblings('.this').removeClass('this').end().addClass('this');
		
		$(jQSlides + ' > div').find('div.i2:visible').slideUp(time).end().children().eq(i + 1).slideDown(time);
	});
}


// Optimizing the space taken by elements with different height
function fullSpace(jQSelector){
	
	var leftHeight = 0;
	var rightHeight = 0;
	
	$(jQSelector).each(function(i){
		
		if(i == 0 || leftHeight <= rightHeight){
			$(this).css('float', 'left');
			leftHeight += $(this).outerHeight(true);
		}
		else{
			$(this).css('float', 'right');
			rightHeight += $(this).outerHeight(true);
		}
	})
}


// Валидация форм
function validate()
{
    var isValid = true;
    var $form = $(this);
    //var formName = $form.attr("name");    
    var fields = "input[name=f_wemail], input[name=f_cname], input[name=f_ccontact], input[name=f_wuser], textarea[name=f_Message]";
    $(fields, $form).each(function(){
        var $this = $(this);
        var $val = $this.val();
        if($val == '' || $val == 'Введите корректные данные')
        {
			$this.prev(".placeholder").html("");
            $this.val("Введите корректные данные");
			$this.addClass("notice");
            isValid = false;
        }
        else if($this.attr("name") == "f_wemail" && !$val.match("^[a-z0-9\._-]+@[a-z0-9\._-]+\.[a-z]{2,4}$"))
        {
            $this.addClass("notice");
            isValid = false;
        }
		else if( $this.attr("name") == "f_cname" )
        {
			if ( $val == '' || $val == 'Вы всё же представьтесь' || $val == 'Иванов Иванов' )
			{
			$this.val("Вы всё же представьтесь");
			$this.addClass("notice");
            isValid = false;
			}
        }
		else if( $this.attr("name") == "f_ccontact" )
        {
			if ( $val == '' || $val == 'Как как с вами связаться?' || $val == 'Телефон, e-mail, телепатический канал.' )
			{
			$this.val("Как как с вами связаться?");
			$this.addClass("notice");
            isValid = false;
			}
        }
        else
        {
			$this.removeClass("notice");
			return true;
        }
    });
	
	if(isValid)
    {
		var inputEmail = $("#RealEmail").val();
		$("#hiddenEmail").val(inputEmail);
		
		var inputEmailComment = $("#RealEmailComment").val();
		$("#hiddenEmailComment").val(inputEmailComment);
		 
		var formName = $form.attr("class");
		if ( formName == 'f_3 ajax_form')
		{
			var url = $form.attr("action");
			var data = $("input, textarea", $form).serialize();
			$.post(url, data).success(function(data){
				$(".field-set", $form).html("<label>За вами уже выехали (:<br/>Никуда не убегайте!</label><br/>");
			});
			
			return false;
		}
		return true;
    }
    return false;
}


jQuery(document).ready(function(){

	// Done projects
	$(window).resize(function(){
		doneQuantity();
		if ($('.floating').length || $('.onbottom').length) { floatingSize(); }
	});
	doneQuantity();
	
	// Styling ordered list
	$('ol').children('li').each(function(i){
		var span_margin = $(this).css('padding-left');
		
		$(this).prepend('<span style="float:left; margin:0 0 0 -' + span_margin + '">' + (i + 1) +'.</span>');
	});
	
	
//	// IKRA contacts (in header)
//	$('p.phone big').mouseover(function(){
//		$(this).html('961-4572').css('margin-right', '5px');
//	}).mouseout(function(){
//		$(this).html('961-IKRA').css('margin-right', '0');
//	})
	
	
	// A joke with "tync"
	//$('#header a.tync').attr('title', 'Тынцай давай!');
	
		
	// Form placeholders
	$('form .placeholder').click(function(e){
		$(e.target).next().focus();
	})
	
	
	// Round map corners
	roundCorners('div.map > div:first-child');
	
	
	// Submenu switcher (accordion) on index page
	subMenuSwitch('#sw_1', '#sw_1_b', 500);
	
	
	// Optimizing the space taken by elements with different height
	fullSpace('div.portfolio_2');
	
	
	//Привязка валидации форм
    $("form[class~=ajax_form]").submit(validate);
    $("form input, form textarea").focus(function(){
	
		$(this).removeClass("notice");
		
        if( $(this).val() == "Введите корректные данные" || $(this).val() == "Вы всё же представьтесь" || $(this).val() == "Как как с вами связаться?")
        {
            $(this).val("");
        }
		
		
    });
	
	// Форма на титульной странице
	$("#inputName").attr("value", "Иванов Иванов"); var text1 = "Иванов Иванов";
	$("#inputContact").attr("value", "Телефон, e-mail, телепатический канал."); var text2 = "Телефон, e-mail, телепатический канал.";
	$("#inputName").focus(function() { $(this).addClass("normalText"); if($(this).attr("value") == text1) $(this).attr("value", ""); });
	$("#inputContact").focus(function() { $(this).addClass("normalText"); if($(this).attr("value") == text2) $(this).attr("value", ""); });
	$("#inputName").blur(function() { if($(this).attr("value") == "") { $(this).attr("value", text1); $(this).removeClass("normalText"); }});
	$("#inputContact").blur(function() { if($(this).attr("value") == "") {$(this).attr("value", text2); $(this).removeClass("normalText"); }});
	
	// Фиксированный блок
	$(window).scroll(function () {
		var pageScroll = $(document).scrollTop();
		var docHeight = $(document).height();
		var rightColHeight = $(".rightcol").height();
		var leftColHeight = $(".leftcol").height();
		var difference = docHeight - rightColHeight - 300;
		
		if ( $(window).height() > rightColHeight && $('#float').length && leftColHeight > rightColHeight )
		{
			if ( pageScroll > 226 && pageScroll < difference ) { $(".rightcol").removeClass('onbottom').addClass('floating'); floatingSize(); }
			else if ( pageScroll > difference ) { $(".rightcol").removeClass('floating').addClass('onbottom'); floatingSize(); }
			else { $(".rightcol").removeClass('floating onbottom'); $(".rightcol").css({marginLeft: 0, width: '33%'}); }
		}
	});
	
	// Корректировка размеров фиксированного блока
	function floatingSize()
	{
		var containerWidth = $(".container").width();
		var leftcolWidth = $(".leftcol").width() + 3;
		var rightcolWidnt = containerWidth - leftcolWidth;
		$(".rightcol").css({marginLeft: leftcolWidth+'px', width: rightcolWidnt+'px'});
	}
		
})

