/**
 * @copyright Affinitive, LLC (support@beaffinitive.com)
 * @author Rob Marscher (rmarscher@beaffinitive.com)
 * @package Enclave
 */
 
/**
 * Affinitive_Gateway
 * Class for dealing with age gates and other checks via javascript
 */
Affinitive_Gateway = function(options) {
	this.settings = {
		url        : '',         // gateway url 
		cookie     : 'chk-visit', // cookie name
		ban        : false,       // do we set a ban if criteria not met? - not implemented
		minAge     : 13,          // minimum age required - not implemented
		cookieDays : 1,           // cookie expiry in days
		overlay    : 'black'      // page overlay type
	};
	
	if (options) {
		jQuery.extend(this.settings, options);
	};
};
Affinitive_Gateway.prototype = {
	init: function() {
		var gateway = this;
		if (!this.check()) {
			jQuery(document).ready(function() {
				gateway._showPopup();
			});
			return true;
		} 
		return false;
	},
	ok: function() {
		this.extendCookie();
		this._hidePopup();
	},
	extendCookie: function() {
		var date = new Date();
		date.setTime(date.getTime() + (this.settings.cookieDays * 86400000));
		var cookieValue = this.settings.cookie + "=true; expires="+ date.toGMTString() + "; path=/;";
		if (fpglobals.cookieDomain) {
			cookieValue += " domain=" + fpglobals.cookieDomain + ";";
		}
		document.cookie = cookieValue;
	},
	check: function() {
		if (document.cookie.length > 0) {
			var start, end;
			start = document.cookie.indexOf(this.settings.cookie + "=");
			if (start != -1) {
				start = start + this.settings.cookie.length+1;
				end = document.cookie.indexOf(";", start);
				if (end == -1) {
					end = document.cookie.length;
				}
				return unescape(document.cookie.substring(start, end));
			} 
		}
		return false;
	},
	_showPopup: function() {
		this.overlay = jQuery('<div></div>')
			.addClass('overlay-' + this.settings.overlay)
			.css({height: jQuery(document).height() + 'px'})
			.appendTo(document.body).fadeIn();
		overlay = this.overlay;
		jQuery(window).resize(function() {
			overlay.css({height: jQuery(document).height() + 'px'});
		});
		var gatewayContent = jQuery('#gatewayContent');
		if (gatewayContent.length == 0) {
			// I think this will help keep users from doing much before
			// the gateway loads
			jQuery.ajaxSetup({
				async: true
			});
			this.popup = jQuery('<div></div>')
				.addClass('overlay-content')
				.load(this.settings.url)
				.appendTo(document.body)
				.fadeIn();
			jQuery.ajaxSetup({
				async: false
			});
		} else {
			this.popup = jQuery('<div></div>')
				.addClass('overlay-content')
				.html(gatewayContent.html())
				.appendTo(document.body)
				.fadeIn();
		}
		jQuery('object').css('visibility', 'hidden');
	},
	_hidePopup: function() {
		this.popup.remove();
		this.overlay.remove();
		jQuery('object').css('visibility', 'visible');
	}
};
