/*****************************************************************************************
* FILE:      PDconfigs.js
* SYSTEM:    JSI
* PUBLISHER: WeddingDetailsTPS1 SID:218 ACCOUNT:WD1
* NOTES:     Legacy site uses default PDcoreg.js and has no OuterContainer  
* HISTORY:
*    2009-03-30 JA: Added options for RandomPages & DebugConsole
*    2009-04-21 JA: Added OffersPreselected
*    2011-01-20 JA: Migrated to v1.29
*    2012-02-01 JA: Updated AdQ Loader to v1.3 w/v1.29.1.0010
***********************************************************************************************************************/

var oAdQuireLoader = new PD_AdQuireLoader(true);
oAdQuireLoader.UrlAdQuire    = '//www.pdapi.com/cs/JSI/v1/default/PDcoreg.v1.291.0010.min.js';
oAdQuireLoader.enableGeoip   = true;
oAdQuireLoader.init();


function PD_getConfigs(){
	// do not delete any of these configs, just change their settings instead!
	var oCfg = {};
	oCfg.general    = {};
	oCfg.connection = {};
	oCfg.errors     = {};
	oCfg.style      = {};
	
	//oCfg.general contains general application configuration settings
	oCfg.general.NumberOfOffersToDisplay = 5;    // Number of offers on each page
	oCfg.general.NumberOfPagesToDisplay  = 99;    // Total number of pages
	oCfg.general.OffersPreselected       = false; // Offer(s) must be preselected
	oCfg.general.RedirectUrl             = PDregData.exit_url ? PDregData.exit_url : false;
	
	oCfg.general.DisplayOfferImages      = true; // display coreg images if true
	oCfg.general.TestMode                = false; // establishes a session in test mode if true
	
	//oCfg.connection contains API connection and publisher authentication settings
	oCfg.connection.Pin     = "PkfeHJty6Njh";   // Publisher's pin
	oCfg.connection.PubCode = "WD1";        // Publisher's pub code
	
	//oCfg.errors contains error and debug settings
	oCfg.errors.DebugMode      = 0;     // Testing purposes: 0 = off; 1,2,3 = low,med,high
	oCfg.errors.TerminateSuccessMessage = "Thanks for participating in these offers!"; //js alert message on successful termination - leave blank to display nothing
	oCfg.errors.HeadlineMessageRCV      = "Please complete the information below to receive this offer"; //message at top of RCV area
	oCfg.errors.ValidationErrorMessage  = "Please correct the required fields in red and try again"; //error message at top of RCV area
	
	//oCfg.style contains stylesheet URL and some display configurations that can't be handled by CSS
	oCfg.style.StylesheetURL = ""; // URL of stylesheet
	oCfg.style.TwoColumnSurvey    = false;    // Display survey as 2 columns if true - requires an appropriate stylesheet
	oCfg.style.TwoColumnRCV       = false;    // Display RCV as 2 columns if true - requires an appropriate stylesheet
	
	/* ****** START Publisher specific code ******** */
	
	
	/* ****** END Publisher specific code ******** */
	oCfg.general.onConfig = function(){
		oAdQuireLoader.addTimepoint('PD_getConfigs',false, 'L.init');
	}
	
	return oCfg;
}



