//**************************************************
// targetingFW.js
// Author: Andrew Burgess 
// Version: 1.0
// Date: 7/21/2008
// release: 10/28/2008
// Update: 
// this framework is the js side of the 
// homepage targeting framework
//***************************************************

var has_geo = false;
var localizedZip = '';

document.observe("dom:loaded", function() {
	targetingFW.runTargeting(); 
	
});

function targetingFWLib() {
	// global stuff
	var contentDropletRequestURL = '/homepage/contentItemDroplet.jsp?q_name=';
	var userDataHash = new Hash();
	var contentItems = new Hash();
	var geoTargetedSlots = new Array('marquee1','slot2','slot3','slot4'); // add slot names here to enable geo flagging
	var stateBucket;
	var region_13_state = new Array('AR','KS','MS','OK',"TX",'CA','NE','CO','IL','IN','MI','OH','WI');
	var region_9_state = new Array('AL','FL','GA','KN',"LO",'MS','NC','SC','TN');
	var region_OF = new Array('AK','AZ','CT','DE','DC','HI','ID','IA','ME','MD','MA','MN','MT','NV','NH','NJ','NM','NY','ND','OR','PA','RI','SD','UT','VT','VA','WA','WV','WY');
	var region_13_state_fullName = new Array('Arkansas','Kansas','Missouri','Oklahoma',"Texas",'California','Nebraska','Colorado','Illinois','Indiana','Michigan','Ohio','Wisconsin');
	var region_9_state_fullName = new Array('Alabama','Florida','Georgia','Kentucky',"Louisiana",'Mississippi','North Carolina','South Carolina','Tennesee');
	var region_OF_fullName = new Array('Alaska','Arizona','Connecticut','Delaware','District of Columbia','Hawaii','Idaho','Iowa','Maine','Maryland','Massachusetts','Minnesota','Montana','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Dakota','Oregon','Pennsylvania','Rhode Island','South Dakota','Utah','Vermont','Virginia','Washington','West Virginia','Wyoming');
	var validTargetCodes = new Array('3_13_UM','3_13_DM_UG','3_13_DM','3_13_M_UG','3_13_M','3_13_U','3_13_D_UG','3_13_D','2_13_UG','2_13_CI','2_13','3_9_UM','3_9_DM','3_9_DM_UG','3_9_M_UG','3_9_M','3_9_U','3_9_D_UG','3_9_D','2_9_UG','2_9_CI','2_9','3_OF_M','2_OF','1');
	//var uverseLGDMACodes = new Array('4','13','16');
	
	// global to hold querystring params for overriding akamai headers during testing
	var overrideArgs = '';
	
	// vars to pivot targeting
	var existingCustomerType = 1;
	var accountType = '';
	var compISP ='';
	var uverseEligible = '';
	var region = '';
	var testing;
	var Geo = '';
	var metaTagsInHead = $$('head meta');
	var trackingPageParam;
	
	//test numbers
	this.isNumeric = function(inputVal) {
		if (isNaN(parseFloat(inputVal))) {
         	return false;
     	}
    	return true
	}
	
	// convert texas to tx and vice-versa
	this.convertStateName = function(name) {
		var foundRetVal = false;
		var foundLocation;
		if(name.length > 2) {
			var foundLocation = region_13_state_fullName.indexOf(name);
			if(foundLocation == -1) {
				foundLocation = region_9_state_fullName.indexOf(name);
				if(foundLocation == -1) {
					foundLocation = region_OF_fullName.indexOf(name);	
					if(foundLocation == -1) {
						// not in a US state
					}
					else {
						foundRetVal = region_OF[foundLocation];
					}
				}
				else {
					foundRetVal = region_9_state[foundLocation];
				}
			}
			else {
				foundRetVal = region_13_state[foundLocation];
			}
		}
		return foundRetVal;
	}
	
	// method for overriding akamai headers during testing
	this.checkOverrideArgs = function() {
		var retval = false;
		overrideArgs = window.location.href.parseQuery();
		if(overrideArgs != '' && overrideArgs.testMode == 'testing') {
			retval = true;
			testing = true;
		}
		return retval;
	}
	// accessors for pivot vars
	this.getExistingCustomerType = function() {
		return existingCustomerType;
	}
	this.getAccountType = function() {
		return accountType;
	}
	this.getRegion = function() {
		return region;
	}
	this.getCompISP = function() {
		return compISP;
	}
	this.getUverseEligible = function() {
		return uverseEligible;
	}
	
	// returns the concatenated userScheme
	this.getUserScheme = function() {
		var pUserScheme;
		pUserScheme = existingCustomerType;
		trackingPageParam = existingCustomerType + '~';
		if(region != '') {
			pUserScheme = pUserScheme + '_' + region;
			trackingPageParam = trackingPageParam + region;
		}
		trackingPageParam = trackingPageParam + '~';
		if(accountType != '') {
			pUserScheme = pUserScheme + '_' + accountType;
			trackingPageParam = trackingPageParam + accountType;
		}
		trackingPageParam = trackingPageParam + '~';
		if(compISP != '') {
			pUserScheme = pUserScheme + '_' + compISP;
			trackingPageParam = trackingPageParam + compISP;
		}
		trackingPageParam = trackingPageParam + '~';
		if(uverseEligible != '') {
			pUserScheme = pUserScheme + '_' + uverseEligible;
			trackingPageParam = trackingPageParam + uverseEligible;
		}
		return pUserScheme;
	}
	// return the current record of a user's state (as in 'WA' not 'cookied')
	this.getStateBucket = function() {
		return stateBucket;
	}
	
	// sets the content Items in a hash
	this.setContentItems = function(userType) {
		var isValidType = validTargetCodes.indexOf(userType);
		if(isValidType == -1) {
			userType = 1;
			trackingPageParam='1~~~~';
		}
		var contentItemsForUser = this.getContentHash();
		contentItemsForUser.set('marquee1', userType + '_marquee1');
		contentItemsForUser.set('slot1', userType + '_slot1');
		contentItemsForUser.set('slot2', userType + '_slot2');
		contentItemsForUser.set('slot3', userType + '_slot3');
		contentItemsForUser.set('slot4', userType + '_slot4');
		contentItemsForUser.set('accordion1', userType + '_accordion1');
	}
	
	// determines if user is 9 or 13 state and stores that information
	this.setStateBucket = function(stateToMatch) {
		var foundLocation = region_13_state.indexOf(stateToMatch);
		if(foundLocation == -1) {
			foundLocation = region_9_state.indexOf(stateToMatch);
			if(foundLocation == -1) {
				stateBucket = 'region_0';
				region = 'OF';
			}
			else {
				stateBucket = 'region_9';
				region = '9';
			}
		}
		else {
			stateBucket = 'region_13';
			region = '13';
		}
	}
	
	// return the current hash of user data to the caller
	this.getUserHash = function() {
		return userDataHash;
	}
	
	// return the current hash of contentItems to the caller
	this.getContentHash = function() {
		return contentItems;
	}
	
	// parse content map
	this.parseMap = function() {
		this.collectMeta();
		//this.getContentItems();
	}
	
	//calls content droplet by sending ajax request for each item in contentItems map
	this.getContentItems = function() {
		var reqURI;
		var ajaxUpd;
		var isCali = false;
		var found;
		var subst;
		if(userDataHash.get('DCSext.wt_aka_region_code') == 'CA') {isCali = true}
		var caliSlotNames = new Array('2_13_slot2','2_13_CI_slot2','2_13_CI_slot4','2_13_UG_slot4','3_13_D_slot2','3_13_D_slot4','3_13_D_UG_slot4','3_13_M_UG_slot1','3_13_M_slot4','3_13_DM_UG_slot4','3_13_DM_slot4','2_13_slot1','2_13_slot3','2_13_slot4','2_13_UG_slot1','2_13_UG_slot2','2_13_UG_slot3','2_13_CI_slot1','2_13_CI_slot3','3_13_U_slot1','3_13_U_slot2','3_13_U_slot3','3_13_U_slot4','3_13_D_UG_slot1','3_13_D_UG_slot2','3_13_D_UG_slot3','3_13_D_slot1','3_13_D_slot3','3_13_M_UG_slot2','3_13_M_UG_slot3','3_13_M_UG_slot4','3_13_M_slot1','3_13_M_slot2','3_13_M_slot3','3_13_UM_slot1','3_13_UM_slot2','3_13_UM_slot3','3_13_UM_slot4','3_13_DM_UG_slot1','3_13_DM_UG_slot2','3_13_DM_UG_slot3','3_13_DM_slot1','3_13_DM_slot2','3_13_DM_slot3');
		var caliMarqueeNames = new Array('2_13_marquee1','2_13_CI_marquee1','2_13_UG_marquee1','3_13_D_marquee1','3_13_D_UG_marquee1','3_13_M_UG_marquee1','3_13_DM_UG_marquee1','3_13_DM_marquee1','3_13_U_marquee1','3_13_UM_marquee1','3_13_M_marquee1');
		contentItems.each(function(pair) {
			reqURI = contentDropletRequestURL + pair.value;
			if(geoTargetedSlots.indexOf(pair.key) != -1 && typeof userDataHash.get('DCSext.wt_aka_dma') != 'undefined') {
				reqURI = contentDropletRequestURL + pair.value + '&q_geography=' + userDataHash.get('DCSext.wt_aka_dma') + '&q_default=false';
			}
			
			if(pair.key == 'marquee1' || pair.key == 'accordion1' ) {
				if(pair.key == 'marquee1') {
					// hack for CA content
					found = caliMarqueeNames.indexOf(pair.value);
					if(isCali && found != -1) {
					subst = pair.value.sub('_marquee', '_CA_marquee');
					if(geoTargetedSlots.indexOf(pair.key) != -1 && typeof userDataHash.get('DCSext.wt_aka_dma') != 'undefined') {
						reqURI = contentDropletRequestURL + subst + '&q_geography=' + userDataHash.get('DCSext.wt_aka_dma') + '&q_default=false';
					} else {
						reqURI = contentDropletRequestURL + subst;
					}
				}
			}
				ajaxUpd = new Ajax.Updater(pair.key,reqURI, {method: 'get', evalScripts: 'true'});
			} 
			else {
				// hack for CA content
				found = caliSlotNames.indexOf(pair.value);
				if(isCali && found != -1) {
					subst = pair.value.sub('_slot', '_CA_slot');
					reqURI = contentDropletRequestURL + subst;
				}	
				ajaxUpd = new Ajax.Updater(pair.key,reqURI, {method: 'get'});
			}
		});
		this.appendId();
	}
	
	this.appendId = function(key,val) {
		if(testing) {
			contentItems.each(function(pair) {
				//$(pair.key+'idHolder').innerHTML += pair.value;
			});	
		}
	}
	
	// returns userType
	this.getUserType = function() {
		var pUserType = this.getUserScheme();
		return pUserType;
	}
	
	// get the cookie
	this.getCookie = function(name) {
		var dc = document.cookie;
	  	var prefix = name + "=";
	 	var begin = dc.indexOf("; " + prefix);
	  	if (begin == -1) {
	    	begin = dc.indexOf(prefix);
	    	if (begin != 0) {
	    		return null;
	    	}
	  	} 
	  	else {
	    	begin += 2;
	    }
	  	var end = document.cookie.indexOf(";", begin);
	  	if (end == -1) {
	    	end = dc.length;
	    }
	  	return unescape(dc.substring(begin + prefix.length, end));
	}
	
	//sets up DTAB cookie write params
	this.setDtab = function() {
		setCookie("DTAB","Tab=Res","90","/",".att.com")	
	}
	
		
	// read a cookie, parse logic depends on name of cookie, we know how to parse if we know the name
	this.parseCookie = function(cookieToParse) {
		var myCookie = this.getCookie(cookieToParse);
		var pRegion = this.getRegion();
		var cookieCtr = 0;
		if( myCookie != null) {
			switch(cookieToParse) {
				case 'attPersistantLocalization' :
					var contentArray = myCookie.split("|");
					var numNodes = contentArray.length;
					if(numNodes >= 5) {
						// if user has localised to something other than the header says, trust the user
						var localizedState = contentArray[3].substring(6);
						localizedZip = '?zip_code='+contentArray[5].substring(4);
						var convertedStateName = this.convertStateName(localizedState);
						if(convertedStateName && convertedStateName != userDataHash.get('DCSext.wt_aka_region_code')) {
							this.setStateBucket(convertedStateName);
							userDataHash.set('DCSext.wt_aka_region_code', convertedStateName);
							if(region == 'OF') {
								if(accountType.include('D')) {
									accountType = accountType.sub('D', '');
									if(accountType == '') {existingCustomerType = 2}
								}
								compISP = '';
							}
						}
					}
					break; 
				case 'TargetUverse' :
					if(!accountType.include('U') && pRegion != 'OF') {
						userDataHash.set('uverseGreen', true);
						uverseEligible = uverseEligible + 'UG';
						if(compISP == 'CI') {compISP = ''}
					}
					break; 
				case 'uvp_env' :
					if(pRegion != 'OF') {
						userDataHash.set('uverse', true);
						cookieCtr++;
						accountType = accountType.gsub('D', '') + 'U';
						compISP = '';
					}
					break; 
				case 'colam_ctn' :
					if(this.isNumeric(myCookie.substr(0, 9))) {
						userDataHash.set('olam', true);
						cookieCtr++;
						accountType = accountType + 'M';
					}
					break; 
			}
			if(cookieCtr > 0 && accountType != '') {
				existingCustomerType = 3;
				compISP = '';
			}
		}
	}
	
	// call parser on a list of cookies and set values in hash
	this.parseCookies = function() {
		var cookieList = new Array('attPersistantLocalization', 'uvp_env', 'TargetUverse', 'colam_ctn');
		for(i = 0; i < cookieList.size(); i++) {
			this.parseCookie(cookieList[i]);
		}
	}
	
	// grab meta tags from the head and store in a hash
	this.collectMeta = function() {
		var akaMetaCtr = 0;
		// see if we're in test mode, if so: override headers with test data from harness page
		if(this.checkOverrideArgs()) {
			var items = overrideArgs;
			if(typeof items.region_code != 'undefined') {
				if(items.region_code != 'unknown') {
					userDataHash.set('DCSext.wt_aka_region_code', items.region_code);
				}
				akaMetaCtr++;
			}
			if(typeof items.network != 'undefined') {
				userDataHash.set('DCSext.wt_aka_network', items.network);
				akaMetaCtr++;
			}
			if(typeof items.dma != 'undefined') {
				userDataHash.set('DCSext.wt_aka_dma', items.dma);
				akaMetaCtr++;
			}
		}
		else {
			for(var i = 0; i < metaTagsInHead.size(); i++) {
				if(metaTagsInHead[i].name.toString().include('aka_')) {	
					userDataHash.set(metaTagsInHead[i].name, metaTagsInHead[i].content);
					akaMetaCtr++;
				}			
			}	
		}	
		if(akaMetaCtr > 0) {
			if(typeof userDataHash.get('DCSext.wt_aka_region_code') != 'undefined') {
				has_geo = true;
				existingCustomerType = 2;
				this.setStateBucket(userDataHash.get('DCSext.wt_aka_region_code'));
			}
			if(typeof userDataHash.get('DCSext.wt_aka_network') != 'undefined') {
				var pRegion = this.getRegion();
				if(userDataHash.get('DCSext.wt_aka_network') == 'att' || userDataHash.get('DCSext.wt_aka_network') == 'sbc_internet' || userDataHash.get('DCSext.wt_aka_network') == 'prodigy') {
					if(!accountType.include('U') && region != 'OF') {					
						accountType = 'D' + accountType;
						existingCustomerType = 3;
					}
				}
				else {
					if(region != 'OF' || existingCustomerType != 3) {
						compISP = compISP + 'CI';
					}
				}
			}
			if(this.getRegion() != '') {
				this.parseCookies();
			}
		}
	}
	
	//tracking stuff
	this.initTracking = function(userType) {
		//var trackUser = userType.toString().gsub('_', '~');
		for(var i = 0; i < metaTagsInHead.size(); i++) {
			if(metaTagsInHead[i].name.toString().include('wtPN')) {	
				metaTagsInHead[i].setAttribute("content", 'ATT_Front_Door_v2|' + trackingPageParam);
			}		
		}
		this.runWT();	
	}
	
	
	this.runWT = function() {
		setTimeout('dcsMain()', 3000);
	}
	
	// this sets up any linkfarm differences in the link farm for user types
	this.setupLinkFarm = function() {
		if(this.getUserType().include('9') || this.getUserType().include('13')) {
			$('movingLink').show();
		}
	}
	
	// init for runtime
	this.runTargeting = function() {
		this.parseMap();	
		var pUserType = this.getUserType();
		//alert(pUserType);
		this.setContentItems(pUserType);
		this.getContentItems();
		this.initTracking(pUserType);
		if(pUserType != 1) {this.setupLinkFarm()};
		this.setDtab();
	}
}
// Instantiation of the class
var targetingFW = new targetingFWLib();
