/**
 * Класс всплывающих форм
 * @param jLink Объект псевдоссылки, управляющей отображением формы
 * @param jForm Объект формы, должен быть построен по определённым законам — содержать в себе блоки с классами form-container, answer-container и tail
 * @param sTailPositionY Расположение хвоста вверху или внизу формы. Может принимать значения: top и bottom
 * @param sTailPositionY Расположение хвоста формы справа или слева от «переключателя». Может принимать значения: left и right
 * @param jFormAlign Центрирование формы. Может принимать значения: centered, lefted
 */

//TODO: Репозиционировать открытую форму при ресайзе окна
//TODO: Что-то делать, когда форме не хватает места по высоте


function ClassFormPopup(jLink, jForm, sTailPositionY, sTailPositionX, jFormAlign)
{
    var oThis = this;
    this.jLink = jLink;
    this.jPopup = jForm;
    this.sTailPositionY = sTailPositionY;
    this.sTailPositionX = sTailPositionX;
    this.jFormAlign = jFormAlign;
    this.jTail = $(".tail", jForm); // Контейнер хвоста формы
    this.jContainer = $(".container", jForm);  // Контейнер формы
    this.jAccessory = $(".form-container", jForm);  // Контейнер формы
    this.jAnswerContainer = $(".answer-container", jForm); // Контейнер ответа, появляющегося после отправки формы
    this.jSubmit = $(".submit", jForm); // Кнопка отправки
    this.jOneMoreTime = $(".one-more-time", jForm); // Ссылка для повторного заполнения формы

    $("form", this.jPopup).submit(function() {
        oThis.showAnswer();
        return false;
    });

    oThis.jPopup.css('left', ($(".root").width() - oThis.jPopup.width()) / 2 + 'px');

    this.showForm = function()
    {
        oThis.jTail.fadeIn(50);
        oThis.jContainer.css('height', '1px');
        oThis.jPopup
            .css('display', 'block')
            .addClass("z-index-top");
        $(".z-index-top").not(oThis.jPopup).removeClass("z-index-top");
        oThis.jAnswerContainer.hide();
        oThis.jAccessory.show();
        var iMinWidth = $('.root').width() / 2;
		var iRealWidth = $('table.form-table', oThis.jAccessory).width();
        var iNewWidth = iMinWidth > iRealWidth ? iMinWidth : iRealWidth;
        if (oThis.sTailPositionY == 'top')
        {
            oThis.jPopup.css('top', ($(".switch", oThis.jLink).offset().top + oThis.jTail.height() - 15) + 'px'); // Высота хвоста больше его видимой части из-за тени
        }
        else if (oThis.sTailPositionY == 'bottom')
        {
            oThis.jPopup.css('bottom', ($(".root").height() - $(".switch", oThis.jLink).offset().top + oThis.jTail.height() - 39 ) + 'px');
        }
        else if (oThis.sTailPositionY == 'middle')
        {
            oThis.jPopup.css('top', ($(".switch", oThis.jLink).offset().top) - (oThis.jAccessory.height() / 1.5) + 'px');
        }
        if (oThis.jFormAlign == 'centered')
        {
            oThis.jPopup.css({left: ($(".root").width() - iNewWidth) / 2 + 'px'});
        }
        else
        {
            oThis.jPopup.css({left: ($(".root").width()*0.04) + 60 + 'px'});
        }
        if (oThis.sTailPositionX == 'left' && oThis.jFormAlign == 'centered')
        {
            oThis.jTail.css('right', ($(".root").width() + iNewWidth) / 2 - oThis.jLink.offset().left - 22 + 'px');
        }
        else
        {
            oThis.jTail.css('bottom', (oThis.jAccessory.height() / 3) - 25 + 'px');
        }
        //        console.log($(iNewWidth));
        $('table.form-table', oThis.jAccessory).css("width", iNewWidth + 'px');
        oThis.jContainer.animate({height: oThis.jAccessory.height() + 'px', width: iNewWidth + 'px'}, 100, function() {
            scrollTo();
        });
        oThis.jLink.unbind('click', oThis.showForm);
        //        oThis.jLink.click(oThis.hideAll);
        $('.switch', oThis.jLink).addClass('switch-black');
        //        console.log('open');
        function scrollTo() {
            if (($(window).scrollTop() - oThis.jPopup.position().top) > -20) {
                $.scrollTo(oThis.jPopup, {offset: -20, duration: 300});
            }
        }
        return false;
    }

    this.showAnswer = function ()
    {
        oThis.jAnswerContainer.show();
        var iMinWidth = $('.root').width() / 2;
		var iRealWidth = $('table', oThis.jAnswerContainer).width() + 100;
        var iNewWidth = iMinWidth > iRealWidth ? iMinWidth : iRealWidth;
        var iNewHeight = oThis.jAnswerContainer.height();
        oThis.jAccessory.hide();
        //console.log(this.jAnswerContainer.height());
        oThis.jContainer.animate({height: oThis.jAnswerContainer.height() + 'px'/*, width: iNewWidth + 'px'*/}, 100);
        if (oThis.jFormAlign == 'centered')
        {
            /*oThis.jPopup.animate({left: ($(".root").width() - iNewWidth) / 2 + 'px'}, 100, function() {
                scrollTo();
            });
            oThis.jTail.css({right: ($(".root").width() + iNewWidth) / 2 - oThis.jLink.offset().left - 22 + 'px'});*/
            scrollTo();
        }
        else
        {

            oThis.jPopup.animate({top: ($(".switch", oThis.jLink).offset().top) - (iNewHeight / 1.5) + 'px'}, 100, function() {
                scrollTo();
            });
            oThis.jTail.css({bottom: (iNewHeight / 3) - 25 + 'px'});
        }
        function scrollTo() {
            if (($(window).scrollTop() - oThis.jPopup.position().top) > -60) {
                $.scrollTo(oThis.jPopup, {offset: -60, duration: 300});
            }
        }
        return false;
    }

    this.hideAll = function ()
    {
        oThis.jAnswerContainer.hide();
        var iNewWidth = 0;
        oThis.jAccessory.hide();
        //console.log(this.jAnswerContainer.height());
        oThis.jContainer.animate({height: 0 + 'px', width: iNewWidth + 'px'}, 100);
        oThis.jPopup.animate({left: 0 + 'px'}, 10, function () {
            oThis.jPopup.css('display', 'none');
        });
        oThis.jTail.fadeOut(50);
        oThis.jLink.unbind('click', oThis.hideAll);
        oThis.jLink.click(oThis.showForm);
        $('.switch', oThis.jLink).removeClass('switch-black');
    //          console.log('close');
    }

    this.jOneMoreTime.click(oThis.showForm);
    this.jLink.click(oThis.showForm);
    $(document).click(oThis.hideAll);
    $('.close', this.jPopup).click(oThis.hideAll);
    this.jPopup.click(function(event) {
        event.stopPropagation();
    });
    this.jSubmit.click(function() {
        $('form', oThis.jPopup).submit();
    });

    // Календарь формы
    $(".forms-calendar span", oThis.jAccessory).bind('click',
            function(event)
            {
                $(".forms-calendar span", oThis.jAccessory).removeClass('active');
                $('.date-picker', oThis.jAccessory).val($(this).text() + '.08');
                $(this).addClass('active');
                return false;
            });

    //oThis.showForm();

}
