/**
 * The class used for a guestbook module.
 */

var guestbook = $.inherit(Module, {
    __constructor: function(elem) {
        this.__base(elem);
        this.type = "guestbook";
        this.isResizing = true;
        this.keepAspectRatio = false;
        this.resizeAxes = 'x';
    },

    loadModuleCallback: function(data) {
        // We need to use innerHTML here because of the (highly probable)
        // chance that the html we get back has <script> in it.  jQuery 1.4
        // tries to be smart and not insert non-standard code.
        this.container[0].innerHTML = data.html;

        this.$form = this.container.find("#form-" + this.getModuleId());
        this.draghandle.addOptionLink("Edit Questions", createRef(this, this.editQuestions));
        this.$responseBlock = this.container.find(".error-block");
        this.$responseBlock.hide();

        this.addDragHandle(data);
        this.appropriatelyResize();
        this.manageModuleMargins();
        this.addResizing();
        this.activateForm();
        this.loadResponses(createRef(this, this.activateEvents));
        this.$submitButton = this.$form.find("#submitButton_" + this.getModuleId());
        this.isSaving = false;
		
    	/* hide and show responses in mobile view */
			var _this = this;
			$('.showResponses', this.container).click(function(){
				$('.response_container', _this.container).stop().slideToggle();
				$('.showME', _this.container).toggle();
				$('.hideME', _this.container).toggle();
				return false;
			});
	},

    activateEvents: function() {
        var _this = this;
        this.container.find(".delete-btn").click(function(ev) {
            ev.preventDefault();
            var i = this.id.replace("delete_", "");
            _this.deleteEntry(i);
        });

        this.container.find(".approve-btn").click(function(ev) {
            ev.preventDefault();
            var i = this.id.replace("approve_", "");
            _this.approveEntry(i);
        });

        this.container.find(".loadAllResponses").click(function(ev) {
            ev.preventDefault();
            _this.loadAllResponses();
        });

    },

    activateForm: function() {
        var _this = this;
        this.$form.submit(function(ev) {
            ev.preventDefault();
            _this.submitForm();
            return false;
        });
    },

    initialize: function () {
        this.$form = this.container.find("#form-" + this.getModuleId());
        this.activateForm();
        this.$responseBlock = this.container.find(".error-block");
        this.$submitButton = this.$form.find("#submitButton_" + this.getModuleId());

        this.$responseBlock.hide();
        this.loadResponses(createRef(this, this.activateEvents));
    },

    loadResponses: function(callback) {
        var $con = this.container.find(".response_container");
        this.ajaxPost("getResponses", {}, function(data) {
            $con.html(data.response.responses);
            (callback || $.noop)();
        });
    },

    loadAllResponses: function() {
        var $con = this.container.find(".response_container");
        $con.html("Loading all Responses...");
        this.ajaxPost("getAllResponses", {}, function(data) {
            $con.html(data.response.moarresponses);
        });
    },

    deleteEntry: function(id) {
        var _this = this;
        var mb = new ModalBox({title: "Delete this Response?"});
        mb.setHTML("<p>Are you sure you want to delete this response?</p>");
        mb.addButton("No", function() {
            mb.close();
        });

        mb.addButton("Yes", function() {
            _this.ajaxPost('deleteEntry', {id: id}, function() {
                _this.loadResponses(createRef(_this, _this.activateEvents));
                mb.close();
            }, 'blue');
        });

        mb.open();
    },

    approveEntry: function(id) {
        var _this = this;
        this.ajaxPost('approveEntry', {id: id}, function() {
            _this.loadModule();
        });
    },

    setResponseHTML: function(words, isGood) {
        this.$responseBlock.removeClass("good");
        this.$responseBlock.show().html(words);
        if (isGood) {
            this.$responseBlock.addClass("good");
        }
    },

    // The only reason this function is so long is because of the generation of the whole form.
    // All these silly divs that need to be generated, where we really need a JS Templating engine
    // D:
    editQuestions: function() {
        mb = new ModalBox({title: "Edit Questions", width: 500});
        mb.setHTML("<p>Select which questions you would like to ask</p><div class='question-window'>Loading...</div>");

        var $questionWindow = mb.getContentBlock().find('.question-window');
        var $questionTypeBlock = $("<select></select>").addClass("question-type");

        var addMultipleChoiceAnswer = function(qid, index, label) {
            var inputid = 'label-answer-' + qid + '-' + index;
            var $answerDiv = $("<div></div>").addClass("question-subanswer");
            $("<label></label>").attr("for", inputid).html("Label:").appendTo($answerDiv);
            $("<input />", {
                id: inputid,
                name: inputid,
                type: 'text',
                value: label,
                "class": 'question-input'
            }).appendTo($answerDiv);
            $("<a></a>").attr("href", "#").html("delete").addClass("deleteAnswer").click(function() {
                $answerDiv.remove();
            }).appendTo($answerDiv);

            return $answerDiv;
        }

        var addQuestionBlock = function(label, type, id, answers) {
            label = label || "";
            type = type || "text";
            id = id || null;

            var $block = $("<div></div>").addClass("question-block draggable");
            var $draghandle = $("<div></div>").addClass("question-handle").appendTo($block);
            var $labelarea = $("<div></div>").addClass("question-label-block").appendTo($block);
            var $typearea = $("<div></div>").addClass("question-type-block").appendTo($block);
            var $deleteButton = $("<a></a>").addClass("sprite delete-question-block").attr("href", "#").html("delete").appendTo($block);

            $deleteButton.click(function() {
                $block.remove();
            });

            $("<label></label>").attr("for", 'label-' + id).html("Label:").appendTo($labelarea);
            $("<input />", {
                id: 'label-' + id,
                name: 'label-' + id,
                type: 'text',
                value: label,
                "class": 'question-input'
            }).appendTo($labelarea);
			
			$("<label></label>").attr("for", 'type-' + id).html("Type:").appendTo($typearea);

            var $answerBlock = $("<div></div>").addClass("question-subanswer-block").appendTo($block);
            var $addAnswer = $("<a></a>").attr("href", "#").addClass("add-answer-button").html("Add Answer").appendTo($block).hide();
            $addAnswer.click(function(ev) {
                ev.preventDefault();
                var count = $answerBlock.children(".question-subanswer").size();
                $answerBlock.append(addMultipleChoiceAnswer(id, count, ""));
            });


            var $qb = $questionTypeBlock.clone();
            $qb.attr('id', "type-" + id).val(type);
            $qb.appendTo($typearea);
            $qb.change(function() {
                if ($(this).val().indexOf('select') >= 0) {
                    $answerBlock.show();
                    $addAnswer.show();
                    $answerBlock.append(addMultipleChoiceAnswer(id, 0, ""));
                }
                else {
                    $addAnswer.hide();
                    $answerBlock.empty().hide();
                }
            });

            if (answers) {
                $addAnswer.show();
                for (var i in answers) {
                    $answerBlock.append(addMultipleChoiceAnswer(id, i, answers[i].label));
                }
            }
            else {
                $answerBlock.hide();
            }

            $block.append($("<br />").addClass("clr"));
            $block.appendTo($questionWindow);

            return $block;
        }

        // Sends the new Question information to the DB.
        var save = function() {
            if (this.isSaving) {
                return;
            }

            this.isSaving = true;
            this.$saveQButton.addClass("disabled").html("Saving...");
            var $newList = $questionWindow.find('.question-block');
            var entries = [];
            var _this = this;

            $newList.each(function(i, el) {
                var label = $(el).find(".question-input").val();
                var type = $(el).find(".question-type").val();
                var answers = [];

                if ($(el).find(".question-subanswer-block").size() > 0) {
                    $(el).find(".question-subanswer-block").find("input").each(function() {
                        answers.push($(this).val());
                    });
                }
                entries[i] = {'label': label, 'type': type, 'answers': answers};
            });

            this.ajaxPost('setQuestions', {'question_list': entries}, function(data) {
                _this.loadModule();
                _this.isSaving = false;
                _this.$saveQButton.removeClass("disabled").html("Save &amp; Close");
                mb.close();
            });
        }

        // Generate all the options based for types of questions.
        var generateQuestionTypeBlock = function(types) {
            for (i in types) {
                $("<option></option>").attr("value", i).html(types[i]).appendTo($questionTypeBlock);
            }
        }

        // 
        var activateButtons = function() {
            $questionWindow.sortable({
                containment: 'parent',
                axis: 'y',
                items: 'div.draggable',
                handle: '.question-handle',
                opacity: '0.75',
                cursor: 'move',
                tolerance: 'pointer'
            });
            this.ajaxPost('getQuestionData', {}, function(data) {
                var qlist = data.response.questions;
                generateQuestionTypeBlock(data.response.types);
                $questionWindow.empty();
                for (i in qlist) {
                    var q = qlist[i];
                    addQuestionBlock(q.label, q.type, q.id, q.answers);
                }
            });
        }

        mb.addButton("Cancel", createRef(mb, mb.close));
        mb.addButton("Add Question", function() { addQuestionBlock('', 'text', 0) });
        this.$saveQButton = mb.addButton("Save &amp; Close", createRef(this, save), 'blue');

        mb.open(createRef(this, activateButtons));
    },

    resetForm: function(isFieldsClear) {
        if (isFieldsClear) {
            this.$form.get(0).reset();
        }
        this.$submitButton.val("Submit");
    },

    submitForm: function() {
        var entries = {};
        var _this = this;

        this.$responseBlock.hide();
        this.$form.find(".response-field").each(function() {
            var id = this.id.replace("input_", "");
            if (id.indexOf("_") > 0) {
                var radioNameArr = this.id.split("_");
                var origName = radioNameArr[0] + "_" + radioNameArr[1];
                var newId = radioNameArr[1];
                entries[newId] = $("input[name=" + origName + "]:checked").val();
            }
            else {
                entries[id] = $(this).val();
            }
        });

        var captchaDude = this.$form.find('#recaptcha_iframe').get(0);

        if (captchaDude) {
            // Add the recaptcha challenge field from the recaptcha iframe to the form
            entries['captcha_challenge'] = captchaDude.contentWindow.document.getElementById('recaptcha_challenge_field').value;
            entries['captcha_response'] = captchaDude.contentWindow.document.getElementById('recaptcha_response_field').value;
        }

        this.$submitButton.val("Submitting...");

        this.ajaxPost('addResponse', {response: entries}, function(data) {
            // On submission, always refresh the captcha
            if (captchaDude) {
                captchaDude.contentWindow.Recaptcha.reload();
            }

            if (data.response.error) {
                _this.resetForm(false);
                _this.setResponseHTML(data.response.error, false);
            }
            else {
                _this.resetForm(true);
                _this.setResponseHTML("Response Successfully Submitted", true);
                _this.loadResponses();
            }
        });
    }
});



