﻿BenefulMap.ModalTellFriend = BenefulMap.ModalForm.extend({
	init: function(modalTitle, modalElements, modalOptions, snippetPath, params, formElements, context) {
		formElements.requiredFields = formElements.requiredFields + ", #recaptcha_response_field";
		this._super( modalTitle, modalElements, modalOptions, snippetPath, params, formElements);
		this.context = context;
		this.originalContext = context;
		this.originalTitle = modalTitle;
		this.spotId = 0;
		this.articlePath = "";
		this.setTellFriendInitialParams();
		this.openListener("tellFriend.open");
		this.closeListener("tellFriend.close");
		this.resultsPopulatedListener("tellFriend.resulsPopulated");
	},
	getOriginalTitle: function() {
	   return this.originalTitle;
	},
	setOriginalTitle: function(originalTitle) {
	   this.originalTitle = originalTitle;
	},
	getOriginalContext: function() {
		return this.originalContext;
	},
	getContext: function() {
		return this.context;
	},
	setContext: function(context) {
		this.context = context;
	},
	getSpotId: function() {
		return parseInt(this.spotId,10);
	},
	setSpotId: function(spotId) {
		this.spotId = parseInt(spotId,10);
	},
	getArticlePath: function() {
		this.articlePath = $("body.article input.article-path").val();
		return this.articlePath;
	},
	setArticlePath: function(articlePath) {
		this.articlePath = articlePath;
	},
	getMapState: function() {
		return this.mapState;
	},
	setMapState: function(mapState) {
		this.mapState = mapState;
	},
	setTellFriendInitialParams: function() {
		var initialParams = {};
		initialParams.context = this.getContext();
		if (this.getContext() == "spot") {
			var id = jQuery.url.attr("file").replace(".aspx", "");
			this.setSpotId(id);
			initialParams.id = this.getSpotId();
		}
		this.setParams(initialParams);
	},
	getParamsFromMapState: function(mapState) {
		if (this.context == "results") {
			var params = {};
			params.context = "results";
			params.id = mapState.toJSON();
			params.location = mapState.getLocation();
		}
		this.setMapState(mapState);
		this.setParams(params);
	},
	showThankYou: function() {
		this.setTitle("Email Sent Successfully");
		this.setContext("thankyou");
		var params = {};
		params.context = this.getContext();
		this.setParams(params);
		this.populate();
	},
	redisplayFormWithMessage: function(message) {
        var params = {};
        params.message = message;
        this.setParams(params);
        this.populate();
	},
	close: function() {
		$(this.getModalDiv()).dialog('close');
	},
	loadRecaptcha: function() {
		var self = this;
		var googleAPIKey = $("#recaptchaPubKey").val();
		Recaptcha.create(googleAPIKey,
		    "recapcha-div",
		    {
		    	theme: "white",
		    	callback: function() {
					$("#recaptcha_response_field").click( function() {
						console.info("clicked recaptcha");
						self.checkFormIsValid();
					});
					$("#recaptcha_response_field").blur( function() {
						console.info("blur recaptcha");
						var formStatus = self.checkFormIsValid();
						self.setFormStatus(formStatus);
					});
				}
		    }
		);
	},
	validateRecaptcha: function() {

	},
	getRecaptchaResponse: function() {
		var response = Recaptcha.get_response();
		return response;
	},
	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;
			}
		});
		if (!this.getRecaptchaResponse()) {
			validForm = false;
		};
		console.info("Form is ", validForm);
		return validForm;
	},
	setFormStatus: function(validForm) {
		if (validForm == true) {
			this.enableContinueButton();
		} else {
			this.disableContinueButton();
		}
	},
	addModalListeners: function() {
		this._super();
		var self = this;
		this.loadRecaptcha();
		$("a.restart").click(function(event) {
			event.preventDefault();
			self.setTitle("Invite a Friend");
			self.close();
			self.open();
		});	
	},
	submitFormData: function() {
		this._super();
		var toEmail = this.getIndividualFormData('FriendEmailAddress');
		var fromName = this.getIndividualFormData('YourName');
		var fromEmail = this.getIndividualFormData('YourEmailAddress');
		var msg = this.getIndividualFormData('FriendMessage');
		var self = this;
		var challenge = Recaptcha.get_challenge();
		var response = Recaptcha.get_response();
		var recaptchaPassed = false;
		
		WagWorld.Web.AjaxUtility.Validate(challenge, response, function(result) {
		    recaptchaPassed = result.value;
		    console.log(recaptchaPassed," in validateRecaptcha");	
			if(recaptchaPassed)
			{
				console.info("recaptcha passed");
				switch(self.context) {
				    case "results":
						var mapState = this.getMapState();
						WagWorld.Web.AjaxUtility.TellFriendAboutResults(mapState.toJSON(), mapState.getLocation(), toEmail, fromName, fromEmail, msg, function(result) {
							self.checkResult(result.value.Pass, result.value.Reason);
						});
					break;

		            case "spot":
		            // int businessId, string toEmail, string fromName, string optionalMessage
						WagWorld.Web.AjaxUtility.TellFriendAboutSpot(self.getSpotId(), toEmail, fromName, msg, function(result) {
							self.checkResult(result.value.Pass, result.value.Reason);
						});
					break;
					case "site":
						WagWorld.Web.AjaxUtility.TellFriendAboutSite(toEmail, fromName, fromEmail, msg, function(result) {
							self.checkResult(result.value.Pass, result.value.Reason);
						});
					break;
					case "article":
						WagWorld.Web.AjaxUtility.SendArticleToFriend(self.getArticlePath(),toEmail, fromEmail, fromName, msg, function(result) {
							self.checkResult(result.value.Pass, result.value.Reason);
						});
					break;
				}
			}
			else {
				$(".recaptcha-error").show();
				Recaptcha.reload();
			}
		});	
	},
	checkResult: function(pass, msg) {
        if (pass == true) {
            this.showThankYou();
        } else {
            this.redisplayFormWithMessage(msg);
        }
	},
	resultsPopulatedListener: function() {
		if (this.getContext() == "results") {
			var self = this;
			$(document).bind("tellFriend.resultsPopulated", function(event, mapState) {
				self.getParamsFromMapState(mapState);
				self.setMapState(mapState);
			});
		}
	},
	revertToInitialState: function() {
		this.setContext(this.getOriginalContext());
		var initialParams = {};
		initialParams.context = this.getContext();
		if (this.getContext() == "spot") {
			var id = jQuery.url.attr("file").replace(".aspx", "");
			this.setSpotId(id);
			initialParams.id = this.getSpotId();
		}
		if (this.getContext() == "results") {
			var mapState = this.getMapState();
			initialParams.context = "results";
			initialParams.id = mapState.toJSON();
			initialParams.location = mapState.getLocation();
		}
		this.setTitle(this.getOriginalTitle());
		this.setParams(initialParams);
	}
});