/** AdQuire Loader **/
// 1.2 2011-12-20 Changed the way GeoIP is loaded to allow blocking
// 1.3 2012-01-24 Always loading GeoIP regardless of zipcode and usage of cookies
function PD_AdQuireLoader(bNoInit, bEnableGeoip, bEnableGA, sUrlAdQuire, sUrlStylesheet){
	var T = this;
	
	this.version = 1.3;
	this.release = '2012-01-24';

	this.disableCache   = false;
	
	this.UrlAdQuire     = sUrlAdQuire    === undefined ? '//www.pdapi.com/cs/JSI/v1/default/PDcoreg.v1.291.js'       : sUrlAdQuire;
	this.UrlStylesheet  = sUrlStylesheet === undefined ? '//www.pdapi.com/cs/JSI/v1/default/styles/PDstyle-standard.css' : sUrlStylesheet;
	this.UrlJQuery      = '//www.pdstatic.com/scripts_js/jquery/jquery.js';
	this.UrlGA          = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.") + "google-analytics.com/ga.js" ;
	this.UrlGeoIP       = '//www.pdapi.com/cs/tmp/geoip.cfm?whichRequest=lookupGeoip';
	
	this.LoadingImg     = '<div style="height: 70px; border: 1px solid #AAAAAA; background: #FFFFFF url(//img.pdstatic.com/adquire/loading-anim-130x60.gif) no-repeat center"></div>';
	
	this.catchUnhandled = false;
	
	this.enableGeoip    = bEnableGeoip ? true : false;
	this.enableGA       = bEnableGA    ? true : false;
	this.enableGeoipTest= false;
	
	this.GeoipData      = {};
	this.GeoipLoading   = false;
	
	this.Variations     = {};
	this.Variations.selected = true;
	this.Variations.Options  = {};
	
	this.Timing = {};
	this.Timing.Trace = [];
	this.Timing.Steps = {};
	this.Utils  = {};
	
	
	if (typeof(PDregData) != 'object'){
		PDregData = {};
	}
	
	T.init = function(){
		window.objGlobal = {};
		window.objGlobal.jQueryLoaded = 100;
		window.PD_catchUnhandled      = T.catchUnhandled;
		
		T.addTimepoint('L.init');

		if (typeof(PDregData) != 'object'){
			PDregData = {};
		}
		
		// Select variation if enabled
		if (T.Variations.selected === true){
			var aOptions = [];
			for (var i in T.Variations.Options) if (T.Variations.Options.hasOwnProperty(i)){
				if (!T.Variations.Options[i].disabled){
					aOptions.push(i);
				}
			}
			T.Variations.selected = aOptions.length > 0 ? aOptions[(Math.floor(Math.random()*100000) % aOptions.length)] : false;
		}
		
		// Apply variations to the loader
		if (T.Variations.selected !== false){
			var oVariation = T.Variations.Options[T.Variations.selected];
			for (var i in oVariation) if (oVariation.hasOwnProperty(i)){
				if (i != 'Configs' && typeof(T[i]) != 'undefined'){
					T[i] = oVariation[i];
				}
			}
		}
		
		var oEl = document.getElementById('PD_OuterContainer');
		if (oEl){
			oEl.innerHTML += T.LoadingImg;
		}
		else{
			// Legacy implementation without container
			document.write('<div id="PD_OuterContainer">'+T.LoadingImg+'</div>');
			T.Utils.log("Note: This AdQuire implementation lacks a PD_OuterContainer");
		}
		
		// Load GeoIP
		if (T.enableGeoip && !document.getElementById('PD_Script_GeoIP')){
			var sGeoIP = T.Utils.getCookie('PD_GeoIP');
			var aParts = sGeoIP ? sGeoIP.split(',') : [];
			if (sGeoIP && aParts.length == 3){
				T.GeoipData.countrycode = aParts[0];
				T.GeoipData.state       = aParts[1];
				T.GeoipData.zipcode     = aParts[2];
				T.GeoipData.status      = 'COOKIE';
				// Set GeoIP data
				PDregData.GeoipData = T.GeoipData;
				
				T.addTimepoint('L.setGeoipInfo', T.GeoipData);
			}
			else{
				T.getGeoipInfo();
			}
			
		}

		// Load jQuery
		if (T.UrlJQuery && typeof(jQuery) == 'undefined' && !document.getElementById('PD_Script_jQuery')){
			T.loadScript(T.UrlJQuery, T.disableCache, 'PD_Script_jQuery');
		}

		// Load AdQuire
		if (T.UrlAdQuire && typeof(PD_initialize) != 'function' && !document.getElementById('PD_Script_AdQuire')){
			T.loadScript(T.UrlAdQuire, T.disableCache, 'PD_Script_AdQuire');
		}
		
		// Load stylesheet
		if (T.UrlStylesheet){
			T.loadStylesheets(T.UrlStylesheet);
		}
		
		// Load Google Analytics
		if (T.enableGA && typeof(_gat) == 'undefined' && !document.getElementById('PD_Script_GA')){
			T.loadScript(T.UrlGA, T.disableCache, 'PD_Script_GA');
		}

	}
	
	T.applyVariationConfigs = function(oCfg){
		// Apply variations to the configs. this must be passed the config object (byref)
		if (T.Variations.selected !== false){
			var oVariation = T.Variations.Options[T.Variations.selected];
			if (typeof(oVariation.Configs) == 'object'){
				for (var i in oVariation.Configs) if (oVariation.Configs.hasOwnProperty(i)){
					if (typeof(oVariation.Configs[i]) == 'object'){
						for (var j in oVariation.Configs[i]) if (oVariation.Configs[i].hasOwnProperty(j)){
							oCfg[i][j] = oVariation.Configs[i][j];
						}
					}
					else{
						oCfg[i] = oVariation.Configs[i];
					}
				}
			}
			
			// Set the SubMid accordingly
			oCfg.connection.SubMid = oCfg.connection.SubMid ? T.Variations.selected +': '+ oCfg.connection.SubMid : T.Variations.selected;
		}
	}
	
	
	T.getGeoipInfo = function(){
		var nCount = 0;
		while (typeof(window['PD_dynamic_'+nCount]) != 'undefined'){
			nCount++;
		}
		window['PD_dynamic_'+nCount] = T.setGeoipInfo;
		T.loadScript(T.UrlGeoIP+'&callbackFunction=PD_dynamic_'+nCount+(T.enableGeoipTest ? '&test=1' : ''), false, 'PD_Script_GeoIP');
		T.addTimepoint('L.getGeoipInfo');
		return true;
	}
	
	T.setGeoipInfo = function(oData){
		if (!oData){
			return false;
		}
		if (oData.error || oData.warning){
			T.addTimepoint('L.setGeoipInfo', oData.error || oData.warning);
			T.Utils.log('L.setGeoipInfo(ERROR)', oData);
			return false;
		}
		
		T.GeoipData = oData;
		T.GeoipData.state   = (oData.region != 'null')     ? oData.region     : '';
		T.GeoipData.zipcode = (oData.postalcode != 'null') ? oData.postalcode : '';
		T.GeoipData.status  = T.Timing.Steps.hasOwnProperty('PD_getConfigs') ? 'LATE' : 'OK';
		
		T.Utils.setCookie('PD_GeoIP', T.GeoipData.countrycode+','+T.GeoipData.state+','+T.GeoipData.zipcode, {expires:60, path:'/'});
		
		// Set GeoIP data
		PDregData.GeoipData = T.GeoipData;
		
		T.addTimepoint('L.setGeoipInfo', T.GeoipData, 'L.getGeoipInfo');
		T.Utils.log('L.setGeoipInfo('+T.GeoipData.status+')', oData);
	}
	
	T.loadScript = function (sUrl, bNoCache, sId){
		// Append a unique timestamp to force script load and avoid cache
		if (bNoCache){
			sUrl += (sUrl.indexOf('?') === false ? "?" : "&") + "_=" + (new Date().getTime());
		}
		// Create a new script element & Set the properties
		var oScript = document.createElement("script");
		oScript.setAttribute("type",  "text/javascript");
		//oScript.setAttribute("defer", "defer");
		oScript.setAttribute("src",   sUrl);
		if (sId){
			oScript.setAttribute("id",   sId);
		}
		// Launch the request
		document.getElementsByTagName("head").item(0).appendChild(oScript);	
		T.addTimepoint('L.loadScript', sId);
		return true;
	}
	
	T.loadStylesheets = function(aURLs){
		if (!aURLs){
			return false;
		}
		if (typeof(aURLs) == 'object' && aURLs.length > 0){
			for (var n = aURLs.length - 1; n >= 0; n--){
				T.loadStylesheet(aURLs[n]);
			}
		}
		else if(typeof(aURLs) == 'string' && aURLs){
			T.loadStylesheet(aURLs);
		}
	}

	T.loadStylesheet = function(sURL){
		if (!sURL){
			return false;
		}
		//declare local variables
		var oNode, oHead;
		
		//create a new link element pointing at the url that was passed in as an argument
		oNode = document.createElement("link");
		oNode.setAttribute("rel", "stylesheet");
		oNode.setAttribute("type", "text/css");
		oNode.setAttribute("href", sURL);
		
		//get the document's head and the head's first child element
		oHead  = document.getElementsByTagName("head")[0];
		
		//pre-pend the link into the document's head before the first child element
		oHead.insertBefore(oNode, oHead.childNodes[0]);
	}
	
	T.addTimepoint = function(sStep, sDesc, sReference){
		var nNow  = (new Date().getTime());
		var oInfo = {time: nNow, step:sStep, desc: sDesc};
		
		if (sReference && T.Timing.Steps.hasOwnProperty(sReference)){
			oInfo.elapsed = nNow - T.Timing.Steps[sReference].time;
		}
		T.Timing.Trace.push(oInfo);
		T.Timing.Steps[sStep] = oInfo;
	}

	T.Utils.log = function(){
		if (typeof(console) == 'object'){
			for (var n = 0; n < arguments.length; n++){
				console.log(arguments[n]);
			}
		}
	}
	
	T.Utils.setCookie = function(name, value, options){
		options = options || {};
		if (typeof value == 'undefined' || value === null){
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			}
			else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	};
	
	T.Utils.getCookie = function(sName){
		var sVal = null;
		if (document.cookie && document.cookie != '') {
			var aCookies = document.cookie.split(';'), sPrefix = sName + '=', nLen = sName.length + 1;
			for (var i = aCookies.length -1; i >= 0; i--) {
				var sCookie = aCookies[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
				// Does this cookie string begin with the name we want?
				if (sCookie.substring(0, nLen) == sPrefix){
					sVal = decodeURIComponent(sCookie.substring(nLen));
					break;
				}
			}
		}
		return sVal;
	};
	
	if (!bNoInit){
		this.init();
	}
}
