﻿$(document).ready(function() {
// Tabs on contacts
$('.maps').hide(); // Hide all divs
$('div.maps:first').show(); // Show the first div
$('.maps_link:first').addClass('active'); // Set the class of the first link to active
$('.maps_link').click(function(){ //When any link is clicked
$('.maps_link').removeClass('active'); // Remove active class from all links
$(this).addClass('active'); //Set clicked link class to active
var currentTab = $(this).attr('rel'); // Set variable currentTab to value of href attribute of clicked link
$('.maps').hide(); // Hide all divs
//$('.tabs').animate({ height: 'toggle', opacity: 1.0},  300, 'linear');
//$(currentTab).show(200); // Show div with id equal to variable currentTab
$(currentTab).show();
showMap();
return false;
});
// Tabs on main
$('.tabs').hide(); // Hide all divs
$('div.tabs:first').show(); // Show the first div
$('#submenu li:first').addClass('active'); // Set the class of the first link to active
$('#submenu li a').click(function(){ //When any link is clicked
$('#submenu li').removeClass('active'); // Remove active class from all links
$(this).parent().addClass('active'); //Set clicked link class to active
var currentTab = $(this).attr('href'); // Set variable currentTab to value of href attribute of clicked link
$('.tabs').hide(); // Hide all divs
//$('.tabs').animate({ height: 'toggle', opacity: 1.0},  300, 'linear');
//$(currentTab).show(200); // Show div with id equal to variable currentTab
$(currentTab).animate({ height: 'toggle'
											//,opacity: 1.0
											},  300, 'linear'); 
return false;
});
// Menu
/*$('#main_menu  li a').hover(
      function () {
        var mw = $(this).width();
		
		if ($(this).attr('class')=='active'){return false};
		$(this).parent().append('<div class="insert_box2"><div class="topLeft"></div><div class="topRight"></div><div class="content"></div><div class="bottomLeft"></div><div class="bottomRight"></div></div>');
		$(this).parent().find('.insert_box2').width(mw+20);
      },
      function () {
        $(this).parent().find('.insert_box2').remove();
      }
    );*/
// Active item main menu 
 var amw = $('#main_menu li a.active').width();
 $('#main_menu li a.active').parent().append('<div class="insert_box2"><div class="topLeft"></div><div class="topRight"></div><div class="content"></div><div class="bottomLeft"></div><div class="bottomRight"></div></div>');
 $('#main_menu li .insert_box2').width(amw+30);
// Active item works menu 
/* var amw2 = $('.works_menu_content li a.active').width();
 $('.works_menu_content li a.active').parent().append('<div class="insert_box3"><div class="topLeft"></div><div class="topRight"></div><div class="content"></div><div class="bottomLeft"></div><div class="bottomRight"></div></div>');
 $('.works_menu_content li .insert_box3').width(amw2+26);*/
// Special offer
var SO = $('#special_offer');
var SOB = $('#so');
SOB.mouseover(function() {
SOB.addClass('sob_act');
  SO.show();
  
  SO.mouseleave(function() {
  SOB.removeClass('sob_act');
  SO.hide();
  
});
});
// Portfolio on the main
 var MapArea = $('#p_link');
 var FirstHref = $('#works_list li:eq(0) a:eq(0)').attr('href');
 MapArea.attr('href', FirstHref);
 $("#works_list").jCarouselLite({btnNext: "#next", btnPrev: "#prev", visible: 1,
 afterEnd: function(a) {
		var plink=a.find('a').attr('href');
		MapArea.attr('href', plink);
    }
 });

// Portfolio on the inner
$('#works_block .r').each(function(index) {
	var SH = $(this).find('.screenshot').height();		
  $(this).append('<div class="shadow"><div class="topLeft"></div><div class="topRight"></div><div class="topMid"></div><div class="shadow_for"><div class="shadow_for2" style="width:100%; height:420px;"></div></div><div class="bottomLeft"></div><div class="bottomRight"></div><div class="bottomMid"></div></div>');
	$(this).find('.shadow_for2').height(SH-12);
  });

$(".screenshot").hover(
  function () {
		var SH = $(this).height();
		$(this).parent().parent().append('<div class="backlight"></div>');
		$(this).parent().parent().find('.backlight').height(SH+10);
		$(this).removeClass().addClass("screenshot_backlight");
		$(this).parent().parent().find('h2 a').removeClass().addClass("screenshot_text_red_link");
  },
  function () {
		$(this).parent().parent().find('.backlight').remove();
    $(this).removeClass().addClass("screenshot");
		$(this).parent().parent().find('h2 a').removeClass().addClass("screenshot_text_link");
  }
);
$('.bs').each(function(index) {
	var BSH = $(this).height();		
  $(this).parent().parent().append('<div class="shadow"><div class="topLeft"></div><div class="topRight"></div><div class="topMid"></div><div class="shadow_for"><div class="shadow_for2" style="width:100%; height:420px;"></div></div><div class="bottomLeft"></div><div class="bottomRight"></div><div class="bottomMid"></div></div>');
	$(this).parent().parent().find('.shadow_for2').height(BSH-12);
  });
// Authentication window
function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		
$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#curtain').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				
			});

