//REQUIRES: jquery, jquery.cookie, NIKEOS.global.js (NIKEOS.AjaxController AC), f4a_js.js, jquery.blockUI2.26.js

/**
 ** TermsOfService
 * When included on every page of a website, this javascript guarantees that a logged in user has accepted the
 * terms and conditions for social interaction legally required by Nike.
 * 
 ** How it works:
 *	For a logged in user, the init function checks for the terms of service cookie (TERMS_OF_SERVICE_UPDATED).
 *		If the value is "CONFIRMED", everything's ok - no further action.
 *		If the cookie doesn't exist, check the UPM getattribute service for TERMS_OF_SERVICE_UPDATED attribute.
 *			If this value is "CONFIRMED", everything's ok - no further action.
 *			If this attribute doesn't exist, prompt the user to accept the terms (popup)
 *				User declines - log out user and redirect them to "config['redirect']" URL
 *				User accepts - set TERMS_OF_SERVICE_UPDATED cookie AND attribute w/ UPM setattribute service
 *
 ** Required code on each page (easiest to include in templates/fragments/usefuljs.html):

<script type="text/javascript"> 
var AC_OPTIONS = {
f4a : {
swf_src : "http://www.nike.com/nikeos/global/swf/f4a/f4a.swf",
js_src : "http://www.nike.com/nikeos/global/js/f4a_js.js"
}
};
var AC = new NIKEOS.AjaxController(AC_OPTIONS);

var TOS_OPTIONS = {
PS : "${yellowPageConfig.profileService}",
locale : "${platypus_region?js_string}",
membershipid : '300',
redirect : '/nikeos/p/nikewomen/${platypus_region?js_string}/'
};

var TOS = new TermsOfService(TOS_OPTIONS);

//This translation text should come from localeConfig per locale
TOS.trans.sampleText = "${localeConfig.config.tos.sampleText}";
TOS.trans.termsHeader = "${localeConfig.config.tos.termsHeader}";
TOS.trans.termsCopy = '${localeConfig.config.tos.termsCopy}';
TOS.trans.cancel = "${localeConfig.config.tos.cancel}";
TOS.trans.accept = "${localeConfig.config.tos.accept}";

JQ(document).ready(function(){
TOS.init();
});
</script>
 */
var TermsOfService = function(options){
	var self = this;
	
	/**
	 * config
	 * category/locale specific configuration variables - currently using:
	 *	config['locale'] : i.e. en_US, fr_FR - must be in a format accepted by the profileService (not en_EMEA, en_AFR, etc)
	 *	config['redirect'] : page to redirect a user to when they choose to NOT accept the terms
	 *	config['membershipid'] : category-, sometimes locale-, specific membership ID for use with profile service
	 *	config['PS'] : yellowpages profileService URL
	 */
	self.config = options;
	self.config['COOKIE'] = 'TERMS_OF_SERVICE_UPDATED';
	
	self.trans = {}; //stores translations from localeConfig that are set in platypus templates
	
	self.init = function(){
		self.setUpPopup();
		if(self.isLoggedIn()){
			if(!self.hasCookie()){
				self.checkTerms();
			}
		}
	};

	self.hasCookie = function(){
		if(JQ.cookie(self.config['COOKIE'])){
			return (JQ.cookie(self.config['COOKIE']) == 'CONFIRMED');
		}
		return false;
	};
	
	self.setCookie = function(){
		JQ.cookie(self.config['COOKIE'],'CONFIRMED',{path:'/'});
	};

	self.checkTerms = function(){
		var data = {
			url : self.config['PS'],
			method : "POST",
			post_data : "action=getattribute&membershipid=" + self.config["membershipid"] + "&attributeName=" + self.config["COOKIE"]
		};
		var callback = function(data){
			var data = JQ.xml2json(data);
			if(data.status == 'success'){
				if(data.attributes[self.config['COOKIE']] == 'CONFIRMED'){
					self.setCookie();
				} else {
					self.showPopup();
				}
			}
		};

		window.makeRequest = function(){
			AC.request(data, callback);
		}

		//Safari timing fix
		if(BrowserDetect.browser == 'Safari'){
			setTimeout("makeRequest()", 1000);
		} else {
			makeRequest();
		}
	};
	
	self.setTerms = function(cb){
		var cb = cb || function(){};
		var data = {
			url : self.config['PS'],
			method : "POST",
			post_data : "action=setattribute&membershipid=" + self.config["membershipid"] + "&attributeName=" + self.config["COOKIE"] + "&attributeValue=CONFIRMED"
		};
		var callback = function(data){
			var data = JQ.xml2json(data);
			if(data.status == 'success'){
				self.setCookie();
				cb();
			} else {
				console.warn('Error setting Terms and Conditions Attribute');
			}
		};
		AC.request(data, callback);
	};
	
	self.logout = function(cb){
		var data = {
			url : self.config['PS'],
			method : "POST",
			post_data : "action=logout"
		};
		var callback = function(data){
			NIKEOS.ME.clearSocialCookies();
			location.href = self.config['redirect'];
		};
		AC.request(data, callback);
	};
	
	self.isLoggedIn = function(){
		if(JQ.cookie('id.nike.com')){
			if(Base64.decode(JQ.cookie('id.nike.com')).split(':')[0] != 'null'){
				return true;
			}
		}
		return false;
	};
	
	self.showPopup = function(){
		if (JQ.browser.msie && JQ.browser.version.substr(0,1)<7) {
			JQ.blockUI({ message: JQ('#tnc_popup'), css: { top: '30px', cursor: 'auto' } });
		} else {
			JQ.blockUI({ message: JQ('#tnc_popup'), css: { width: '100%', 'text-align': 'center', left: 'auto', top: '20%', cursor: 'auto' } });
		}
	};
	
	self.hidePopup = function(){
		JQ.unblockUI();
	};
	
	self.setUpPopup = function(){
		var html = [];
		html.push('<div id="tnc_popup" class="jqmWindow">');
		html.push('	<div id="top">');
		html.push('		<div id="close"></div>');
		html.push('	</div>');
		html.push('	<div id="body_wrapper">');
		html.push('		<div id="body">');
		html.push('			<div id="body_inner">');
		html.push('				<div class="tocPrompt">');
		html.push('					<div class="toc_header">' + self.trans.termsHeader + '</div>');
		html.push('					<div class="clear"></div>');
		html.push('					<div class="message">' + self.trans.termsCopy + '</div>');
		html.push('					<div class="clear"></div>');
		html.push('					<div id="bottom_options">');
		html.push('						<div class="accept"><div class="accept" style="float: left;"><div id="accept" class="red_button transparent activated"> <div class="btn_left"/> <div class="btn_content"> <div id="accept_btn">' + self.trans.accept  + '</div> </div> <div class="btn_right"/></div><div class="clearme"/></div></div>');
		html.push('						<div class="cancel">' + self.trans.cancel + '</div>');
		html.push('					</div>');
		html.push('				</div>');
		html.push('			</div>');
		html.push('		</div>');
		html.push('	</div>');
		html.push('	<div id="bot"></div>');
		html.push('</div>');
		JQ('body').append(html.join(''));
		JQ('#tnc_popup .accept').click(function(){
			self.setTerms(self.hidePopup);
		});
		JQ('#tnc_popup #close, #tnc_popup .cancel').click(function(){ self.logout(); self.hidePopup(); });
	};
}

