function setCenter(item) {
    var windowHeight = document.body.clientHeight,
        currentOffset = document.documentElement.scrollTop || document.body.scrollTop;

    currentOffset = currentOffset + parseInt((windowHeight - $(item).outerHeight()) / 2);
    currentOffset = (currentOffset < 10) ? 10 : currentOffset;

    pLeft = parseInt($(item).outerWidth() / 2);
    $(item).css({
        'top':currentOffset,
        'marginLeft' :-pLeft
    }).show();
}

function showPopup(popup) {
    popup = $('#' + popup);

    setCenter(popup);
    createBlind(popup);

    popup.show();
    popup.find('.popup-close').click(function() {
        closePopup(popup);
        return false;
    });
}

function createBlind(popup) {
    blind = $('<div class="blind"></div>');

    blind.height($(document).height()).appendTo('body');
    blind.click(function() {
        closePopup(popup);
    });
}

function closePopup(popup) {
    $('div.blind').remove();
    popup.hide();
}

$(function() {
    $('.ts-call-recall').click(function() {
        showPopup('ts-call-popup');
        return false;
    });

    (function() {
        var requireds;

        function callValid() {

            requireds.each(function() {
                var value = $(this).val(),
                    phoneRX = /^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{6,10}$/;

                switch (this.name) {
                    case 'ts-call[name]':
                        !value ? $(this).addClass('non-valid') : $(this).removeClass('non-valid');
                        break;
                    case 'ts-call[phone]':
                        !phoneRX.test(value) ? $(this).addClass('non-valid') : $(this).removeClass('non-valid');
                        break;
                }
            });
        }

		var send = false;
        $('.ts-call-popup-form').submit(function() {
            requireds = $('.required', this);

            callValid();
            $('.iText', this).keyup(callValid);

            if ($('.non-valid', this).length) {
                $('.non-valid:first', this).focus();
            } else {
				if(send) return false;
				send = true;
				var data = $(this).find('input:text, textarea');
				data.removeClass('non-valid');
				$.post('/message_jx.php',data,
					function(msg) {
						if (msg.error) {
							alert('Ошибка при отправке сообщение.');
						} else {
							data.val('');
							alert('Сообщение успешно отправленно.');
						}
						send = false;
					},
				'json');
			}
			return false;
        });
    })();
});
