﻿// Class ModalForm
//
// - Requires -
// jquery.js
// class.js
// modal.js
//
// - Inherits from -
// Modal Class (see modal.js)
//
// - Properties -
// modalElements: object containing
//		modalDiv - div that $().dialog() is called on
//		targetElement - link that fires dialog()
// snippetPath: absolute path to snippet aspx
// params: Query string params for ajax populate call
// modalTitle: Friendly title for modal (added to modalOptions)
// modalOptions: the options object passed into $().dialog()
// formElements: object containing
//		fieldsToSerialize
//		fieldsToValidate
//		requiredFields


BenefulMap.ModalForm = BenefulMap.Modal.extend({
	init: function(modalTitle, modalElements, modalOptions, snippetPath, params, formElements) {
		this._super( modalTitle, modalElements, modalOptions, snippetPath, params);
		this.continueButton = this.modalDiv + " button.continue";
		this.cancelButton = this.modalDiv + " .cancel";
		this.textfieldWithCountdown = this.modalDiv + " textarea.textfield-with-countdown";
		this.countdownField = this.modalDiv + " span.textfield-countdown";
		this.formElements = formElements;
		this.formData = {};
		this.requiredFieldsFilled = false;
		this.invalidFieldPresent = false;
	},
	getTextfieldWithCountdown: function() {
		return this.textfieldWithCountdown;
	},
	setTextfieldWithCountdown: function(textfieldWithCountdown) {
		this.textfieldWithCountdown = textfieldWithCountdown;
	},
	getCountdownField: function() {
		return this.countdownField;
	},
	setCountdownField: function(countdownField) {
		this.countdownField = countdownField;
	},
	getFormElements: function() {
		return this.formElements;
	},
	setFormElements: function(formElements) {
		this.formElements = formElements;
	},
	getFieldsToSerialize: function() {
		return this.formElements.fieldsToSerialize;
	},
	setFieldsToSerialize: function(fieldsToSerialize) {
		this.formElements.fieldsToSerialize = fieldsToSerialize;
	},
	getFieldsToValidate: function() {
		return this.formElements.fieldsToValidate;
	},
	setFieldsToValidate: function(fieldsToValidate) {
		this.formElements.fieldsToValidate = fieldsToValidate;
	},
	getRequiredFields: function() {
		return this.formElements.requiredFields;
	},
	setRequiredFields: function(requiredFields) {
		this.formElements.requiredFields = requiredFields;
	},
	getContinueButton: function() {
		return this.continueButton;
	},
	setContinueButton: function(continueButton) {
		this.continueButton = continueButton;
	},
	disableContinueButton: function() {
		console.info("Continue button disabled :(");
		$( this.getContinueButton() ).addClass("disabled");
	},
	enableContinueButton: function() {
		console.info("Continue button enabled :)");
		$( this.getContinueButton() ).removeClass("disabled");
	},
	continueButtonIsEnabled: function() {
		if ( $(this.getContinueButton()).hasClass('disabled') == false) {
			return true;
		} else {
			return false;
		}
	},
	getCancelButton: function() {
		return this.cancelButton;
	},
	setCancelButton: function(cancelButton) {
		this.cancelButton = cancelButton;
	},
	getFormData: function() {
		return this.formData;
	},
	setFormData: function(formData) {
		this.formData = formData;
	},
	getIndividualFormData: function(dataKey) {
		return this.formData[dataKey];
	},
	setIndividualFormData: function(dataKey, dataValue) {
		this.formData[dataKey] = dataValue;
	},
	addModalListeners: function() {
		this._super();
		this.continueButtonListener();
		this.cancelButtonListener();
		this.validationListeners();
		this.disableContinueButton();
		this.textareaCountListener();
		$('span.star input').rating();
		this.catchEnterKey();
		$(this.getModalDiv() + " input:text:first").focus();
	},
	catchEnterKey: function() {
		var self = this;
		$(this.getModalDiv() + " form").submit( function(event) {
			console.log("preventing submit");
			event.preventDefault();
		});
	},
	textareaCountListener: function() {
	    //N ext line checks for required textarea and counter objects or returns false
	    if ($(this.getTextfieldWithCountdown()).length == 0 && $(this.getCountdownField()).length == 0) return false;
	    var textfieldToBeCounted = $(this.getTextfieldWithCountdown()); // The textarea that will be counted and restricted
	    var areaToShowCount = $(this.getCountdownField());// The counter object. Visually shows the countdown of characters as it happens on the page
	    var maxAmountOfCharacters = $(this.getCountdownField()).html(); // The maximum number of characters a user will be allowed. WARNING: Pulled directly from the markup of the counter object.
	    textfieldToBeCounted.keyup(function(event) {
	        if ($(this).val().length <= maxAmountOfCharacters) {
	            areaToShowCount.html(maxAmountOfCharacters - $(this).val().length);
	        }
	        else if ($(this).val().length >= maxAmountOfCharacters) {
	            $(this).val($(this).val().substring(0, maxAmountOfCharacters));
	        }
	    });
	},
	cancelButtonListener: function() {
		var self = this;
		$( this.getCancelButton() ).unbind();
		$( this.getCancelButton() ).click(function(event) {
			event.preventDefault();
			self.close();
		});
	},
	continueButtonListener: function() {
		var self = this;
		$( this.getContinueButton() ).unbind();
		$( this.getContinueButton() ).click(function(event) {
			event.preventDefault();
			if ( self.continueButtonIsEnabled() ) {
				self.processForm();
			}
		});
	},
	validationListeners: function() {
		var validForm = this.checkFormIsValid();
		this.setFormStatus(validForm);
		
		var self = this;
		$( this.getFieldsToValidate() ).blur(function(event) {
			self.validateField(this);
	    });
		$( this.getFieldsToValidate() ).change(function(event) {
			self.validateField(this);
	    });
		$( this.getRequiredFields() ).change(function(event) {
			var validStatus = self.checkFormIsValid();
	        self.setFormStatus(validStatus);
		});
		$( this.getRequiredFields() ).click(function(event) {
			var validStatus = self.checkFormIsValid();
	        self.setFormStatus(validStatus);
		});
	    $( this.getRequiredFields() ).keyup( function(event) {
	        var validStatus = self.checkFormIsValid();
	        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.checkFormIsValid();
			self.setFormStatus(validForm);
		});		
	},
	checkFormIsValid: function() {
		var validForm = true;
		$( this.getRequiredFields() ).each( function() {
			if ($(this).val() == "") {
				validForm = false;
			}
		});
		if (this.testAdditionalRequiredFields() == false) {
			validForm = false;
		}
		
		$( this.getFieldsToValidate() ).each( function() {
			if ( $(this).hasClass("invalidField") ) {
				validForm = false;
			}
		});
		
		console.info("Form is ", validForm);
		return validForm;
	},
	testAdditionalRequiredFields: function() {
		return true;
		// overridden in child modals
	},
	setFormStatus: function(validForm) {
		if (validForm == true) {
			this.enableContinueButton();
		} else {
			this.disableContinueButton();
		}
	},
	processForm: function() {
		this.serializeFormData();
		this.submitFormData();
	},
	serializeFormData: function() {
		var self = this;
		var serializedData = $(this.getFieldsToSerialize()).serializeArray();
		console.log("serialized data: ", serializedData);
		jQuery.each(serializedData, function() {
			self.setIndividualFormData(this.name, this.value);
		});
		this.injectAdditionalDataIntoSerializedArray();
	},
	injectAdditionalDataIntoSerializedArray: function() {
		// this is overridden in child modals
	},
	submitFormData: function() {
		// Stub function: gets overriden
		console.info("This is the data that would get submitted: ", this.getFormData());
	}
});