﻿/*Скрипт, реализующий логику обработки анкеты клиента. 
Мелехин Тимофей
20 июня 2011 г.
*/

function InitFeedBackForm() {

    $("#questions").empty();

    Questions = [{
        QuestionID: 13,
        Question: "1. Оцените, пожалуйста, насколько удобна в использовании программа ЭДО в Кабинете Клиента? (от 1 до 10, где 1- совсем не удовлетворен, 10 полностью удовлетворен)",
        Type: "Grade"
    },
                    { QuestionID: 14,
                        Question: "2. Какие дополнительные услуги Вам хотелось бы видеть в программе ЭДО?",
                        Type: "Text"
                    },
                    { QuestionID: 15,
                        Question: "3. Какие услуги были бы Вам полезны в Кабинете Клиента на сайте Компании?",
                        Type: "Text"
                    }];

    $.each(Questions, function (index, value) {

        var q = $("#question").clone();
        q.attr('id', 'question_' + value.QuestionID);
        var Question = q.children(".question_text");
        Question.html(value.Question);
        var control = AddIndexToID(q, value.QuestionID, "control");
        AddIndexToID(q, value.QuestionID, "value");
        var Comment = AddIndexToID(q, value.QuestionID, "comment");
        var link = AddIndexToID(q, value.QuestionID, "link");

        if (value.Type == "Title") {
            link.hide();
            control.hide();
            Comment.hide();
        }
        if (value.Type == "Text") {
            link.hide();
            control.hide();
            Comment.show();
        }
        else if (value.Type == "filials") {
            $("#filials").show();
            $("#filials").appendTo(Question);

            link.hide();
            control.hide();
            Comment.hide();
        }
        else {

            Comment.hide();

            link.click(function () {

                var QuestionIndex = GetID_Index($(this));
                var com = $("#comment_" + QuestionIndex);
                var display = com.css("display");
                var link = $("#link_" + QuestionIndex)[0];

                if (display == "none") {
                    com.show();
                    link.innerText = "Удалить комментарий";
                } else {
                    com.hide();
                    com.val("");
                    link.innerText = "Оставить комментарий";
                }
            });

            control.selectable({
                selected: function (event, ui) {
                    var QuestionIndex = GetID_Index($(this));
                    var result = $("#value_" + QuestionIndex);
                    result.val(ui.selected.innerText);
                },
                stop: function (e, ui) {

                    /*Обработчик, который откидывает множественный выбор значений через CTRL*/
                    $(".ui-selected:first", this).each(function () {
                        $(this).siblings().removeClass("ui-selected");
                        var refreshVal = $(this).attr("value");
                    });
                }
            });


            if (value.Type == "GradeHead") { link.hide(); }

            if (value.Type == "GradeMiddle") {
                link.hide();
                Question.css("margin-left", "30px");
            }
            if (value.Type == "GradeEnd") {
                Question.css("margin-left", "30px");
            }

            control.css("margin-left", "25px");
        }

        q.show();
        q.appendTo($('#questions'));
    });

    $("#question").hide();


    ShowFeedBackPupUp();
}

function InitFeedBackFormExt() {
    /*checking of cookies work*/
    //debugger;

    $.cookie("CheckingSomeValue", 1, { expires: 1, path: "/" });

    if ($.cookie("CheckingSomeValue") == 1) {
        InitFeedBackForm();
    }
}
function AddIndexToID(element, index, id) {
    var e = element.find("#" + id);
    e.attr("id", id + "_" + index);
    return element.find("#" + id + "_" + index);
}
function ShowFeedBackPupUp() {

//    if ($('#banner_scroller_container').length > 0) { /*Скрываем Flash Banner*/
//        $('#banner_scroller_container').hide();
//    }

    background.asBackground();
    background.show();

    popup.show();
    popup.center();
}
function GetID_Index(e) { return e.attr("id").split('_')[1]; }

function SaveAndClose(showLater) {
    ///Собираем ответы
    var Questions = new Array();
    
    $('div[id*="question_"]').each(function (index) {

        var QuestionIndex = GetID_Index($(this));
        var grade = $("#value_" + QuestionIndex).val();
        var CommentText = $("textarea[id='comment_" + QuestionIndex + "']").val();

        //        if (QuestionIndex == 7) /*пока оставляем жестко, потом переделаю...*/
        //        {
        //            CommentText = $("#filials option:selected").html();
        //        }

        if (isNaN(parseInt(grade))) grade = 0;

        var QuestionResult = {
            QuestionID: QuestionIndex,
            Grade: grade,
            Comment: CommentText
        };

        Questions[Questions.length] = QuestionResult;

    });

    var QuestionsJson = Sys.Serialization.JavaScriptSerializer.serialize(Questions);

    $.ajax(
    {
        type: "POST",
        url: "/PopUpFeedback/FeedBack.asmx/SaveFeedBack",
        data: "{ 'answers':'" + QuestionsJson + "', 'showLater':'" + showLater + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: SaveSuccess,
        error: SaveError

    });
    function SaveSuccess(data, status) {
        if (showLater == true)
            Close();
        else
            Cancel();
    }
    function SaveError(xmlRequest) {
        alert(xmlRequest.status + ' \n\r ' +
              xmlRequest.statusText + '\n\r' +
              xmlRequest.responseText);
    }
}
function Cancel() {
    /*Анкета блокируется для данного ПК*/
    $.cookie("FeedbackExt", 1, { expires: 365, path: "/" });
    End();
}

function Close() {
    /*Анкета появится через день*/
    $.cookie("FeedbackExt", 1, { expires: 1, path: "/" });
    End();
}
function End() {
    background.hide();
    popup.hide();
//    if ($('#banner_scroller_container').length > 0) { /*Скрываем Flash Banner*/
//        $('#banner_scroller_container').show();
//    }
}

function CheckForShowFromCookie() {
    if ($.cookie("FeedbackExt") != 1)
        InitFeedBackFormExt();
}
