 


















if(typeof tsSiteId != 'undefined' && tsSiteId == '59') {	
	var doWWiKeywords = true;
}

/** 
 *assign indexOf to the array object if using IE <9
 */
 
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i < this.length; i++) {
            if(this[i]==obj) {
                return i;
            }
        }
        return -1;
    }
}
window.TWC = window.TWC || {};
TWC.Events = TWC.Events || {};


//SET up local storage for hard Declarations
var appsToHardDeclarations = {
		"achesandpains":"aches",
		"airquality":"airq",
		"allergies":"algy",
		"boatandbeach":"bnb",
		"businesstravel":"btrav",
		"climate":"clim",
		"coldandflu":"cold",
		"driving":"driv",
		"events":"undc",
		"fishing":"fish",
		"fitness":"fit",
		"flightstatus":"flt",
		"garden":"gdn",
		"golf":"golf",
		"health":"hlth",
		"home":"home",
		"homeimp":"himp",
		"homeplanner":"hmpl",
		"lawn":"lawn",
		"livingsmart":"live",
		"marine":"mar",
		"momsplanner":"mp",
		"news":"news",
		"outdooractivity":"odact",
		"outdoors":"outd",
		"petcare":"pcare",
		"pets":"pets",
		"pollen":"plln",
		"schoolday":"schd",
		"ski":"ski",
		"sportingevents":"undc",
		"sports":"spts",
		"sunsafety":"sun",
		"traffic":"traff",
		"travel":"trvl",
		"vacationplanner":"vac",
		"weddings":"wed",
//		"undeclared":"undc",
		"flight-status":"flt",
        "traffic":"traff",
        "fitness":"fit",
        "golf":"golf",
        "home-imp":"himp",
        "pet-care":"pcare",
        "moms-planner":"mp"
       };

