
    $(document).ready(function() {
       $('div.guide input.guide-survey-submit').live('click', Guide.answerSurvey);
       $('.record-custom-answer-trigger').live('click', Guide.recordCustomAnswer);
    });
    
    var _negativeMargin = 60;
    
    var Guide = {
        msgs: false,
        strings: false,
        msgCount: 0,
        survey_id: -1,
        pastSurveyResults: [],
        surveyResults: [],
        setMsgs: function(msgsJSON) {
            Guide.msgs = msgsJSON.msgs;
            Guide.msgCount = msgsJSON.count;
        },
        move: function(e) {
            $('div.concordance-guide').css('margin-top', ($(e.target).offset().top - $('div#header').height() - _negativeMargin));
            Guide.trigger(e);
        },
        trigger: function(e) {
        	switch($(e.target).attr('id')) {
                // reminder service by SMS - ask for Number
                case 'no_number':
                    Guide.setBubbleHTML('<p><strong>' + (Guide.msgs[30]['label'] ? Guide.msgs[30]['label'] : Guide.msgs[30]['name']) + '</strong></p>');
                    break;
                case 'register-aed-1':
                case 'register-aed-8':
                    if ($('input#register-aed-1').attr('checked') || $('input#register-aed-8').attr('checked')) {
                        Guide.setBubbleHTML('<p><strong>' + (Guide.msgs[1]['label'] ? Guide.msgs[1]['label'] : Guide.msgs[1]['name']) + '</strong></p>');
                    } else {
                        Guide.hide();
                    }
                    break;
                case 'edit-profile-aed-1':
                case 'edit-profile-aed-8':
                    if ($('input#edit-profile-aed-1').attr('checked') || $('input#edit-profile-aed-8').attr('checked')) {
                        Guide.setBubbleHTML('<p><strong>' + (Guide.msgs[36]['label'] ? Guide.msgs[36]['label'] : Guide.msgs[36]['name']) + '</strong></p>');
                    } else {
                        Guide.hide();
                    }
                    break;
                case 'register-address-street':
                case 'register-address-location':
                case 'register-address-postal':
                case 'register-address-state':
                    Guide.setBubbleHTML('<p><strong>' + (Guide.msgs[2]['label'] ? Guide.msgs[2]['label'] : Guide.msgs[2]['name']) + '</strong></p>');
                    break;
                case 'edit-profile-address-street':
                case 'edit-profile-address-location':
                case 'edit-profile-address-postal':
                case 'edit-profile-address-state':
                    Guide.setBubbleHTML('<p><strong>' + (Guide.msgs[43]['label'] ? Guide.msgs[43]['label'] : Guide.msgs[43]['name']) + '</strong></p>');
                    break;
                case 'register-phone':
                case 'register-mobile':
                    Guide.setBubbleHTML('<p><strong>' + (Guide.msgs[39]['label'] ? Guide.msgs[39]['label'] : Guide.msgs[39]['name']) + '</strong></p>');
                    break;
                case 'edit-profile-phone':
                case 'edit-profile-mobile':
                    Guide.setBubbleHTML('<p><strong>' + (Guide.msgs[40]['label'] ? Guide.msgs[40]['label'] : Guide.msgs[40]['name']) + '</strong></p>');
                    break;
                default:
            }
        },
        prepareHTML: function() {
            var displayMsg = false;
            // if guide has msg
            if (Guide.msgs) {
                // if guide has exactly one msg
                if (Guide.msgCount == 1) {
                    // get first msg (pretty uncool)
                    $.each(Guide.msgs, function(i, n) {
                        // usually display msg, but in some cases msgs should appear first time when triggered by js-action later
                        switch(n['id']) {
                            case '30':
                                break;
                            default:
                                displayMsg = n;
                        }
                    });
                }
            }
            if (displayMsg) {
                // if msg is no survey, just display
                if (!displayMsg['survey']) {
                    Guide.setBubbleHTML('<p><strong>' + (displayMsg['label'] ? displayMsg['label'] : displayMsg['name']) + '</strong></p>');
                } else {
                    //console.info(displayMsg);
                    // init survey action
                    Guide.survey_id = displayMsg['survey']['id'];
                    Guide.initSurvey(displayMsg['survey']['html']);
                }
                Guide.show();
            } else {
                Guide.hide();
            }
        },
        initSurvey: function(html) {
            Guide.setBubbleHTML(html);
            
            if (Guide.pastSurveyResults.length > 0) {
               var tmp = $('form#guide-survey-form-' + Guide.pastSurveyResults[0]['question_id']).parent().attr('id').split('-');
               var nextId = (parseInt(tmp[(tmp.length - 1)]) + Guide.getNextQuestionId(Guide.pastSurveyResults[0]));
               $('div#guide-survey-form-block-' + nextId).removeClass('hidden');
            } else {
               $('div.guide div.form-block:first').removeClass('hidden');
            }
            
            //$('div.guide div.form-block:first').removeClass('hidden');
        },
        setBubbleHTML: function(html) {
            Guide.show();
            $('div.guide').html(html);
        },
        hide: function() {
            $('div.concordance-guide').addClass('hidden');
        },
        show: function() {
            $('div.concordance-guide').removeClass('hidden');
        },
        answerSurvey: function(e) {
            // handle ids to prepare showing next survey msg
            var id = $(this).parent().parent().parent().attr('id');
            // get question_id for storage
            var tmp = $(this).parent().parent().attr('id').split('-');
            // store question and answer(s) temporary
            var question_id = parseInt(tmp[(tmp.length - 1)]);
            var answers = {
                question_id: question_id,
                values: []
            };
            // get answer(s)
            if ($('.guide-q-' + question_id).is('select')) {
                answers['values'].push($('.guide-q-' + question_id).val());
            } else {
                $('.guide-q-' + question_id + ':checked').each(function() {
                    var val = $(this).val();
                    var tmp = $(this).attr('id').split('-');
                    var textareaClass = tmp[(tmp.length - 2)] + '-' + tmp[(tmp.length - 1)];
                    if ($('div.guide textarea.guide-q-custom-answer-' + textareaClass).length > 0 && !$('div.guide textarea.guide-q-custom-answer-' + textareaClass).hasClass('hidden')) {
                        val = { 'val': $(this).val(), text: $('div.guide textarea.guide-q-custom-answer-' + textareaClass).val() };
                    }
                    answers['values'].push(val);
                });
            }
            //console.info('question_id: ' + question_id + "\n" + 'answer (values): ' + answers['values'] + "\n" + 'answer (text): ' + answers['text']);
            Guide.surveyResults = [];
            Guide.surveyResults.push(answers);
            var tmp = $(this).parent().parent().parent().attr('id').split('-');
            var nextId = (parseInt(tmp[(tmp.length - 1)]) + Guide.getNextQuestionId(answers));
            // hide current question and show next
            $('div#' + $(this).parent().parent().parent().attr('id')).addClass('hidden');
            /*
            if ($('div#guide-survey-form-block-' + nextId).length > 0) {
                $('div#guide-survey-form-block-' + nextId).removeClass('hidden');
            } else {
               Guide.postAnswersToWebservice();
            }
            */
            Guide.postAnswersToWebservice(nextId);
        },
        recordCustomAnswer: function() {
            var tmp = $(this).attr('id').split('-');
            var id = tmp[(tmp.length - 2)] + '-' + tmp[(tmp.length - 1)];
            if ($(this).attr('checked')) {
                $('textarea.guide-q-custom-answer-' + id).removeClass('hidden');
            } else {
                $('textarea.guide-q-custom-answer-' + id).addClass('hidden');
            }
        },
        postAnswersToWebservice: function(nextId) {
         var lastQuestion = false;
         if ($('div#guide-survey-form-block-' + nextId).length <= 0) {
            lastQuestion = true;
         }
         //console.info(Guide.surveyResults);
            //Guide.setBubbleHTML('<p><strong>' + Guide.strings.survey_saving_answers + '</strong></p>');
            $.post(window.location.protocol+"//"+window.location.hostname+"/_lib_local/concordance/ConcordanceAjax.php", {
               action: 'saveSurveyResults',
               survey_id: Guide.survey_id,
               surveyResults: JSON.stringify(Guide.surveyResults),
               lastQuestion: lastQuestion
             }, function(res) {
               if (res) {
                  if ($('div#guide-survey-form-block-' + nextId).length > 0) {
                     $('div#guide-survey-form-block-' + nextId).removeClass('hidden');
                 } else {
                  Guide.setBubbleHTML('<p><strong>' + Guide.strings.survey_save_success + '</strong></p>');
                 }
               } else {
                  Guide.setBubbleHTML('<p><strong>' + Guide.strings.survey_save_fail + '</strong></p>');
               }
             },"json");
        },
        /*
        postAnswersToWebservice: function() {
         //console.info(Guide.surveyResults);
            Guide.setBubbleHTML('<p><strong>' + Guide.strings.survey_saving_answers + '</strong></p>');
            $.post(window.location.protocol+"//"+window.location.hostname+"/_lib_local/concordance/ConcordanceAjax.php", {
               action: 'saveSurveyResults',
               survey_id: Guide.survey_id,
               surveyResults: JSON.stringify(Guide.surveyResults)
             }, function(res) {
               var bubbleHTML = Guide.strings.survey_save_fail;
               if (res) {
                  bubbleHTML = Guide.strings.survey_save_success;
               }
               Guide.setBubbleHTML('<p><strong>' + bubbleHTML + '</strong></p>');
             },"json");
        },
        */
        getNextQuestionId: function(answers) {
            //console.info(JSON.stringify(answers));
            var questionProperties = [
               {
                  question_ids: [21, 22],
                  answers: ['a', 'c'],
                  action: {
                     type: 'skip',
                     count: 1
                  }
               },
               {
                  question_ids: [23, 24],
                  answers: false,
                  action: {
                     type: 'skip',
                     count: 7
                  }
               },
               {
                  question_ids: [25],
                  answers: ['c'],
                  action: {
                     type: 'msg',
                     text: Guide.strings.discuss_with_doc
                  }
               },
               {
                  question_ids: [26],
                  answers: ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'],
                  action: {
                     type: 'msg',
                     text: Guide.strings.discuss_with_doc
                  }
               },
               {
                  question_ids: [30],
                  answers: ['d', 'e'],
                  action: {
                     type: 'skip',
                     count: 1
                  }
               },
               {
                  question_ids: [35, 36],
                  answers: ['a'],
                  action: {
                     type: 'skip',
                     count: 1
                  }
               },
               {
                  question_ids: [37, 38],
                  answers: false,
                  action: {
                     type: 'skip',
                     count: 24
                  }
               },
               {
                  question_ids: [39],
                  answers: ['c'],
                  action: {
                     type: 'msg',
                     text: Guide.strings.discuss_with_doc
                  }
               },
               {
                  question_ids: [40],
                  answers: ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'],
                  action: {
                     type: 'msg',
                     text: Guide.strings.discuss_with_doc
                  }
               },
               {
                  question_ids: [43],
                  answers: ['c', 'd'],
                  action: {
                     type: 'skip',
                     count: 1
                  }
               },
               {
                  question_ids: [45],
                  answers: ['c', 'd', 'e'],
                  action: {
                     type: 'skip',
                     count: 1
                  }
               }
            ];
            var next = 1;
            jQuery.each(questionProperties, function() {
               var _t = this;
               jQuery.each(_t.question_ids, function() {
                  if (this != answers.question_id) return true;
                  var doIt = false;
                  jQuery.each(answers.values, function() {
                     var in_array = false;
                     var _a = this;
                     if (_t.answers) {
                        jQuery.each(_t.answers, function() {
                           //console.info('this: ', this, ' _a: ', _a);
                           if (in_array) return true;
                           if (_a.valueOf() != this.valueOf()) return true;
                           in_array = true;
                           return false;
                        });
                        if (in_array) {
                           doIt = true;
                        }
                     } else {
                        doIt = true;
                     }
                  });
                  if (doIt) {
                     switch(_t.action.type) {
                        case 'msg':
                           alert(_t.action.text);
                           break;
                        case 'skip':
                           next = next + _t.action.count;
                           break;
                        default:
                     }
                  }
                  return false;
                  // hier weitermachen, auf antwort checken und entsprechende schritte einrichten
               });
            });
            return next;
        }
    }