﻿/* Cookie */
/**********/
var Cookie = {
	set: function(name, value, hoursToExpire) {
		var expire = '';
		if (hoursToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (3600000 * parseFloat(hoursToExpire)));//86400000ms = 1 day
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + '; path=/;');
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
};
/* Age Gate*/
/*
	Manages a the creation and posting of an age gate form.
	- An agegate is created for users that do not have a date of birth cookie, or a cookie with a 'failed' value.
	- The form is then posted server-side for redirection/cookie setting.
*/
var AgeGate = {
	userCode: 'en-us',
	listData: false,
	copyData: false,
	elements: {
		container: false,
		form: false,
		hdrStep1: false, 	// hp1_AgeGate.Step1
		subHdrStep1: false, // hp1_AgeGate.SelectRegion
		regionList: false,	
		hdrStep2: false,	// hp1_AgeGate.Step2
		subHdrStep2: false,	// hp1_AgeGate.AgePrompt
		dobList: false,
		lnkProceed: false	//hp1_AgeGate.ProceedButton
	},
	
	init: function(options){
		this.options = Object.extend({
			containerID: 'blocker_regionselect_agegate',
			formAction: '?',
			formMethod: 'post',
			enabled: true,
			DOBCookieName: 'hp1_AgeGate_Status',
			langCodeCookieName: 'LanguageInfo',
			startYear: 1930
		}, options || {});
		
		//$(document.body).removeClassName('js-enabled');

		this.elements.container = $(this.options.containerID);
		
		if(!(Object.isElement(this.elements.container)) || this.options.enabled == false){
			return;
		}
		else{
			this.elements.container.update();
		}
		
		// read DOB cookie, if it exists
		var dob = Cookie.get(this.options.DOBCookieName);
		if(dob && dob == 'passed'){
			this.removeBlocker();
			return;
		}
		
		// Get user code and set this.userCode if LangInfo exists
		var langInfo = Cookie.get(this.options.langCodeCookieName);
		if(langInfo){
			this.userCode = langInfo.toLowerCase();
		}
		
		this.createForm();
	
		this.getJSONData();
	},
	
	// shows the agegate.
	show: function(){
		this.elements.container.setStyle({'display':'block'});
		//CN: remove js class from body in order to hide the page from showing thru
		$(document.body).removeClassName('js-enabled');
	},
	
	removeBlocker: function(){
		this.elements.container.remove();
		//CN: add js class to body in order to show the page
		$(document.body).addClassName('js-enabled');
	},
	
	// generates the markup and element references for the agegate form, it doesn't populate the copy.
	createForm: function(){
		this.elements.form = new Element('form', {method: this.options.formMethod, action: this.options.formAction, id: 'frmAgeGate', name: 'frmAgeGate'});
		this.elements.container.insert(this.elements.form);
		
		// region
		this.elements.hdrStep1 = new Element('h4');
		this.elements.subHdrStep1 = new Element('h3');
		this.elements.regionList = new Element('ol');
		this.elements.hdrStep2 = new Element('h4');
		this.elements.subHdrStep2 = new Element('h3');
		this.elements.dobList = new Element('ol');
		this.elements.lnkProceed = new Element('a', {'class': 'btn-cta'});
	
		// Region fieldset and children
		var fstRegion = new Element('fieldset', { id:'fst-region'});
		fstRegion.insert(this.elements.hdrStep1)
			.insert(this.elements.subHdrStep1)
			.insert(this.elements.regionList);
		this.elements.form.insert(fstRegion);
		
		// DOB fieldset and children
		var fstDOB = new Element('fieldset', { id:'fst-DOB'});
		fstDOB.insert(this.elements.hdrStep2)
			.insert(this.elements.subHdrStep2)
			.insert(this.elements.dobList)
			.insert(this.elements.lnkProceed);
		this.elements.form.insert(fstDOB);
		
		this.elements.form.insert(new Element('div', {'class': 'clear'}));
		this.elements.form.insert(new Element('input', {'type': 'hidden', 'value': window.location.href, 'name': 'urlreferer', 'id': 'urlreferer'}));
		
		this.elements.regionList.observe('click', this.__regionListClick.bindAsEventListener(this));
		this.elements.lnkProceed.observe('click', this.__proceedClick.bindAsEventListener(this));
		
	},
	// populates the agegate copy from the copyData with the given language code (e.g. 'en-us')
	regionalizeForm: function(code){
		/*		
		var oRegion = {
			"hp1_AgeGate.Step1":"Step 01",
			"hp1_AgeGate.Step2":"Step 02",
			"hp1_AgeGate.SelectRegion":"PLEASE SELECT YOUR REGION.",
			"hp1_AgeGate.AgePrompt":"ENTER YOUR DATE OF BIRTH:",
			"hp1_AgeGate.DateFormat":"MDY",
			"hp1_AgeGate.DatePart1":"Month",
			"hp1_AgeGate.DatePart2":"Day",
			"hp1_AgeGate.DatePart3":"Year",
			"hp1_AgeGate.ProceedButton":"PROCEED"
		};
		*/
		var oRegion = this.copyData[code];
	
		this.elements.hdrStep1.update(oRegion['hp1_AgeGate.Step1']);
		this.elements.subHdrStep1.update(oRegion['hp1_AgeGate.SelectRegion']);
	
		this.elements.hdrStep2.update(oRegion['hp1_AgeGate.Step2']);
		this.elements.subHdrStep2.update(oRegion['hp1_AgeGate.AgePrompt']);

		this.populateDOBList(oRegion['hp1_AgeGate.DateFormat'].toArray(), [oRegion['hp1_AgeGate.DatePart1'], oRegion['hp1_AgeGate.DatePart2'], oRegion['hp1_AgeGate.DatePart3']]);
		this.elements.lnkProceed.update(oRegion['hp1_AgeGate.ProceedButton']);
		Cufon.refresh();
	},
	
	// Listens for selection of a new region from region list and regionalizes the form with selection
	__regionListClick: function(e){
		var radRegions = this.elements.regionList.select('input[type=radio]');
		radRegions.each(function(elRad){
			if(elRad.checked == true){
				elRad.up('li').addClassName('selected');
				this.regionalizeForm(elRad.value);
			} else{
				elRad.up('li').removeClassName('selected');
			}
		}.bind(this));
	},
	// Listens to the proceed button and posts the form
	__proceedClick: function(e){
		e.stop();
		var unSelected = this.elements.dobList.select('select').reject(function(elSelect){
			return elSelect.selectedIndex > 0;
		});
		if(unSelected.size() == 0){
			this.postForm();
		}
	},
	
	// Populates the the region list with radio buttons and labels. 
	populateRegionList: function(aRegions){
		/*
		// Sample JSON
		[
			{"Description":"English - United States","NativeDescription":"English - United States","Code":"en-us"},
			{"Description":"French - France","NativeDescription":"FranÃ§ais - France","Code":"fr-fr"},
			{"Description":"German - Germany","NativeDescription":"Deutsch - Deutschland","Code":"de-de"},
			{"Description":"Spanish - Latin America","NativeDescription":"EspaÃ±ol - AmÃ©rica Latina","Code":"es-mx"},
			{"Description":"Japanese - Japan","NativeDescription":"æ—¥æœ¬èªž-æ—¥æœ¬","Code":"ja-jp"}
		]
		// Sample markup for a region
		<li>
			<label for='rad_en-US'>United States</label>
			<input type='radio' name='culturecode' id='rad_en-US' value='en-US' />
		</li>
		*/
		this.elements.regionList.update();
		$A(aRegions).each(function(region){
			var elLi = new Element('li');
			var radID = 'rad_' + region.Code;
			
			var elRad = new Element('input', {'type':'radio', 'name':'culturecode', 'id':radID, 'value': region.Code});

			if(region.Code == this.userCode){
				elLi.addClassName('selected');
				elRad.checked = true;
			} else{
				elRad.checked = false;
			}
			elLi.insert(elRad);
			elLi.insert(new Element('label', {'for': radID}).update(region.NativeDescription));
			this.elements.regionList.insert(elLi);
		}.bind(this));
	},
	
	// populates the date of birth list with Month, Date, and Year selects.
	populateDOBList: function(aFormatOrder, aPrompts){
		this.elements.dobList.update();
		// loop through the format order ['M','D','Y'] and create markup
		for(var i=0; i < aFormatOrder.length; i++){
			/*
				<li>
					<label for='dobM'>-Month-</label>
					<select id='dobM' name='dobM'></select>
				</li>
			*/		
			var elLi = new Element('li', {'class': aFormatOrder[i]});
			var selectName = aFormatOrder[i].toLowerCase();
			var elSelect = new Element('select', {'id': selectName, 'name': selectName});
			elLi.insert(new Element('label', {'for': selectName}).update(aPrompts[i]));
			
			elSelect.insert(new Element('option', {'value': ''}).update('-' + aPrompts[i] + '-'));
			
			switch(aFormatOrder[i]){
				case "M":
					for(var m = 1; m <= 12; m++){
						elSelect.insert(new Element('option', {'value': m}).update(m.toPaddedString(2)));
					}
					break;
				case "D":
					for(var d = 1; d <= 31; d++){
						elSelect.insert(new Element('option', {'value': d}).update(d.toPaddedString(2)));
					}				
					break;
				case "Y":
					var now = new Date();
					var currentYr = now.getFullYear();
					for(var y = currentYr; y >= this.options.startYear; y--){
						elSelect.insert(new Element('option', {'value': y}).update(y));
					}
					break;
			}
			elLi.insert(elSelect);
			this.elements.dobList.insert(elLi);
		}
	},
	// Posts the form (set destination in this.options.formAction)
	postForm: function(){
		this.elements.form.submit();
	},
	
	// Get's the region list data and copy data as JSON data from ajax calls.
	getJSONData: function(){
		// Request the region list Data
		new Ajax.Request(rootVirtual + 'Validation/Culture', {
			method: 'get',
			onSuccess: this.xhrListDataSuccess.bind(this),
			onFailure: this.xhrFailureCallback.bind(this)
		});
		// Request the localized copy data.
		new Ajax.Request(rootVirtual + 'Validation/GetCultureContents', {
			method: 'get',
			onSuccess: this.xhrCopyDataSuccess.bind(this),
			onFailure: this.xhrFailureCallback.bind(this)
		});			
	},
	
	xhrListDataSuccess: function(transport){
		this.listData = transport.responseJSON;
		this.populateRegionList(this.listData);
	},
	
	xhrCopyDataSuccess: function(transport){
		this.copyData = transport.responseJSON;
		this.regionalizeForm(this.userCode);
		// Now that we some copy, show the form.
		this.show();
	},
	
	xhrFailureCallback: function(transport){
		console.warn('Something went wrong with the xhr request.', transport.status, transport.statusText, transport);
	}	
};
// Used on region select page to manage 'selecting' a region and posting the form.
var RegionSelect = {
	init: function(elForm, elRegionList, elLnkProceed, options){
		this.elForm = $(elForm);
		this.elRegionList = $(elRegionList);
		this.elLnkProceed = $(elLnkProceed);
		this.options = Object.extend({
			langCodeCookieName: 'LanguageInfo'			
		}, options || {});	
		
		var langInfo = Cookie.get(this.options.langCodeCookieName);
		if(langInfo){
			elUserRegion = elRegionList.select('input[value=' + langInfo.toLowerCase() + ']').first();
			elUserRegion.checked = true;
			elUserRegion.up('li').addClassName('selected');
		}

		this.elRegionList.observe('click', this.__regionListClick.bindAsEventListener(this));
		this.elLnkProceed.observe('click', this.postForm.bind(this));	
		
	},
	// Listens for selection of a new region from region list and sets the selected class
	__regionListClick: function(e){
		var el = e.element();
		if(el.nodeName == 'UL'){
			return;
		} else{
			el = e.findElement('li');
		}
		var selectedCode = el.down('input[type=radio]').value;
		var radRegions = this.elRegionList.select('input[type=radio]');
		radRegions.each(function(elRad){
			if(elRad.value == selectedCode){
				elRad.up('li').addClassName('selected');
				elRad.checked = true;
			} else{
				elRad.up('li').removeClassName('selected');
				elRad.checked = false;
			}
		}.bind(this));
	},
	
	postForm: function(){
		this.elForm.submit();
	}
};