var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#curtain').css({
				//backgroundColor:	"#000",
				//opacity:			0.9,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn(1000);

$(".order_popup").click(function ()
{
	$.get("/order.popup.html", function (data)
	{
		$('body').append(data);

		var arrPageSizes = ___getPageSize();

		// Занавес
		$('#curtain').css(
		{
			backgroundColor:	"#000",
			opacity:			0.2,
			width:				arrPageSizes[0],
			height:				arrPageSizes[1]
		});
		$('#curtain, #close_form').click(function()
		{
			_finish();
		});

		// Валидация формы заказа, параметры
		$('#order-form').validForm({errorContainer: '#order-form-text'});

		// Ставим изображение капчи
		var captchaSrc = "/order.ajax.php?action=captcha_get";
		$("#captcha_block img").attr('src', captchaSrc);

		// Заставляем капчу обновлятся при нажатии
		$("#captcha_block img").click(function ()
		{
			$(this).attr('src', captchaSrc+'&'+new Date().getTime());
		});

	});

	return false;
});

function _finish() {
			$('#order-form-box').remove();
			$('#curtain').fadeOut(function() { $('#curtain').remove(); });
		}
function form_message() {
			//$('#order-form').remove();
			//$('#curtain').fadeOut(function() { $('#curtain').remove(); });
		}

});

// Валидация форм
jQuery.fn.validForm = function(userOptions) {

    var options = {
    	errorContainer: "#errorList",
    	errorContainerCssClass: {
    		'text-color': "#F00"
    	}
    }

    $.extend(options, userOptions);
  

    //$('head').append("<style>#wrapper div.consult input.inputError, #wrapper div.consult textarea.inputError {border: 2px solid #F00; background: #FAA;}</style>");

    $(this).each( function() {
    	var id = "#" + $(this).attr('id');
        if ($(id + " input").length > 0) {
            Validate(id);
        } else {
        	return false;
        }
    });

	function isValidEmailAddress(emailAddress)
	{
		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pattern.test(emailAddress);
	}

	function Validate(form)
	{
		$(form + " #order-form-button").click(function()
		{
			var errorAmount = 0;

			var collection = $(form + " input")
				.add(form +" textarea");

			collection.each(function()
			{
				var element = $(this);
				len = $.trim($(this).val());

				if (element.attr('id') == "order_email")
				{
					var email = $(this).val();
					if(!isValidEmailAddress(email))
					{
						len = 0;
						element.addClass('inputError');
						errorAmount++;
					}
				};

				if (!len)
				{
					element.addClass('inputError');
					errorAmount++;
				}
				else
				{
					element.removeClass('inputError');
				}
			});

			collection.keypress (function ()
			{
				$(this).removeClass('inputError');
			});

			collection.change (function()
			{
				if (($(this).attr('value')).length < 1)
				{
					$(this).addClass('inputError');
				}
				else
				{
					$(this).removeClass('inputError');
				}
			});

			if (errorAmount>1)
			{
				$(options.errorContainer).html('Заполните пожалуйста правильно выделенные поля');
				$(options.errorContainer).show();
				return false;
			}
			else
			{
				$('body').append('<div id="preloader" style="position: absolute; top:53%; left:48%; z-index:10000;"><img src="/images/preloader.gif" border=0 /></div>');
				
				$(form + " #order-form-button").css("display", "none");
				collection.each(function()
				{
					 $(this).attr("readonly", "readonly");
				});
				
				
				$.getJSON
				(
					'/order.ajax.php',
					{
						"action"	: "send",
						"captcha"	:  $.trim($("#order_captcha").val()),
						"data"		:
						{
							"name"		: $("#order_name").val(),
							"phone"		: $("#order_phone").val(),
							"company"	: $("#order_company").val(),
							"email"		: $("#order_email").val(),
							"about"		: $("#order_about").val()
						}
					},
					function (data)
					{
						if (data.status == "error")
						{
							if (data.code == 2)
							{
								$("#order_captcha").addClass('inputError');
							}

							console.log(data.message);
							return;
						}

						$.get("/order.complete.html", function (data2)
						{
							$(options.errorContainer).empty().prepend(data2);
							$("#order_complete_who").text(data.who);
							$("#order_complete_id").text(data.id);
							$("#order-form").remove();
							$("#preloader").remove();
							$(".form_heading").text("Ответная форма сообщения");
						});
					}
				);
			}
		});
	}
}

