$(function() {
	
    //Отображение портфолио сайтов
    if($(location).attr('pathname') == '/works/sites.html')
    {
        $('#prev').hide();
    	var sites_num = $("#sites").attr("num");
    	var actions_count = 0;
    	
    	$("#next").click(function(){
    		var window_width = get_width();
    		var offset = $('#sites').offset();
    		percent_offset = Math.round((offset.left/window_width)*100)*-1 + 60;
    		
    		var offset1 = "-"+(percent_offset+3)+"%";
    		var offset2 = "-"+(percent_offset-2)+"%";
    		var offset3 = "-"+(percent_offset+1)+"%";
    		var offset4 = "-"+percent_offset+"%";
    
    		$("#sites").animate({left: offset1}, 1300);
    		$("#sites").animate({left: offset2}, 300);
    		$("#sites").animate({left: offset3}, 200);
    		$("#sites").animate({left: offset4}, 100);
    		
    		actions_count++;
    		
    		if($('#prev').css('display') == "none") $('#prev').fadeIn(1800);
    		if(actions_count == (sites_num-1)) $('#next').fadeOut(1800);
    	});
    	
    	$("#prev").click(function(){
    		var window_width = get_width();
    		var offset = $('#sites').offset();
    		percent_offset = Math.round((offset.left/window_width)*100) + 60;
    
    		var offset1 = (percent_offset+3)+"%";
    		var offset2 = (percent_offset-2)+"%";
    		var offset3 = (percent_offset+1)+"%";
    		var offset4 = percent_offset+"%";
    
    		$("#sites").animate({left: offset1}, 1300);
    		$("#sites").animate({left: offset2}, 300);
    		$("#sites").animate({left: offset3}, 200);
    		$("#sites").animate({left: offset4}, 100);
    		
    		actions_count--;
    		
    		if(actions_count == 0) $('#prev').fadeOut(1800);
    		if($('#next').css('display') == "none") $('#next').fadeIn(1800);
    	});
    }
    
    //Управление блоками и псевдо-ссылками
    //Используется только для "полиграфия" и "создание сайтов"
	if($(location).attr('pathname') == '/works/polygraphy.html' || $(location).attr('pathname') == '/services/sites.html')
    {
        //На первую ссылку ставим класс активный и отображаем первый блок
        $(".pseudo_link:first").toggleClass('pseudo_link').toggleClass('active');
        $(".real_div:first").fadeIn("slow");
        
        //По клику на ссылку:
        $(".pseudo_link").live("click", function(){
           $("#content .active").toggleClass('active').toggleClass('pseudo_link'); //для активной ссылки ставится обычный класс,
           $(this).toggleClass('pseudo_link').toggleClass('active'); //а на нажатую ссылку ставится активный
           
           $(".real_div:visible").hide();
           var show_id = $(this).attr("rel");
           $("#"+show_id).fadeIn("slow");
           
           if(show_id == "5") $("body").toggleClass("funky");
           else $("body").removeClass("funky");
        });
    }
    
    // Отображение формы
        
    $("#modal_form_button").live("click", function(){
        $("#modal_form_bg").fadeIn("slow");
        $("#modal_form").fadeIn("slow");
        
        //Скрываем по клику все формы
        $("#modal_form_bg").click(function(){
            $("#modal_form").fadeOut("slow");
            $("#modal_form_bg").fadeOut("slow");
        });
        
        //Скрываем по Escape
        $(document).keyup(function(e) {
          if (e.keyCode == 27) {
            $("#modal_form").fadeOut("slow");
            $("#modal_form_bg").fadeOut("slow");
            }
        });
    });
    
    // Валидация формы
    // Айдишники всех обязательных полей
	var required = ["name", "phone"];

	var email = $("#email");

    var errornotice = $("#errornotice");
	// The text to show up within a field when it is incorrect
	var emptyerror = "Это поле обязательно.";
	var emailerror = "Неверный e-mail.";

	$("#theform").submit(function(){	
		//Валидация полей
		for (i=0;i<required.length;i++) {
			var input = $('#'+required[i]);
			if ((input.val() == "") || (input.val() == emptyerror)) {
				input.addClass("needsfilled");
				input.val(emptyerror);
				errornotice.fadeIn(750);
			} else {
				input.removeClass("needsfilled");
			}
		}
		//Валидация e-mail.
		if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
			email.addClass("needsfilled");
			email.val(emailerror);
		}

		//если какое-то из полей формы имеет класс 'needsfilled', то форма не сабмитиццо
		if ($(":input").hasClass("needsfilled")) {
			return false;
		} else {

			errornotice.hide();

			var post_name = $("#name").val();
			var post_email = $("#email").val();
			var post_phone = $("#phone").val();
			var post_message = $("#message").val();
			

			$.ajax({
			   type: "POST",
			   url: "http://www.divogroup.com/15/",
			   data: "script=goscript&name="+post_name+"&email="+post_email+"&phone="+post_phone+"&message="+post_message,
			   success: function(data) {
			   		$("#modal_form").animate({height: "150px"}, 800);
				    $(".container").html(data);
                    $("#modal_form_bg").delay(2000).fadeOut(2000);
				    $("#modal_form").delay(1000).fadeOut(2000);
				  }
			 });
			 
			 return false;
		}
	});
	
	//Стираем поля на фокусе
	$(":input").focus(function(){		
	   if ($(this).hasClass("needsfilled") ) {
			$(this).val("");
			$(this).removeClass("needsfilled");
	   }
	});
});

function get_width()
{
	if (document.body && document.body.offsetWidth) {
		return document.body.offsetWidth;
	}
	if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
		return document.documentElement.offsetWidth;
	}
	if (window.innerWidth && window.innerHeight) {
		return winW = window.innerWidth;
	}
}