// Create global setEvent function that creates a Deferred Object if an only if it is not already there.
TWC.Events.setEvent = function(eventname) {
	var _parent = TWC.Events;
	// check for dots in the string
	var _dot = eventname.split(/\./);
	// if you have a dot in your string
	if (_dot.length > 1) {
		// grab the first value as your new parent
		var n = _dot.shift();
		// check if your new parent exists
		_parent[n] = _parent[n] || {};
		var newObj = _parent[n];
		for(var i = 0,l = _dot.length - 1;i<l;i++){
			newObj[_dot[i]] = newObj[_dot[i]] || {};
			newObj = newObj[_dot[i]];
		}
		newObj[_dot[_dot.length-1]] = newObj[_dot[_dot.length-1]] || jQuery.Deferred();
	} else {
		// return right away, quick match
		_parent[eventname] = _parent[eventname] || jQuery.Deferred();
	}
}
TWC.initpco = function($,pcoObject,pageId,mode,siteId,currlocId){

	/**
	 * Define placeholders for service call deferred events 
	 */
	var wxLocDfrdEvent,adDfrdEvent,piqDfrEvent;
	
	
	/**
	 * Assign server side pcoObject if it exists
	 */ 
	var PCO = pcoObject || {}, locale_str = (TWC && TWC.Titan && TWC.Titan.locale) || "en_US" || "en_US", locale_lang = locale_str.split("_")[0];
	
	
	//Set the adKeywordsReady event
	TWC.Events.setEvent("adKeywordsReady");

	// Create  event if not already present
	TWC.Events.setEvent("locations_changed");
	TWC.Events.setEvent("locations_pagelet_ready");
		
	// Create pcoReady event if not already present
	TWC.Events.setEvent("pcoReady");

	// Create Optimizely Pagelet Load Event if not already present
	TWC.Events.setEvent("pageletLoad");
	
	// Create Optimizely Custom Interaction Event if not already present
	TWC.Events.setEvent("customInteraction");

		
	// Create pcoRefresh event if not already present
	TWC.Events.setEvent("pcoRefresh");
				
	TWC.Events.setEvent("userDeviceevent");
	
	TWC.Events.setEvent("autodetectLocEvent");
	
	TWC.Events.setEvent("autodetectLocFailEvent");
	 
	/**
	 * Add a page property to PCO if it doesn't exist
	 * Needed for static pages'
	 */
	 
	if($.isEmptyObject(pcoObject) && pageId){
		PCO.page = PCO.page || {};
		PCO.page.pageId = PCO.page.pageId || pageId;
		PCO.page.locale = locale_str;
		PCO.page.lang= locale_lang;
	}
	
	// For Titan. If locale does not match the page locale, overwrite it.
	if(PCO.page && PCO.page.locale && PCO.page.locale !== locale_str) {
		PCO.page.locale = locale_str;
		PCO.page.lang	= locale_lang;
	}
    //alert(PCO.page.locale);

	/**
	 *  If the page is an Intellicast, estreet, static or blue marble page
	 *  the pcoObject will be null. For this case make two service calls 
	 *  to populate a minimal pco with the ad object and weather object
	 */
	
	var pageResponsive="true";
	if(null === pcoObject || !pcoObject.currloc || $.isEmptyObject(pcoObject.currloc) || (pageResponsive=="true")){
		
		// if pcoObject exists, but there is no pcoObject.currloc
		// check localstoragefor preferredLocation, if it exists 
		// make the /service/wx.
		
		// If there is no pcoObject, but there is a currlocId 
		// use it to call /service/wx and add location obj
		// as currloc and wx object to pco.
		
		// Finally if there is no pcoObject and no currlocId
		// check localstoragefor preferredLocation, if it exists 
		// make the /service/wx call.
		
		var locid = null;
		if(currlocId){
			locid = currlocId;
		}else{
			var user = $.jStorage.get("user");
			var preferredLoc =(user && user.preferredLocation) ? user.preferredLocation : undefined;;
            if (preferredLoc)  {
                    var locationId = preferredLoc.locid;
                    if (!locationId)   locationId = preferredLoc.zip;
                      
                    if (locationId && locationId.indexOf(":") != -1) { //Sometimes we have loctype appended
                        locationId = locationId.split(":")[0]; 
                    }    
                    locid=locationId  + ":" + (preferredLoc.type || preferredLoc.loctype)  + ":" + (preferredLoc.countryCode || preferredLoc.country);
             }
			 
		}
		
		
		var sdynhost = "d.imwx.com" || "d.imwx.com";
		
		if(locid){
			// Request wx data and loc data
			wxLocDfrdEvent = $.ajax({
				url: ["http://",sdynhost,"/services/wx/",locid].join(""),
				dataType: "jsonp",
				type:"GET",
				success: function(data) {
					PCO.wx = data.wx;
					PCO.currloc = data.loc;
				}
			});
		}
		
		if (typeof(pageId)=="undefined"){
			pageId=PCO.page.pageId;
		}
		
		if (typeof(siteId)=="undefined"){
			siteId="53";
		}
		if (typeof(mode)=="undefined"){
			mode="default";
		}
		
		var initial_orientation;
		var isMobileSite;
			
	
		if(window.innerwidth > window.innerheight) { initial_orientation = "Landscape" ;}
		else initial_orientation = "Portrait";
		
		if(pageId && siteId && !pcoObject || pageResponsive == "true"){
		 	var newmode=mode;
			if (pageResponsive=="true"){
				var viewportWidth  = $(window).width();
				if (viewportWidth >=320 && viewportWidth <=767){
					siteId="59";
					newmode=mode+"_"+siteId;
					isMobileSite="true";
					window.A21 = window.A21 || {};
					A21.googleLib = "gpt_mobile.js";
					A21.isMobileSite=isMobileSite;
				}else if (viewportWidth >=768 && viewportWidth <=1024){
					if (initial_orientation=="Portrait"){
							siteId="121";
					}
					else{
							siteId="122";
					}
					newmode=mode+"_"+siteId;
				}
			}

			// 2014-07-22 - Cord Hamrick - per Jira Ticket BKB-453
			TWC.Events.setEvent("pcoServicesAdCallReady");
			
			// If there is a pageId and siteId and there is
			// not already a pcoObject, request ad data
			adDfrdEvent = $.ajax({
				url: ["http://",sdynhost,"/services/ad/",pageId].join(""),
				dataType: "jsonp",
				data:{
					mode:newmode || "default",
					siteId:siteId || "53" 
				},
				type:"GET",
				success: function(data) {
					if(data){
						PCO.ad = data;
						TWC.Events.pcoServicesAdCallReady.resolve(); // 2014-07-22 - Cord Hamrick - per Jira Ticket BKB-453
					}
				}
			});
			
		}
		
	}
	
	/***
	 **
	 ** Private data and methods
	 **/
	 
	
	
	var undeclaredDec = "undc";

	var getNodeAndKeyFromString = function(nod,pn){
		// fail instantly if node value is not a string
		if (typeof nod !== "string") {
			return [undefined,undefined];
		}
		// start with the PCO as your parent unless explicitly told otherwise
		var _parent = pn || PCO;
		// check for dots in the string
		var _dot = nod.split(/\./);
		// if you have a dot in your string
		if (_dot.length > 1) {
			// grab the first value as your new parent
			var n = _dot.shift();
			// if your new parent exists
			if (_parent[n]) {
				// recurse
				return getNodeAndKeyFromString(_dot.join('.'),_parent[n]);
			} else {
				// fail quickly
				return [undefined,undefined];
			}
		} else {
			// return right away, quick match
			return [_parent,nod];
		}
	};
	
	var getVal = function(nod){
		// get node and key
		var nkArray = getNodeAndKeyFromString(nod);
		// if you have a valid parent node, return the value from the parent node's key
		if (nkArray[0]) {
			return nkArray[0][nkArray[1]];
		// if you don't have a valid parent node, return js type undefined (falsy)
		} else {
			return undefined;
		}
	};
	var setVal = function(nod,val){
		// get node and key
		var nkArray = getNodeAndKeyFromString(nod);
		// if you have a valid parent node, return the value from the parent node's key
		if (nkArray[0]) {
			return (nkArray[0][nkArray[1]] = val);
		// if you don't have a valid parent node, return js type undefined (falsy)
		} else {
			return undefined;
		}
	};
	
	var persistValue= function( key, val, ttl){
					
		ttl = ttl || 0;
		if(!key) {
			
			return;
		}
		$.jStorage.set(key, val);
		if(ttl>0) {
		    $.jStorage.setTTL(key, ttl);
		}
	};
	
	var getPersistedValue=function(key){
		return $.jStorage.get(key);
	};

	var removePersistedValue=function(key){
		return  $.jStorage.deleteKey(key);
	};
	
	var isPersistedKey=function(key){
		if (getPersistedValue(key)=="undefined" || getPersistedValue(key)==null){
			return false;
		}
		return true;
	};
	
	var initAllLocations=function(loc){
		prvlgd.set("user.savedLocations",loc.savedLocations);
		prvlgd.set("user.recentSearchLocations",loc.recentSearchLocations);
	};
	
	var setSavedLocations=function(loc){
		var savedLocs=prvlgd.get("user.savedLocations") || [],
			alreadySaved = false;
		for(var i = 0,l=savedLocs.length; i < l; i++) {
			if(isLocEqual(loc,savedLocs[i])) {
				alreadySaved = true;
				break;
			}
		}
		if(!alreadySaved){
			savedLocs.unshift(loc);
			// Limit savedLocs array to 10
			savedLocs = savedLocs.slice(0,10);
		}
		return savedLocs;
	};
	
	
	var modifySavedLocations = function(indx,loc){
		var savedLocs = prvlgd.get("user.savedLocations");
		if(null != savedLocs && savedLocs[indx]){
			if(loc){
				savedLocs.splice(indx,1,loc);
			}else{
				savedLocs.splice(indx,1);
			}
		}
		return savedLocs;
	};
	
	var setPreferredLocation=function(){
		var savedLocs = prvlgd.get("user.savedLocations");
		var recentSearchLocs=prvlgd.get("user.recentSearchLocations");
		if(savedLocs && savedLocs.length>0) {
			prvlgd.setUser("preferredLocation", savedLocs[0]);
		} else if (recentSearchLocs && recentSearchLocs.length>0) {
			prvlgd.setUser("preferredLocation", recentSearchLocs[0]);
			
		} else if (savedLocs.length==0 && recentSearchLocs.length==0) {
			prvlgd.setUser("preferredLocation", "");
		}
		
	};
	
	var setRecentSearchLocations=function(loc){
		var recentSearchLocs=prvlgd.get("user.recentSearchLocations") || [],
			alreadySaved = false,
			rsLength = recentSearchLocs.length;
		
		if(rsLength !== 0){
			for(var i = 0; i < rsLength; i++) {
				if(isLocEqual(loc,recentSearchLocs[i])){
					alreadySaved = true;
					recentSearchLocs.splice(i,1);
					recentSearchLocs.unshift(loc);
					break;
				}
			}
		}
		
		if(!alreadySaved) {
			recentSearchLocs.unshift(loc);
			// Limit saved recentSearchLocations array to 10
			recentSearchLocs = recentSearchLocs.slice(0,10)
		}
		
		return recentSearchLocs;
	};
	
	var modifyRecentSearchLocations = function(indx,loc){
		var rsLocs = prvlgd.get("user.recentSearchLocations");
		if(rsLocs && rsLocs[indx]){
			if(loc){
				rsLocs.splice(indx,1,loc);
			}else{
				rsLocs.splice(indx,1);
			}
		}
		return rsLocs;
	};

	//convenience methods to access core declarations functions
	
	var setSoftDeclaration=function(val,oper){
		if (oper && oper === 'd')
		{
			prvlgd.removeSoftDeclaration(val);
		}
		else
		{
			prvlgd.addSoftDeclaration(val);
			prvlgd.removeSuppressedDeclaration(val);
		}
	
	};
	
	var setHardDeclaration=function(val,oper){
		if (val && val.length <=0) return;
		if (val == 'Undeclared' || val == 'null') return;

		if (oper && oper === 'd')
		{
			prvlgd.removeHardDeclaration(val);
			prvlgd.removeSoftDeclaration(val);			
		}
		else
		{
			prvlgd.addHardDeclaration(val);
			prvlgd.removeSuppressedDeclaration(val);
		}
		
	};
	
	var setSuppressedDeclaration=function(val,oper){
		if (oper && oper ==='d')
		{
			prvlgd.removeSuppressedDeclaration(val);
		}
		else
		{
			prvlgd.addSuppressedDeclaration(val);
			prvlgd.removeHardDeclaration(val);
			prvlgd.removeSoftDeclaration(val);
		}
	};
	
	var isLocEqual = function(loc1, loc2){
		var isEqual = (loc1 && loc2 && !loc1.lon || !loc1.lat) ? (loc1 && loc2 && loc1.locid == loc2.locid && loc1.loctype == loc2.loctype) : loc1 && loc2 && loc1.locid == loc2.locid && loc1.loctype == loc2.loctype && loc1.lat == loc2.lat && loc1.lon == loc2.lon;
		return isEqual;
	};

	

	var manageSuppressedDeclarations = function(){
		if (!prvlgd) return null;
		{
			var suppressdecl=prvlgd.getSuppressedDeclarations();
			var hasChanged = false;
			for(var key in suppressdecl) 
	        {
		        var expDate = new Date(suppressdecl[key]);
		        var now = new Date();
		        if ( now.getTime() - expDate.getTime() > 90*24*60*60*1000)
		        {
		        	delete suppressdecl[key];
		        	hasChanged = true;
		        }
				
	        }
			//save new entryset			
			if(hasChanged == true)prvlgd.set("user.suppressedDeclarations",suppressdecl);
	       
		}
		
	};
	
	var initUserPrefBasedCookies=function(userpref){
		var userPrefExists = typeof(userpref)!="undefined" && null!=userpref;
	   
	    function getUPSlot(slotNo){
			var str="";
			if(userpref.indexOf("%7C")>0) {
				str = userpref.split("%7C")[slotNo];  
			} else {
	     		str = userpref.split("|")[slotNo];
	     	}
	     	str = unescape(str);
	     	str = str.replace(/\+/g," ");
	        str = str.match(/[a-zA-Z0-9]/) ? str : null;
			return str;
	    };
		
		function convertAge(dob) {
			if(dob != null){
		    	dob = dob.replace("+","");
		    	var d = new Date();
		    	var curr_year = d.getFullYear();
		    	return curr_year-dob;
			}else{
				return " ";
		   	}
		};
		
	    function findAgeRange(age) {
	    	if(age == " ")return [""];
	        var ageRange = [];
	        age = parseInt(age, 10);
	        if (isNaN(age)) {
	            return '';
	        }
	        if (age >= 18 && age <= 24) {
	            ageRange.push('1824');
	        }
	        if (age >= 18 && age <= 34) {
	            ageRange.push('1834');
	        }
	        if (age >= 18 && age <= 49) {
	            ageRange.push('1849');
	        }
	        if (age >= 21 && age <= 34) {
	            ageRange.push('2134');
	        }
	        if (age >= 25 && age <= 49) {
	            ageRange.push('2549');
	        }
	        if (age >= 25 && age <= 54) {
	            ageRange.push('2554');
	        }
	        if (age >= 35 && age <= 54) {
	            ageRange.push('3554');
	        }
	        if (age >= 18 && age <= 99) {
	            ageRange.push('18u');
	        }
	        if (age >= 25 && age <= 99) {
	            ageRange.push('25u');
	        }
	        if (age >= 35 && age <= 99) {
	            ageRange.push('35u');
	        }
	        if (age >= 45 && age <= 99) {
	            ageRange.push('45u');
	        }
	        if (age >= 50 && age <= 99) {
	            ageRange.push('50u');
	        }
	        if (age >= 55 && age <= 99) {
	            ageRange.push('55u');
	        }
	        if (age >= 65 && age <= 99) {
	            ageRange.push('65u');
	        }
	        if (age >= 45 && age <= 65) {
	            ageRange.push('bybm');
	        }
	        if (age >= 30 && age <= 44) {
	            ageRange.push('genx');
	        }
	        if (age >= 21 && age <= 29) {
	            ageRange.push('geny');
	        }
	        if(ageRange.length <= 0){
	        	return [];
	        }
	        return ageRange;
	        
	    };
	    
	    function getGender() {
	        //var tempSex = "nl";
	        if(getUPSlot(14) != null) {
	        	tempSex = getUPSlot(14).toLowerCase();
	        	tempSex = tempSex.replace("+", "");
		        if(tempSex==="f" || tempSex==="m") {
		        	return tempSex;
		        } else {
		        	return "nl";
		        }
	        } else {
	        	return "nl";
	        }
	    };      
	    
	    function decrypt(param)
		{
			 var rtnString="";
			 var c = param.split("-");
			 for (i=0;i<c.length;i++)
		     {
		     	rtnString += String.fromCharCode(c[i]);
		     }
		     return rtnString;
		};
		
		
		//if prm present, parse out the birthday and gender
		var birthday="";
		var gender="";
		if (typeof prm != 'undefined' && prm && prm.length > 0)

		{
			var d_birthdayAndGender = decrypt(prm);
			var bgLength = d_birthdayAndGender.length;
			if (bgLength === 11)
			{
				//got both bday and gender
				birthday = d_birthdayAndGender.substring(0,10);
				gender = d_birthdayAndGender.substring(10);
			}
			else if (bgLength ===10 )
			{
				//got just bday
				birthday = d_birthdayAndGender.substring(0,10);
			}
			else if (bgLength === 1)
			{
				//got just gender
				gender = d_birthdayAndGender;
			}
		}
  
	    if (gender && gender.length>0)
	    {
	    	prvlgd.setUser("gender", gender);
	    }
	    else
	    {
	    	var user = prvlgd.get("user");
	    	if (user && userPrefExists && (user['gender'] ==='nl' || user['gender'] ==='' || !user['gender'])) 
	    	{
	    		prvlgd.setUser("gender", getUPSlot(14)?getGender():"nl");
			}
	    }
	    
	    if (birthday && birthday.length>0)
	    {
	    	var tempBd = birthday.split(',').join('/');//safari does not like commas, replace with / to work..RTOY
	    	var b = new Date(tempBd);
	    	var d = new Date();
		   	var curr_year = d.getFullYear();
		    var ageFromUP = curr_year-b.getFullYear();
		    prvlgd.setUser("age", findAgeRange(ageFromUP));
	    }
	    else
	    {
	    	var user = prvlgd.get("user");
	    	if (user && userPrefExists && (user['age'] ==='nl' || user['age'] ==='' || !user['age'])) 
	    	{
	    		prvlgd.setUser("age", getUPSlot(13)?findAgeRange(convertAge(getUPSlot(13))):"nl");
	    	}
	    		
	    }
		
		if (userPrefExists)
		{
	  		prvlgd.setUser("claritas", getUPSlot(33)?"nl":getUPSlot(33));
			prvlgd.setUser("ursId", getUPSlot(2)?getUPSlot(2):"nl");
			prvlgd.setUser("dwInstallId", getUPSlot(25) ? getUPSlot(25).replace(/^\s*/, "").replace(/\s*$/, ""):"");
	    }
	};
	
	var init= function(){
		var that = this;
		//Adding the PCO device node
		var device = $ && $.jStorage ? $.jStorage.get("pcoDeviceNode") : null, locale_str = (TWC && TWC.Titan && TWC.Titan.locale) || "en_US" || "en_US", locale_lang = locale_str.split("_")[0];;
		if(device && !device.error){
			prvlgd.set("device",device);
		}else{
			var url = "http://www.weather.com/diag/ua.js?cb=?";
			$.ajax({url:url,
				dataType: 'jsonp',
				contentType: "application/json",
				success:function(data, textStatus, jqXHR){
					data.error = false;
					$.jStorage.set("pcoDeviceNode",data);
					prvlgd.set("device",data);
				},
				failure:function(){
					var defaults = {
									UserAgent:null,
									"dClass":null,
									"dClassVersion":null,
									"OpenDDRId":null,
									"OpenDDRDevice":null,
									"OpenDDRDisplay":null,
									"OpenDDRJS":null,
									"OpenDDRWireless":null,
									"OpenDDRTablet":null,
									"OpenDDRCrawler":null,
									"OpenDDRDesktop":null,
									"browserId":null,
									"browserName":null,
									"browserVer":null,
									"browserOS":null,
									error : true
									}
					$.jStorage.set("pcoDeviceNode",defaults);
					prvlgd.set("device",defaults);
				},
				context:that
				});
		}		
		
		// IMPORTANT!! - Retrieve localstorage and insert it into pco before doing anything else
		// to pco otherwise the contents of the user object in localstorage will be overwritten by 
		// any prvlgd.setUser method.

		// Check to see if localStorage is present for user
		// If it is, set pco.user and resolve locations_changed
		// otherwise retrieve information from cookies.
		var user= $.jStorage.get("user");
		if (user){ 
			prvlgd.set("user", user);
			TWC.Events.locations_changed.notify();
		}else{
			// Retrieve user declaration information from "a" cookie and delete
			var oldDeclarations = $.cookie("a"),
				oldDeclareArray = [];
			if(null != oldDeclarations){
				oldDeclareArray = oldDeclarations.split("^");
			}else{
				oldDeclarations = $.cookie("UserPreferences");
				if(null != oldDeclarations){
					oldDeclSlots = oldDeclarations.split("|");
					oldDeclareArray = [oldDeclSlots[16]];
				}
			}

			prvlgd.setUser("initDeclarations",oldDeclareArray);
		
			$.cookie("a",null,{path:"/",domain:"weather.com"});
			TWC.Events.locations_changed.notify();
			
		
			
		}
		
        //Set profile Node by reading from cookie
        var profileCookie = $.cookie("uplogin");
        prvlgd.set("profile", {});

		if(typeof(profileCookie) !== 'undefined' && profileCookie !== null && profileCookie.length > 0) {
			var parr = profileCookie.split('^');

			if(typeof parr[0] !== 'undefined' && parr[0] !== null) prvlgd.set("profile.upshostname", parr[0]);
			if(typeof parr[1] !== 'undefined' && parr[1] !== null) prvlgd.set("profile.lastmodified", parr[1]);
			if(typeof parr[2] !== 'undefined' && parr[2] !== null) prvlgd.set("profile.userid", parr[2]);
			if(typeof parr[3] !== 'undefined' && parr[3] !== null) prvlgd.set("profile.username", parr[3]);
		}

		//delete asi cookie
		$.cookie("rsi_segs",null,{path:"/",domain:"weather.com"});
		
		//WxPlatform tracking - setting page.market & page.partner 
		if (prvlgd.get("ad.zone")) {
			var prtnr = prvlgd.get("ad").zone.split("/")[1];
		}
		if (prvlgd.get("metrics.pagename")) {
			var mkt = prvlgd.get("metrics").pagename.split("/")[2];
		}
		if (mkt != "") {
			prvlgd.set("page.market", mkt);
		}
		if (prtnr != "") {
			prvlgd.set("page.affiliate",prtnr);
		}


		// Set flash object
		prvlgd.setUser("flash", $.browser);
		
		//prvlgd.set("page.fv", fv);
		var partnerValueBeforeSet=$.cookie("partner");
		
		if (partnerValueBeforeSet == null || typeof(partnerValueBeforeSet) =="undefined"){
			//MFW Changes for partner cookie
			try {
				if(document && document.referrer && document.referrer.indexOf("//www.facebook.com/") > 0) {
					var params = window.location.search.substring(1);
					var partnerParam = '';
					paramArray = params.split("&");
					for(var i=0, l=paramArray.length; i < l; i++) {
						if(paramArray[i].match(/partner/) && paramArray[i].split("=").length > 1){
							partnerParam = paramArray[i].split("=")[1];
							//alert(partnerParam);
							break;
						}
					}
					
					if(partnerParam.length > 0) {
						$.cookie("partner", partnerParam, {
							domain  : '.weather.com',
							path    : '/'
						});
					}
				}
			}
			catch(err) {
				// Ignore any errors related to partner cookie as this should not stop pco processing.
			}
		}
		
		
		
		var set30MinuteCookie=function(cookieName,cookieChange){
			var cookieVal=$.cookie(cookieName);
			cookieVal=cookieChange?cookieChange:cookieVal;
			if (cookieVal!=null && typeof(cookieVal)!="undefined") {
				var date = new Date();
	 			var minutes = 30;
	 			date.setTime(date.getTime() + (minutes * 60 * 1000));
	 			
				$.cookie(cookieName, cookieVal, {
					domain  : '.weather.com',
					path    : '/',
					expires : date
				});
			}else{
				cookieVal=undefined;
			}
			return cookieVal;
		}
		
		var parStr=set30MinuteCookie("partner");
		var siteStr=set30MinuteCookie("site");
		set30MinuteCookie("partner_url");	
		var ilabelStr=set30MinuteCookie("ilabel");
		var parName = "";

		//search query params for site or par to override current partner  
		var params = window.location.search.substring(1);
		paramArray = params.split("&");
		
		var useTitanPar = false; 
		var isTitanPage = false; 
		if(TWC && TWC.Titan && TWC.Titan.par !== 'undefined')
		{
			isTitanPage = true;

			if (user)
			{
				if (user.parStr === 'undefined' || $.trim(TWC.Titan.par) !== $.trim(user.parStr))
				{
			 		//console.log("setting Titan parstring from "+ user.parStr + " to " + TWC.Titan.par);
					parStr=set30MinuteCookie("partner", TWC.Titan.par);
					useTitanPar = true;

				}	
			}	
		}
		
		for(var i=0, l=paramArray.length; i < l; i++) {
			if(!useTitanPar && !isTitanPage){
				if(paramArray[i].match(/par=/)){ 
					parStr=set30MinuteCookie("partner", paramArray[i].split("=")[1]);
				}
			}	
			if(paramArray[i].match(/par=/)){
				parStr=set30MinuteCookie("partner", paramArray[i].split("=")[1]);
			}
			if(paramArray[i].match(/site=/)){
				siteStr=set30MinuteCookie("site", paramArray[i].split("=")[1]);
			}
			if(paramArray[i].match(/ilabel=/)){
				ilabelStr=set30MinuteCookie("ilabel", paramArray[i].split("=")[1]);
			}
		}
		prvlgd.setUser("parStr",parStr);
		prvlgd.set("page.parStr",parStr);
		prvlgd.setUser("siteStr",siteStr);
		prvlgd.set("page.siteStr",siteStr);
		prvlgd.set("page.ilabelStr",ilabelStr);
		
		var fv=$.cookie("fv");
		if(fv==null || fv==undefined){
			fv=1;
		}else{
			if(fv != -1){
				fv++;
			}
			if(fv >3){
				fv=-1;
			}
		}
		prvlgd.set("page.fv",set30MinuteCookie("fv",fv));
		
		
		
		//Set page environment
		var serverEnv = "";
		var replEnvStr = location.host.replace(".weather.com","");
		
		if (location.href.match(/preview/)) {
			serverEnv = ["preview:",replEnvStr].join(""); 
		} else if (location.href.match(/beta/)) {
			serverEnv = ["beta:",replEnvStr].join(""); 
		} else {
			 serverEnv = ["live:",replEnvStr].join("");
		}
		prvlgd.set("page.env", serverEnv);
	
		
		
		
		var userpref=$.cookie("UserPreferences");
	
		//if (typeof(userpref)!="undefined" && null!=userpref){
		//calling this no matter what now. conditional logic inside 
		//this method because of UP age gender workaround SKB-18
			initUserPrefBasedCookies(userpref);
		//}
		
		
		var signedIn = $.cookie('Ticket_web');		
		prvlgd.setUser("signedIn", signedIn);
					
		// Set user's date and time when page loaded
		var dt = new Date(),
			yy = dt.getFullYear(),
			mt = dt.getMonth() + 1,
			date = dt.getDate(),
			dow = dt.getDay(),
			mh = dt.getHours(),
			hh = (mh > 12) ? mh - 12 : (mh == 0) ? 12 : mh,
			ampm = (mh < 12) ? "AM" : "PM",
			mm = dt.getMinutes(),
			ss = dt.getSeconds() + "",
			ss = (ss.length > 1) ? ss : "0" + ss,
			tm = dt.getTime(),
			day = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][dow],
			tzOffset = dt.getTimezoneOffset()/60;
		prvlgd.set("user.date",[mt,"/",date,"/",yy].join(""));
		prvlgd.set("user.time",[hh,":",mm,":",ss].join(""));
		prvlgd.set("user.day",day);
		prvlgd.set("user.tzOffset",tzOffset);
		
		prvlgd.setUser("preferredDeclaration",prvlgd.getPreferredDeclaration());
		prvlgd.setUser("suppressedDeclarations",manageSuppressedDeclarations());
		
		
		//populate soft declaration from page declaration if on dynamic page and not home page
		
		if ("false" == prvlgd.get("ad.dynamic") && "home" != prvlgd.get("ad.pageIdCode"))
		{
			var pageDeclValue = prvlgd.get("ad.pageDeclaration");
			setSoftDeclaration (pageDeclValue);
			var harddecl=prvlgd.getHardDeclarations();
			if (harddecl.indexOf(pageDeclValue) >= 0 )
			{
				setHardDeclaration(pageDeclValue);
			}
		}
		
		var defaultUnits = "e";
		if(locale_str !== "en_US") {
			defaultUnits = "m";
		}

		// Set user's unit prefs from cookie. if Titan pages check that unit first - Rob Toy
		var units = $.cookie("u") || defaultUnits;
		prvlgd.set("user.unit",units);
		if ( TWC && TWC.Titan && TWC.Titan.temp && TWC.Titan.temp !== units)
		{
			TWC.Titan.tempChange = true;
			prvlgd.set("user.unit", TWC.Titan.temp);
			$.cookie("u",TWC.Titan.temp,{domain:'.weather.com',path:'/'});
			prvlgd.setUser("reboot_unit", TWC.Titan.temp); 
		}
		
		
		// Set fromStr from either cookie or query param
		// Read the cookie from the fromStr cookie and set it in the
		// page node of PCO, then delete the cookie.
		var fromStr = $.cookie("fromStr");
		if(!fromStr){
			var params = window.location.search.substring(1);
			paramArray = params.split("&");
			for(var i=0, l=paramArray.length; i < l; i++) {
				if(paramArray[i].match(/from/)){
					fromStr = paramArray[i].split("=")[1];
					break;
				}
			}
		}
		prvlgd.set("page.fromStr",fromStr);
		
		
		// Set fromURL from either cookie or query param
		// Read the cookie from the fromURL cookie and set it in the
		// page node of PCO, then delete the cookie.
		var fromURL = $.cookie("fromURL");
		if(!fromURL){
			var params = window.location.search.substring(1);
			paramArray = params.split("&");
			for(var i=0, l=paramArray.length; i < l; i++) {
				if(paramArray[i].match(/fromurl/)){
					fromURL = paramArray[i].split("=")[1];
					break;
				}
			}
		}
		prvlgd.set("page.fromURL",fromURL);
		$.cookie('fromURL', null, {path:"/",domain:"weather.com"});
		
	
		
		prvlgd.setRMID();
	
		var currentUser = prvlgd.get("user");		
		if (currentUser.currentLocation ==null || typeof (currentUser.currentLocation)=="undefined"){			
			prvlgd.setUser('currentLocation', {});
		}
		var currentLocation = currentUser.currentLocation, updatedTime = currentLocation.updatedTime;
		var callLocation = "false", diff=0,curTime = new Date();
		if(updatedTime =='undefined' || updatedTime == null){
			callLocation = "true";				
		} else {
			var remindTimedate = new Date(updatedTime);
			diff = Math.floor((curTime.getTime() - remindTimedate.getTime()) / 90000); // ms per 15 min			
		}		
		if(callLocation=="true" || diff > 15) {	
			var akamaiURL = "" || "http://gip.imwx.com/wxdata/gip/get.js?cb=?";			
			$.ajax({
				url: akamaiURL,					
				type: 'GET',
				crossDomain: true,
				dataType: 'jsonp',
				success: function(data) {
					if(data && data.lat && data.lng){
						var dynhost = "d.imwx.com" || "d.imwx.com";
						var latUrl = 'http://'+dynhost+'/data/latlonlocation';						
						var lat = data.lat;
						var lon = data.lng;						
						var akaURL = latUrl + '?lat=' + lat + '&lon=' + lon;
						akaURL = encodeURI(akaURL);
						$.ajax({								
							url: akaURL,
							dataType: "jsonp",
							type:"GET",
							success: function(loc) {
								if(loc != null){
									currentLocation = loc;								
									currentLocation.updatedTime = new Date();
									prvlgd.setUser("currentLocation",currentLocation);
									TWC.Events.autodetectLocEvent.notify();
								}							
							}, error: function() {
								TWC.Events.autodetectLocFailEvent.notify();
							}
							
						});
						
					}
				}, error: function() {
					TWC.Events.autodetectLocFailEvent.notify();
				}
			});				 			
		}



		var currloc = prvlgd.get("currloc");
		var currentLocation = prvlgd.get("user.currentLocation");
		if(null != currloc && null != currentLocation && currentLocation.lat && currentLocation.lon){
			var latitude = currentLocation.lat;
			var longitude = currentLocation.lon;
			var url = encodeURI("http://wxdata.weather.com/wxdata/LBSAds/get.js?lat=" + latitude + "&lng=" + longitude + "&cb=?");
			piqDfrEvent = $.ajax({
				url: url,
				dataType: "jsonp",
				data:{
					key:"97ce49e2-cf1b-11e0-94e9-001d092f59fc"
				},
				type:"GET",
					success: function(list) {
						currloc.placeIQ = list;												
						prvlgd.setUser("currloc",currloc);					 
					}
			});
		}

try{console.log()}catch(e){}
        //This is for asset level targeting within a page.
        //An asset may be tagged by a collection, declaration etc.
        prvlgd.set("asset", {});

		if(wxLocDfrdEvent && adDfrdEvent && piqDfrEvent) {
			// If wxloc and/or ad are retrieved by a service 
			// call wait until the service call is complete
			// otherwise assume the data was in pcoObject.
			$.when(wxLocDfrdEvent,adDfrdEvent,piqDfrEvent).then(function(){
				prvlgd.setORD();
				prvlgd.initAdKeywords();
			});
		} else if(wxLocDfrdEvent && adDfrdEvent) {
			// If wxloc and/or ad are retrieved by a service 
			// call wait until the service call is complete
			// otherwise assume the data was in pcoObject.
			$.when(wxLocDfrdEvent,adDfrdEvent).then(function(){
				prvlgd.setORD();
				prvlgd.initAdKeywords();
			});
		} else if(wxLocDfrdEvent) {
			// Just wxloc service called
			$.when(wxLocDfrdEvent).then(function(){
				prvlgd.setORD();
				prvlgd.initAdKeywords();
			});
		} else if(adDfrdEvent) {
			// Just ad service called
			$.when(adDfrdEvent).then(function(){
				prvlgd.setORD();
				prvlgd.initAdKeywords();
			});
		} else if(piqDfrEvent) {
			// Just ad service called
			$.when(piqDfrEvent).then(function(){
				prvlgd.setORD();
				prvlgd.initAdKeywords();
			});
		} else {
			// No services called
			prvlgd.setORD();
			prvlgd.initAdKeywords();
		}

		TWC.Events.adKeywordsReady.progress(function(){
			// Fire pcoReady Event when ad keywords are ready
			TWC.Events.pcoReady.resolve();
			TWC.Events.pcoRefresh.notify();
		});

		
		// if there is a currloc in pco set cookie LocID
		// Eventually this will be removed.
		var currloc = prvlgd.get("currloc");
		if(currloc){
			$.cookie("LocID",currloc.locid,{path:"/",domain:"weather.com",expires:3650});
		}
		
	};
	

	/***
	 **
	 ** Privileged methods
	 **/
	 
	var prvlgd = {};
	
	prvlgd.getAd = function(){
		
	};
	
	prvlgd.get = function(n){
	
		// will return a value or undefined
		return getVal(n);
	};
	
	prvlgd.set = function(n,v){
		// will return the value you attempted to set, or undefined
		// will not create any missing intervening nodes
		
			return setVal(n,v);
		
	};

	//declarations methods
	prvlgd.getSoftDeclarations=function()
	{
		return (prvlgd.get("user.softDeclarations") || []);
	};

	prvlgd.removeSoftDeclaration=function(val)
	{
		var softdecl=prvlgd.getSoftDeclarations();
		var idx = softdecl.indexOf(val);
		//delete from soft
		if(idx >=0)
		{
			softdecl.splice(idx,1);
			prvlgd.set("user.softDeclarations",softdecl);
		}	
		
	};

	prvlgd.addSoftDeclaration=function(val)
	{
		prvlgd.removeSoftDeclaration(val);
		var softdecl=prvlgd.getSoftDeclarations();
		softdecl.unshift(val);
		prvlgd.set("user.softDeclarations",softdecl);
	};

	prvlgd.getHardDeclarations=function()
	{
		return (prvlgd.get("user.hardDeclarations") || []);
	};

	prvlgd.removeHardDeclaration=function(val)
	{
		var harddecl=prvlgd.getHardDeclarations();
		var idx = harddecl.indexOf(val);
		//delete from hard
		if(idx >=0)
		{
			harddecl.splice(idx,1);
			prvlgd.set("user.hardDeclarations",harddecl);
		}	
	};

	prvlgd.addHardDeclaration=function(val)
	{
		prvlgd.removeHardDeclaration(val);
		var harddecl=prvlgd.getHardDeclarations();
		harddecl.unshift(val);
		prvlgd.set("user.hardDeclarations",harddecl);
	};
	
	/*
	prvlgd.updateHardDeclaration=function(val)
	{		
		var harddecl=prvlgd.getHardDeclarations();
		if (harddecl contains val)
		{
			prvlgd.removeHardDeclaration(val);
			harddecl.unshift(val);
			prvlgd.set("user.hardDeclarations",harddecl);
		}
	};
	*/

	prvlgd.getSuppressedDeclarations=function()
	{
		return prvlgd.get("user.suppressedDeclarations") || {};
	};

	prvlgd.addSuppressedDeclaration=function(val)
	{
		var suppressdecl=prvlgd.getSuppressedDeclarations();
		if (!suppressdecl[val]){				
			//this is removing value from hash
			//testing - suppressdecl[val] = new Date(2011,10,8,0,0,0);
			suppressdecl[val] = new Date();
			prvlgd.set("user.suppressedDeclarations",suppressdecl);
		}
	};
	
	prvlgd.removeSuppressedDeclaration=function(val)
	{
		var suppressdecl=prvlgd.getSuppressedDeclarations();
		//adding to hard, so need to remove suppressed here
		if (suppressdecl[val]){				
			delete suppressdecl[val];
			prvlgd.set("user.suppressedDeclarations",suppressdecl);
		}
		
	};

	prvlgd.getPreferredDeclaration = function(){
		
		var hards = prvlgd.getHardDeclarations();
		if (hards && hards[0] && hards[0] !== undeclaredDec )
		{
			return hards[0];
		}
		var softs = prvlgd.getSoftDeclarations();
		if (softs && softs[0])
		{
			return softs[0];
		}
		
		return undeclaredDec;
		
	};
	
	initUserNode = function(node){
		if(!prvlgd.get("user")){
			var user = {};
			user[node] = {};
			persistValue("user",user);
		}
	}
	
	prvlgd.setUser = function(node,val,oper){
		if(!prvlgd.get("user")){
			PCO.user = {};
			persistValue("user",PCO.user);
		}
		if(node == "measurements") {
			if(val)
			{
				$.ajax({
					url: '/pagelet/userprefset?u='+val,
					dataType: 'html',
					type:'POST',
					success: function () {
						prvlgd.set("user.unit", val);	
						setTimeout(function ()
						{
							if((typeof(isMobileSite) != 'undefined') && isMobileSite==1){
								var currloc = TWC.pco.get('currloc');
								var additionalParams =  currloc.locid + ":" + currloc.loctype + ":" + (currloc.country).toUpperCase();
								document.location.href = TWC.pco.get("page").defaultCmd + "/"+additionalParams+"?"+ new Date().getTime();	
							}else{
								window.location.reload();
							}
						}, 0); 									
					},
					error: function (a,b,c) {
	
					}
		  	 	});
	  	 	}
		
		} else if(node == "reboot_unit") {
			if(val)
			{
				$.ajax({
					url: '/pagelet/userprefset?u='+val,
					dataType: 'html',
					type:'POST',
					success: function () {
						prvlgd.set("user.unit", val);										
					},
					error: function (a,b,c) {
	
					}
		  	 	});
	  	 	}
		
		} else if (node=="rmid") {
			prvlgd.set("user.rmid", val);
		} else if (node=="cobrand") {
			//prvlgd.set("user.cobrand", val);
		} else if (node==="age") {
			prvlgd.set("user.age", val);
		} else if (node==="gender") {
			prvlgd.set("user.gender", val);
		} else if (node==="gender") {
			prvlgd.set("user.gender", val);
		} else if (node==="coll") {
			prvlgd.set("user.coll", val);
		} else if (node==="claritas") {
			prvlgd.set("user.claritas", val);
		}else if (node==="dwInstallId") {
			prvlgd.set("user.dwInstallId",val);
		} else if (node==="ursId") {
			prvlgd.set("user.ursId",val);
		} else if (node=="preferredLocation") {
			prvlgd.set("user.preferredLocation", val);
		} else if(node == "lastResolvedLoc") {
			prvlgd.set("user.lastResolvedLoc", prvlgd.get("currloc"));
		} else if (node=="preferredDeclarationFamily") {
			prvlgd.set("user.preferredDeclarationFamily", val);
		} else if(node=="backTo") {
			prvlgd.set("user.backTo",val);
		} else if(node=="androidPopUp") {			
			prvlgd.set("user.androidPopUp",val);
		} else if(node=="currentLocation") {
			prvlgd.set("user.currentLocation",val);
		} else if(node=="parStr") {			
			prvlgd.set("user.parStr",val);
		} else if(node=="siteStr") {			
			prvlgd.set("user.siteStr",val);
		} else if(node=="lotame") {
			prvlgd.set("user.lotame",val);
		} else if(node.match(/Locations/)) {
			if(node=="initAllLocations") {
				initAllLocations(val);
			} else if(node=="savedLocations" && !oper) {
				prvlgd.set("user.savedLocations",setSavedLocations(val));
			} else if(node=="savedLocations" && oper) {
				prvlgd.set("user.savedLocations",modifySavedLocations(oper,val));
			} else if(node=="recentSearchLocations" && !oper) {
				prvlgd.set("user.recentSearchLocations",setRecentSearchLocations(val));
			} else if(node=="recentSearchLocations" && oper) {
				prvlgd.set("user.recentSearchLocations",modifyRecentSearchLocations(oper,val));
			}
			setPreferredLocation();
			TWC.Events.locations_changed.notify();
		} else if(node.match(/Declaration/)) {
			if (node=="initDeclarations") {
				if (val instanceof Array) {
					for (i=0; i < val.length; i++) {					
						setHardDeclaration(appsToHardDeclarations[val[i].toLowerCase()]);
					}
				}
				prvlgd.set("user.preferredDeclaration",prvlgd.getPreferredDeclaration());
			} else if (node=="hardDeclaration") {
				setHardDeclaration(val,oper);
				prvlgd.set("user.preferredDeclaration",prvlgd.getPreferredDeclaration());
			} else if (node=="softDeclaration") {
				setSoftDeclaration(val,oper);
				prvlgd.set("user.preferredDeclaration",prvlgd.getPreferredDeclaration());
			} else if (node=="suppressedDeclaration") {
				setSuppressedDeclaration(val,oper);
				prvlgd.set("user.preferredDeclaration",prvlgd.getPreferredDeclaration());
			} else if (node=="preferredDeclaration") {
				prvlgd.set("user.preferredDeclaration",val);
			}
		} else if(node=="mapPrefs" && !oper) {
			if(val) {
				prvlgd.set("user.mapPrefs", val);
	  	 	}
		}
		else if(node=="pollenExpand" && !oper) {
			prvlgd.set("user.pollenExpand",val);
		}	
		else if(node=="video" && !oper) {
			if(val)
			{
				prvlgd.set("user.video", val);
	  	 	}
		}
		// 4/2/2012: TODO, Need to look into refactor this code, shouldn't have to add this every time something new is added to user storage
		else if(node=="flash" && !oper) {
			if(val) {
				prvlgd.set("user.flash", val);
	  	 	}
		} else if (node=="signedIn") {			
			prvlgd.set("user.signedIn", val);
		} else if (node =="imap") {
			prvlgd.set("user.imap", val);
		} else if (node=="device") {
			prvlgd.set("user.device", val);
		} else if (node=="commuter") {
			prvlgd.set("user.commuter", val);
		} else if (node=="local_suite_bgw") {
			prvlgd.set("user.local_suite_bgw", val);
		} else if (node=="local_suite_bgm") {
			prvlgd.set("user.local_suite_bgm", val);
		}
		
		persistValue("user",prvlgd.get("user"));
		
	};


	prvlgd.setRMID=function() {
		
		//read rmid from local storage
		var rmid = prvlgd.get("user.rmid");
		if(!rmid)
			rmid=genRMID();
		
		prvlgd.setUser("rmid", rmid);
				
	};
	
	
	prvlgd.setORD=function() {
		var ord = genORD();
		prvlgd.set("ad.ord",ord);
		
	};
	
	prvlgd.initAdKeywords=function() {
		var adkeywords={};
		var cust_params="";
		
		function addContentModuleKeyword() {
			if(TWC && TWC.pcoinjector && (null != TWC.pcoinjector.ad_cmdl_keyword && typeof(TWC.pcoinjector.ad_cmdl_keyword) != 'undefined')) {
				var cmdlKeywords = TWC.pcoinjector.ad_cmdl_keyword;
				buildkw("cmdl",cmdlKeywords);
			}
		}
		
		function addTweetKeywords() {
			if(TWC && TWC.pcoinjector && (null != TWC.pcoinjector.ad_tweet_keyword && typeof(TWC.pcoinjector.ad_tweet_keyword) != 'undefined')) {
				var tweetKeywords = TWC.pcoinjector.ad_tweet_keyword;
				var tweetArr=[];
				var tweet = tweetKeywords.split(";");
				
				for (i=0;i < tweet.length; i++) {
					var tweetVal = tweet[i].split("=");
					var len = tweetVal.length;
					if(len >0 && len==2) {
						tweetArr.push(tweetVal[1]);
					}
				}
		
				buildkw("tweet",tweetArr,tweetArr.join('&tweet='));
			}
		}
		
		function getKeywordValues(keymap, keywords){
			
			jQuery.each(keymap, function (key, value) {
				buildkw(key,keywords[value]);
			});
		}
		
		function getPrcpKeywordValues(keyName, keywords){
					
			var myarray = new Array();
			jQuery.each(keywords, function (key, value) {   			 
			  myarray.push(key+"_"+value);	
			  
			});
			myarray.sort();
			buildkw(keyName,myarray);
		}
		
		function debugMode() {
			return !!$.cookie("adstest");
		}
		
		
		function addAdstest() {
			var isDebug=debugMode();
			var debugKeyword     = isDebug ?  $.cookie('adstest') : '';
			if (isDebug){
				buildkw("adstest",debugKeyword);
				prvlgd.set("ad.debug",true);
			}
		}
		
	function getKeywordNulls(keymap){
		
		jQuery.each(keymap, function (key, value)
		{
			buildkw(key, "nl");
		});
	}
		
		function addGPR(loc)
		{
			if (loc && loc.gpr){
				buildkw("intl",loc.gpr,loc.gpr.join("&intl="));
			}else{
				buildkw("intl","nl");
			}
		}
			
		function addLayoutKeywords(){
			var layoutArr=[],layoutValue=[];
			var layoutKeywords=prvlgd.get("ad.layout");
			if("undefined" != typeof(layoutKeywords)){
				var layout = layoutKeywords.split(";");
				for(i=0; i < layout.length; i++) {
					var layout2 = layout[i];
					layoutValue = layout2.split("=");
					if(layoutValue.length>0 && layoutValue.length==2){
						layoutArr.push(layoutValue[1]);
					}
				}
				
				buildkw("lo",layoutArr,layoutArr.join('&lo='));
			}
		
		}
		
		function addFV(){
			var vw = prvlgd.get("page.fv") || 'nl';
			vw = vw + ""; //convert to String
			buildkw("vw",vw);
		}
		
		function addORD(){
			if (prvlgd.get("ad.ord")){
				buildkw("ord",prvlgd.get("ad.ord"));
			}else{
				buildkw("ord","nl");
			}
		}
		
	
		function addWxKeywords() {
			var wx = prvlgd.get("wx");

			if(wx) {
				var wxkeymap =
				{
					tmp  : 'temp',
					tmpr : 'tempR',
					plln : 'pollen',
					wind : 'wind',
					uv   : 'uv',
					hmid : 'hum',
					sev  : 'severe',
					cnd  : 'cond',
					snw  : 'snw',
					baro : 'baroTendency'
				};
				
				 var fcstKeymap = {
						    fhi : "tempH",
						    fli : "tempL",
						    fhr : "tempHR",
						    flr : "tempLR",
						    fsnw: "fsnw",
						    cws: "cws",
						    fpdi1: "fpdi1",
						    fpdi2: "fpdi2",
						    fpdi3: "fpdi3"
						  };
	
				var fcstCondKeymap = {
						  	fc1 : "fc1",
						    fc2 : "fc2",
						    fc3 : "fc3"
				}
				
				var fcstPrcpKeymap = {
							prcp : "prcp"
				}
				var fiveDayKeymap = {
						  	d1 : "d1",
						    d2 : "d2",
						    d3 : "d3",
						    d4 : "d4",
						    d5 : "d5"
				}
				
				if (wx.temp || wx.tempR){
					getKeywordValues(wxkeymap, wx);
					if(wx.fcast) {
						getKeywordValues(fcstKeymap, wx.fcast);
					} else {
						getKeywordNulls(fcstKeymap);
					}
					if(wx.fcast.cond) {
						getKeywordValues(fcstCondKeymap, wx.fcast.cond);
					} else {
						getKeywordNulls(fcstCondKeymap);
					}
					if(wx.fcast.prcp) {
						getPrcpKeywordValues('prcp',wx.fcast.prcp);
					} else {
						buildkw('prcp','nl');
					}
					if(wx.fcast.fiveDay) {
						getKeywordValues(fiveDayKeymap,wx.fcast.fiveDay);
					} else {
						getKeywordNulls(fiveDayKeymap);
					}
				}
				else {
					getKeywordNulls(wxkeymap);
					getKeywordNulls(fcstKeymap);
					getKeywordNulls(fcstCondKeymap);
					getKeywordNulls(fcstPrcpKeymap);
					getKeywordNulls(fiveDayKeymap);
				}
			}
		}
		
		
		function addUserKeywords(){
			
			var user = prvlgd.get("user");
			if (user) {
				buildkw("age",user.age);
				buildkw("gender",user.gender);
				buildkw("rmid",user.rmid);
				buildkw("coll",user.coll);
				var cobrand=user.cobrand;
				buildkw("cobr",cobrand);
				
				
			} else {
				buildkw("age","nl");
				buildkw("gender","nl");
				buildkw("rmid","nl");
				buildkw("cobr","nl");
				buildkw("coll","nl");
			}
			
		}
		
		function addDeclKeywords() {
			if (prvlgd.get("user") && prvlgd.get("ad") ) {
	    		
	    		var	isdynamic=false;
	    		var fam="nl";
	    		var ch="nl";
                var assetDeclaration = prvlgd.get("asset").pcoll;
	    		var primaryDeclaration = prvlgd.get("user").preferredDeclaration;
				
				var isUndecl= (primaryDeclaration=="undc"?true:false);
				var pageDeclaration = prvlgd.get("ad").pageDeclaration;
				
	    		isdynamic = (prvlgd.get("ad").dynamic=="true")?true:false;
	    		var adcontents=prvlgd.get("ad").adContents;
	    		var contentTypeMap="";

                //If an asset has a declaration, it trumps the higher level declarations since it is the most context specific
                if(isdynamic && null != assetDeclaration) {
                    contentTypeMap=adcontents[assetDeclaration];
                }else if (!isdynamic && null!=pageDeclaration){
	    			 contentTypeMap=adcontents[pageDeclaration];
	    			
	    		} else if (isdynamic && isUndecl && typeof(businessDeclaration)!="undefined"){
	    			 contentTypeMap=adcontents[businessDeclaration];
	    		
	    			 buildkw("contentType",businessDeclaration);
	    		} else if (isdynamic && null!=primaryDeclaration){
	    			contentTypeMap=adcontents[primaryDeclaration];
	    			 buildkw("contentType",primaryDeclaration);
	    			        		
	    		}
	    		
	    		
	    	 	//if the page has a declaration use that to pass fam/channel keywords
	    		
	    		if (isdynamic && typeof(contentTypeMap)!="undefined"){
					fam=contentTypeMap.family;
					ch=contentTypeMap.channel;
					buildkw("fam",fam);
					buildkw("ch",ch);
					prvlgd.setUser("preferredDeclarationFamily", fam);
				
		    	}else if (!isdynamic && typeof(contentTypeMap)!="undefined"){
					prvlgd.setUser("preferredDeclarationFamily", contentTypeMap.family);
					
				}
			
			}else{
				buildkw("fam","nl");
				buildkw("ch","nl");
			}
			
			if (typeof(businessDeclaration)!="undefined" && prvlgd.get("page")){
			  prvlgd.set("page.businessVertical",businessDeclaration);
			}
			
		}
		
		function addForecastKeywords(){
		if (prvlgd.get("page") && prvlgd.get("currloc")) {			 
		        
		        if(prvlgd.get("currloc").loctype == "4") {		        			
			       buildkw("ent","zip");
			    } else if(prvlgd.get("currloc").loctype == "1") {		        			
			        	buildkw("ent","city");
			       }
		    }
	}
		
		function addAdKeywords(){
			var ad=prvlgd.get("ad");
			 if (ad && ad.keywords) {
				 var kw=ad.keywords;
				  for (var i=0; i< kw.length; i++){
					  var kwarr=kw[i].split("=");
					  if (kwarr[0] && kwarr[1]){
						  buildkw(kwarr[0],kwarr[1]);
					  }
				  }
			 }
			 if(ad && ad.ord){
				 buildkw("ord",ad.ord);
			 }
			 
			 // amznads keywords into cust_params...
			 if("amznads" in window && "getKeys" in window.amznads) {
			 	var keys = amznads.getKeys(); 
				
				var amznStr="";
				for(var i =0; i < keys.length; i++) {  
				 	amznStr+=keys[i];
				 	if (i < keys.length-1){
				 		amznStr+=",";
				 	}
				}
				buildkw("amznslots",amznStr);
			 }

			 // Yieldfire keywords into cust_params...
			 if("YF" in window && "getKVNoYFP" in window.YF) {
			 	buildkw("yfp", window.YF.getKVNoYFP());
			 }
			 
			 if(prvlgd.get("page.parStr")) {
			 	buildkw("par",prvlgd.get("page.parStr"));
			 }
			 
			 var isRefKeyWordBuilt = false;
			 if(document && document.referrer && document.referrer.length > 0) {
			 	try {
			 		// a simple hack to convert string URL to location object and there by get hostname.
			 		var hostValue = jQuery('<a>').prop('href', document.referrer).prop('hostname');
				 	if(hostValue && hostValue.indexOf(".") != -1) {
				 		var hostParts = hostValue.split(".");
				 		var hostPartsLength = hostParts.length;
				 		if(hostPartsLength > 1) {
				 			var startIndex = (hostParts[0] == 'www' ? 1 : 0);
				 			var website = hostParts.splice(startIndex, hostPartsLength - startIndex - 1).join(".");
				 			buildkw("refurl", website);
				 			isRefKeyWordBuilt = true;
				 		}
				 	}
			 	}
			 	catch(err) {
			 	}
			 }
			 if(!isRefKeyWordBuilt) {
			 	buildkw("refurl", "nl");
			 }
		}
		
		function buildkw(name, value, asStr){
			// Temporary code to block certain keywords not currently
			// not currently sold from appearing ad calls (BKB-157)
            var paramsToIgnore = ["prcp","piq","cid"];
			if(paramsToIgnore.indexOf(name) !== -1) {
				return;
			}
			// End BKB-157 fix
			
			var val = value || "nl";
			adkeywords[name]=val;
			if(!asStr) {
				cust_params=cust_params+name+"="+val+"&";
			} else {
				cust_params=cust_params+name+"=" +asStr+"&";
			}
			
		}
		
		function addLocaleKeywords(){
			var locale ='nl';
			var page = prvlgd.get("page");
			if(page && page.locale){
				locale = page.locale;
			}
			buildkw('locale', (locale ||'nl') );
		}
		
		function addWfxTriggers()
		{
			if (typeof wfxtrigs != 'undefined')
			{
				var sArray = wfxtrigs.split ("=")
				if (sArray && sArray.length > 1)
				{
					buildkw(sArray[0], (sArray[1]));	
				}
			}
			
		}
		
		function addWwiKeywords(){
			var eventCode ='nl';
			var currloc=prvlgd.get("currloc");
			var key = "97ce49e2-cf1b-11e0-94e9-001d092f59fc";
			var baseURL =  "http://wxdata.weather.com/wxdata/";
			var param = "wwir/"+currloc.locid + ".js?cb=?&includeDay=false";
			var url = baseURL + param;
			$.ajax(url, {
					"dataType": "jsonp",
					"jsonp": "cb",
					"cache": true,
					"data": {"key":key},
					success: function(data) {	 
						var combinedEventType = data.overallType || '';
    					buildkw('h2o',combinedEventType);
    					prvlgd.set("ad.pageKeywords", adkeywords);
						prvlgd.set("ad.cust_params",cust_params);
    					TWC.Events.adKeywordsReady.notify();
	    			}, 
	    			error: function (jqXHR, textStatus, errorThrown) {
	    				prvlgd.set("ad.pageKeywords", adkeywords);
						prvlgd.set("ad.cust_params",cust_params);
	    				TWC.Events.adKeywordsReady.notify();
	    			}		
    			});
    		
		}
		
		function addLotame() {
			var tpid = prvlgd.get('user.lotame.lot_tpid'); 
			if (tpid && tpid !== '') {
				buildkw("tpid",tpid);
			}
		}
		
		function addLocKeywords() {
			var cid= 'nl';
			var currloc=prvlgd.get("currloc");
			var piqData='' ;
			var piq = [];

			var loc, dma, stateCd, city, countryCd,countyName,zip;
			
			// Test to see if currloc is an empty object,
			// since it may have been initialized as an 
			// empty object. If it was not initialized
			// and is undefined, this test will also fail.
			if ($.isEmptyObject(currloc)){
				currloc=prvlgd.get("user.preferredLocation");
			}
			
			// Only need to test if currloc is truthy since,
			// At this point it will only be undefined (falsy) 
			// if there was no user.preferredLocation
			if(currloc) {
					
				if(currloc.locid) {
					loc=currloc.locid;
					zip=currloc.zip;
				} else if(currloc.zip) {
					loc=currloc.zip;
					zip=currloc.zip;
				}
				
			
		  
				if(loc && loc.indexOf(":") !=-1) {
					loc = loc.replace(":","$");
				} 
				var city = currloc.locname;
				if(city) {
					city=city.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
				}
				
				dma=currloc.dma || 'nl';
				stateCd=currloc.state || 'nl';
				countryCd=currloc.country || 'nl';
				countyName=currloc.countyName || 'nl';
				cid=currloc.claritas || 'nl';
				
				buildkw('loc',(loc ||  'nl'));
				buildkw('dma', dma);
				buildkw('st', stateCd.toLowerCase());
				buildkw('cc',countryCd.toLowerCase());
				buildkw('cnty',countyName);
				buildkw('cid',cid);
				buildkw("zip",zip);
				buildkw("lat",((currloc.lat + "") || 'nl'));
				buildkw("lon",((currloc.lon + "")  || 'nl'));
				buildkw("ct",(city || 'nl'));
				
				// Adding placeIQ elements to the ad call
				if(currloc.placeIQ && currloc.placeIQ.piq) {							
					piqData = currloc.placeIQ.piq;							
				}
				if(piqData && piqData.length > 0) {
					for (var count=0; count < piqData.length; count++){				
						piq.push(piqData[count].value);							
					}
					buildkw("piq",piq,piq.join('&piq='));
				} else {
					buildkw("piq",'nl');
				}
				
				addGPR(currloc);
				
			} else {
				buildkw('loc','nl');
				buildkw('dma', 'nl');
				buildkw('st', 'nl');
				buildkw('cc','nl');
				buildkw('cid','nl');
				buildkw('intl','nl');
				buildkw('ct','nl');
				buildkw('lat','nl');
				buildkw('lon','nl');
			}
	
		}
		
		
		addLayoutKeywords();
		addLocKeywords();
		addLocaleKeywords();
		addWxKeywords();
		addAdKeywords();
		addForecastKeywords();
		addDeclKeywords();
		addUserKeywords();
		addFV();
		addAdstest();
		addTweetKeywords();
		addContentModuleKeyword();
		addLotame();
		addWfxTriggers();
		
		var currloc = prvlgd.get("currloc");
		if (typeof doWWiKeywords != 'undefined' && doWWiKeywords == true && currloc) {
			addWwiKeywords();
		} else {
			prvlgd.set("ad.pageKeywords", adkeywords);
			prvlgd.set("ad.cust_params",cust_params);
			TWC.Events.adKeywordsReady.notify();
		} 		
		
	};
	
	function genRandStr(inlen,inchars) {
		var chars = inchars?inchars:"0123456789";
		var len = inlen?inlen:16;
		var ret = "";
		for(var i=0; i < len; i++) {
			ret += chars.charAt(Math.floor(Math.random()*chars.length)%chars.length);
		}
		return ret;
	}
	
	function genRMID() {
		return genRandStr(16,"0123456789");
	}
	
	function genORD() {
		return genRandStr(16,"0123456789");
	}

	prvlgd.setDevice=function(){
		var usr=prvlgd.get("user");
		if(!usr || typeof(usr.device)=="undefined") {
			jQuery.ajax({
				url: '/pagelet/wurfl',
				dataType: 'json',
				
				success: function (data) {
					prvlgd.setUser("device", data);
					TWC.Events.userDeviceevent.resolve();
				}
	  	 	});
		
		} else {
			TWC.Events.userDeviceevent.resolve();
		}
	};
	
	prvlgd.updateClassName = function(className) {
		jQuery(".mw-wx-triggered").addClass(className);
	};

	prvlgd.setClassName=function(){
		var usr=prvlgd.get("user");
		var recentSearchLocs=prvlgd.get("user.recentSearchLocations") || [],
			rsLength = recentSearchLocs.length;
		if (rsLength > 0){
				jQuery.ajax({
					url: '/pagelet/wxtrigger/'+recentSearchLocs[0].locid,
					dataType: 'json',
					type:'GET',
					success: function (data) {
						window[data.functionName](data.className);	
					}
					
			   	});
		}
	};
	
	
	
	
	// Initialize PCO
	init();
	
	/***
	 **
	 ** Return a reference to the privileged object
	 **/
	return prvlgd;
};
