/*
	Dependency:
		/js/lib/jquery-1.6.4.min.js
		/js/src/core.js
		/js/lib/jquery.cookie.js
		/js/lib/jquery.blockUI.js
 */
//EmailSplash() --Singleton
//purpose: display a full-screen splash if user hasn't yet been nudged for sign-up
//init:
//  check the cookie, if set, finish; otherwise set up splash call
if (typeof B2.common == "undefined"){
	B2.common = {};
}

B2.common.EmailSplash =  {
	NEWSLETTER_COOKIE: 'SUPRESS_NEWSLETTER_SPLASH',
	DEALS_COOKIE: 'SUPPRESS_DEALS_SPLASH',
	isDealsSplash: false,
	splashCookieName: '',

	needsSplashed: function() {
		// splash cookie already set: no
		if ($('#email-splash .deals-signup-body').length > 0) {
			this.isDealsSplash = true;
			this.splashCookieName = this.DEALS_COOKIE;
		} else {
			this.splashCookieName = this.NEWSLETTER_COOKIE;
		}
		var splash = $.cookie(this.splashCookieName)
		if (undefined != splash) {
			return false;
		}
		// internal/partner referrer: no
		var ref = document.referrer
		if (ref != undefined && ref.length > 0 && ref.search('(saviply|bundle|localhost)') >= 0)
			return false

		// newsletter link ("?nns" as first search param): no
		if (window.location.search && window.location.search.indexOf('nss') == 1)
			return false;
			
		return true
	},

	// on click handler 'this' is an html div, refer to objects by full scope
	dismissSplash: function() {
		$.unblockUI();
		if (B2.common.EmailSplash.isDealsSplash) {
			var eventName = "Deals splash page exit";
		} else {
			var eventName = "Newsletter splash page exit";
		}
		B2.Tracking.trackEvent(eventName, 'Close', B2.Article.slug, true);
		// seen splash, disable for remainder of browser session.
		$.cookie(B2.common.EmailSplash.splashCookieName, true, { expires: null, path: '/'});
	},

	showSplash: function() {
		if (this.isDealsSplash) {
			var eventName = "Deals splash page enter";
		} else {
			var eventName = "Newsletter splash page enter";
		}
		B2.Tracking.trackEvent(eventName, 'Enter', B2.Article.slug, true);
		$.blockUI({
			message: $('#email-splash'), 
			overlayCSS: {
				opacity: .8,
				cursor: 'default'
			},
			css: {
				width: 240,
				padding: 12,
				top: '20%',
				border: '7px solid #aaa',
				cursor: 'default'
			},
			focusInput: false
		});
		$('.blockOverlay').attr('title','Click to unblock').click(this.dismissSplash);
		$('#splash-close').click(this.dismissSplash);
		
		// clear email subscribe field when clicked on
		B2.Core.Util.buildDefaultPrefill(
				$('#signup-email-input'),
				'Enter email address',
				'faded'
		);
		B2.Core.Util.buildDefaultPrefill(
				$('#signup-zip-input'),
				'Enter ZIP code',
				'faded'
		);
	},
	
	emailSubscribe: {
		init: function() {
			if (B2.common.EmailSplash.isDealsSplash) {
				var eventName = 'Deals Widget Sign up';
			} else {
				var eventName = 'Newsletter Widget Sign up';
			}
			actionName = 'Splash Page'

			$("#splash-form").submit(function(e) {
				B2.Tracking.trackEvent(eventName, actionName, 'Submitted', true)
				e.preventDefault();
				var email = "", zip = "";
				email = $("#signup-email-input").attr("value");
				zip = $('#signup-zip-input').attr("value");
				if (B2.common.EmailSplash.isDealsSplash) {
					var serviceUrl = "/services/deals-signup/";
				} else {
					var serviceUrl = "/services/email-subscribe/";
				}
        // make ajax call to fetch csrf token
        csrfToken = ""
        setCsrfToken = function(value) {
          csrfToken = value['csrf_token'];

          // post request to /email-subscribe/ handler
          $.ajax({
              url: serviceUrl,
              type: "POST",
              data: {"source":"splash", "email":email, "zip":zip, "csrfmiddlewaretoken":csrfToken},
              success: function(response) {
    						if (response.indexOf('Thanks') == 0) {
    							$("#signup-email-input").attr("disabled", "disabled");
    							$("#signup-zip-input").attr("disabled", "disabled");
    							B2.Tracking.trackEvent(eventName, actionName, 'ResponseSuccess', true)
    							// update the front end if user successfully subscribes
    							$.cookie(B2.common.EmailSplash.splashCookieName, true, { expires: 92, path: '/'});
    							setTimeout($.unblockUI,2000);
    						} else {
    							B2.Tracking.trackEvent(eventName, actionName, 'ResponseUserError', true)
    						}
    						$("#splash-status").html(response);
    						$("#splash-status").hide().fadeIn("fast");
              },
              error: function (response) {
                  B2.Tracking.trackEvent(eventName, actionName, 'ResponseServerError', true)
                  $("#splash-status").html("We had a server error, and couldn't subscribe you. But please, try again later, thanks!");
                  $("#splash-status").hide().fadeIn("fast");
    					},
    					complete: function(o) {
    						$("#splash-status").click(this.dismissSplash);
    					}
          });   
        }
        $.ajax({
          url: "/services/fetch-csrf/",
          type: "POST",
          async: false,
          success: setCsrfToken,
          error: function (response) {
            B2.Tracking.trackEvent(eventName, actionName, 'ResponseServerCsrfError', true)
            $("#splash-status").html("We had a server error, and couldn't subscribe you. But please, try again later, thanks!");
            $("#splash-status").hide().fadeIn("fast");
          }
        })
        // provide visual feedback to user
				$("#splash-status").html("Sending your request...");
				$("#splash-status").hide().fadeIn("fast");
			});
		}
	},

	init: function() {
		B2.Logger.log('EmailSplash init');
		if (this.needsSplashed()) {
			this.emailSubscribe.init();
			this.showSplash();
		}
	}
}
