﻿BenefulMap.ModalAddSpot = BenefulMap.ModalAuthenticatedForm.extend({
    init: function(modalTitle, modalSlug, modalElements, modalOptions, snippetPath, params, formElements, fieldsets, links, continueButtons, categoryButtons, otherCategorySuggestion) {
        this._super(modalTitle, modalSlug, modalElements, modalOptions, snippetPath, params, formElements);
        this.fieldsets = fieldsets;
        this.links = links;
        this.continueButtons = continueButtons;
        this.categoryButtons = modalElements.modalDiv + " " + categoryButtons;
        this.otherCategorySuggestion = modalElements.modalDiv + " " + otherCategorySuggestion;
        this.allowSubmission = true;
        this.redisplayWithErrors = false;
		this.openListener("addspot.open");
    },
	openListener: function(eventName) {
		var self = this;
		$(document).bind(eventName, function(event) {
			self.open();
		});
	},
    getCategoryButtons: function() {
        return this.categoryButtons;
    },
    getOtherCategorySuggestion: function() {
        return this.otherCategorySuggestion;
    },
    radioButtonListeners: function() {
        var self = this;
        console.log(this.getCategoryButtons());
        console.log(this.getOtherCategorySuggestion());
        $(this.getCategoryButtons()).click(function(event) {
            if ($(this).val() == "5") {
                $(self.getOtherCategorySuggestion()).removeAttr("disabled");
            } else {
                $(self.getOtherCategorySuggestion()).attr("disabled", "disabled");
            }
        });
    },
    getCurrentStage: function() {
        return this.currentStage;
    },
    setCurrentStage: function(currentStage) {
        this.currentStage = currentStage;
    },
    switchStage: function(newStage, disableContinueButton) {
        this.setCurrentStage(newStage);
        this.showFieldset(newStage);
        if (newStage == "step1" || newStage == "step2") {
            console.log("setting validation listeners");
            this.validationListeners();
        }
        if (disableContinueButton == true) {
            this.disableCurrentContinueButton();
        }
        console.log("Current Stage is now: ", this.getCurrentStage());
    },
    goToNextStage: function() {
        switch (this.getCurrentStage()) {
            case "step1":
                this.switchStage("step2", true);
                break;
            case "step2":
                this.switchStage("uploadPhoto", false);
                break;
            case "uploadPhoto":
                this.processForm();
                break;
            default:
                return false;
        }
    },
    goToPrevStage: function() {
        switch (this.getCurrentStage()) {
            case "step2":
                this.switchStage("step1", false);
                break;
            case "uploadPhoto":
                this.switchStage("step2", false);
                break;
            default:
                return false;
        }
    },
    getFieldsets: function() {
        return this.fieldsets;
    },
    setFieldsets: function(fieldsets) {
        this.fieldsets = fieldsets;
    },
    getIndividualFieldset: function(dataKey) {
        return this.fieldsets[dataKey];
    },
    setIndividualFieldset: function(dataKey, dataValue) {
        this.fieldsets[dataKey] = dataValue;
    },
    showFieldset: function(fieldsetKey) {
        jQuery.each(this.getFieldsets(), function(key, val) {
            if (key == fieldsetKey) {
                $(val).show();
            } else {
                $(val).hide();
            }
        });
    },
    getLinks: function() {
        return this.links;
    },
    setLinks: function(links) {
        this.links = links;
    },
    getBackLinks: function() {
        return this.links.back;
    },
    setBackLinks: function(backLinks) {
        this.links.back = backLinks;
    },
    getSkipLinks: function() {
        return this.links.skip;
    },
    setSkipLinks: function(skipLinks) {
        this.links.skip = skipLinks;
    },
    getContinueButtons: function() {
        return this.continueButtons;
    },
    setContinueButtons: function(continueButtons) {
        this.continueButtons = continueButtons;
    },
    populate: function() {
		var self = this;
		jQuery.ajax({
		    type: "GET",
			cache: false,
			url: self.getSnippetPath(),
			data: self.getParams(),
			success: function(data, textStatus) {
				$( self.getModalDiv() ).html(data);
				$( self.getModalDiv() ).dialog('open');
				self.embedPhotoSwf();
				self.addModalListeners();
			},
			dataType: "html"
		});
	},
    addModalListeners: function(stepName) {
        if (stepName) {
            this.switchStage(stepName, true)
        } else {
            this.switchStage("step1", true);
        }
        this._super();
        this.backLinksListener();
        this.skipLinksListener();
        this.showFieldset(this.getCurrentStage());
        this.radioButtonListeners();
    },
    backLinksListener: function() {
        var self = this;
        $(this.getBackLinks()).click(function() {
            self.goToPrevStage();
        });
    },
    skipLinksListener: function() {
        var self = this;
        $(this.getSkipLinks()).click(function() {
            self.goToNextStage();
        });
    },
    embedPhotoSwf: function() {
    	console.info("embedding swf");
        var swfContainer = "flashcontent";
        var swfPath = root + "_res/swf/TransformTool.swf";
        var expressInstallPath = root + "_res/swf/expressInstall.swf";

        var flashvars = {};
        flashvars.BusinessID = $("#flash-business-id input").val();
        flashvars.PhotoKey = $("#flash-user-id input").val();
        flashvars.endpointURI = $("#FlashEndPointUri").val();
		flashvars.serverLocation = $("#FlashServerLocation").val();
        flashvars.Context = "Admin";
        flashvars.flash_name = "flashcontent";

        var params = {};
        params.quality = "high";
        params.allowScriptAccess = "sameDomain";
        params.wmode = "transparent";
        params.base = root + "_res/swf/";
        params.bgcolor = "#ffffff";

        var attributes = "";

        swfobject.embedSWF(swfPath, swfContainer, "710", "500", "10", expressInstallPath, flashvars, params, attributes);
    },
    continueButtonListener: function() {
        var self = this;
        $(this.getContinueButton()).unbind();
        $(this.getContinueButton()).click(function(event) {
            event.preventDefault();
            if (self.currentContinueButtonIsEnabled()) {
                self.goToNextStage();
            }
        });
    },
    getCurrentContinueButton: function() {
        return this.continueButtons[this.getCurrentStage()];
    },
    setCurrentContinueButton: function(val) {
        this.continueButtons[this.getCurrentStage()] = val;
    },
    currentContinueButtonIsEnabled: function() {
        if ($(this.getCurrentContinueButton()).hasClass('disabled') == false) {
            return true;
        } else {
            return false;
        }
    },
    disableCurrentContinueButton: function() {
        console.info("Current ontinue button disabled :(");
        $(this.getCurrentContinueButton()).addClass("disabled");
    },
    enableCurrentContinueButton: function() {
        console.info("Current continue button enabled :)");
        $(this.getCurrentContinueButton()).removeClass("disabled");
    },
    getCurrentFieldsToValidate: function() {
        return this.formElements[this.getCurrentStage()].fieldsToValidate;
    },
    setCurrentFieldsToValidate: function(fields) {
        this.formElements[this.getCurrentStage()].fieldsToValidate = fields;
    },
    getCurrentFieldsToSerialize: function() {
        return this.formElements[this.getCurrentStage()].fieldsToSerialize;
    },
    setCurrentFieldsToSerialize: function(fields) {
        this.formElements[this.getCurrentStage()].fieldsToSerialize = fields;
    },
    getCurrentRequiredFields: function() {
        return this.formElements[this.getCurrentStage()].requiredFields;
    },
    setCurrentRequiredFields: function(fields) {
        this.formElements[this.getCurrentStage()].requiredFields = fields;
    },
    validationListeners: function() {
        var self = this;
        $(this.getCurrentFieldsToValidate()).blur(function(event) {
            self.validateField(this);
        });
        $(this.getCurrentFieldsToValidate()).change(function(event) {
            self.validateField(this);
        });
        $(this.getCurrentFieldsToSerialize()).keyup(function(event) {
            var validStatus = self.checkCurrentFormIsValid();
            self.setFormStatus(validStatus);
        });
    },
    validateField: function(formItem) {
        var self = this;
        var fieldData = {};
        fieldData.FieldName = $(formItem).attr('name');
        fieldData.FieldAnswer = $(formItem).val();
        var json = JSON.stringify(fieldData);
        var validationFunction = 'Validate' + fieldData.FieldName;
        WagWorld.Web.AjaxValidation[validationFunction](json, function(result) {
            var errorMsg = result.value.ErrorMessage;
            var fieldName = result.value.FieldName;
            if (!errorMsg) {
                console.info(fieldName + " passed validation :)");
                $(formItem).removeClass("invalidField");
            } else {
                console.info(fieldName + " failed validation :(");
                $(formItem).addClass("invalidField");
            }
            var validForm = self.checkCurrentFormIsValid();
            self.setFormStatus(validForm);
        });
    },
    checkCurrentFormIsValid: function() {
        var validForm = true;
        $(this.getCurrentRequiredFields()).each(function() {
            if ($(this).val() == "" || $(this).val() == '- Choose -') {
                validForm = false;
            }
        });
        $(this.getCurrentFieldsToValidate()).each(function() {
            if ($(this).hasClass("invalidField")) {
                validForm = false;
            }
        });
        return validForm;
    },
    submitFormData: function() {

        if (this.allowSubmission == true) // prevent hyperactive users from clicking the Send button over and over and submitting duplicate records.  Added per a defect
        {
            this.allowSubmission = false;
            this._super();
            var self = this;
            var output = {};
            this.disableCurrentContinueButton();
            jQuery.each(this.getFormData(), function(key, value) {
                key = key.replace("Optional", "");
                if ((key != "Review") && (key != "Rating") && (key != "Headline")) {
                    output[key] = value;
                }
            });
            var photoKey = $("#flash-user-id input").val();

            output.photoKey = $("#flash-user-id input").val();
            console.log("output is: ", output);
            console.log("photo key is", photoKey);
            var review = this.getIndividualFormData("Review");
            var rating = parseInt(this.getIndividualFormData("Rating"));
            var headline = this.getIndividualFormData("Headline");
            var jsonBusinessObject = JSON.stringify(output);

            WagWorld.Web.AjaxUtility.AddSpot(jsonBusinessObject, review, rating, headline, photoKey, function(result) {
                console.log(result);
                self.checkResult(result.value.Pass, result.value.Reason, result.value.AuxiliaryInt, result.value.AuxiliaryNumber);
            });
        }
    },
    checkResult: function(pass, msg, stageNum, idNum) {
        this.allowSubmission = true;
        if (pass == true) {
            if (msg == "promotion" || msg == " promotion") {
                this.close();
                $(document).trigger("promotion.open", [0, "Spot"]);
            } else {
                this.showThankYou(idNum);
            }
        } else {
            if (msg == "UserNotAuthenticated") {
                this.close();
                $(document).trigger("login.open");
            } else {
                this.redisplayFormWithMessage(msg, stageNum);
            }
        }
    },
    repopulate: function(stageNum) {
        var self = this;
        jQuery.ajax({
            type: "GET",
            url: self.getSnippetPath(),
            data: self.getParams(),
            cache: false,
            success: function(data, textStatus) {
                $(self.getModalDiv()).html(data);
                $(self.getModalDiv()).dialog('open');
                self.addModalListeners("step2");
            },
            dataType: "html"
        });
    },
    showThankYou: function(idNum) {
        this.setTitle("Thank You");
        var params = {};
        params.ph = 2;
        params.id = idNum;
        this.setParams(params);
        this.populate();
    },
    redisplayFormWithMessage: function(message, stageNum) {
        var params = {};
        params.ph = 1;
        params.message = message;
        this.setParams(params);
        this.repopulate(stageNum);
    },
    revertToInitialState: function() {
        this._super();
        this.switchStage("step1", true);
    },
    serializeFormData: function() {
        var self = this;
        var serializedData = $(this.getFieldsToSerialize()).serializeArray();
        jQuery.each(serializedData, function() {
            if (this.value != "on") {
                self.setIndividualFormData(this.name, this.value);
            }
        });
        $(this.getModalDiv() + " input[name=Rating]").each(function() {
            if (this.checked) {
                self.setIndividualFormData("Rating", $(this).val());
            }
        });
    }
});