// this class abstracts a modified client-side personalization system for product family landing pages
if(typeof console !== 'undefined') {var debug = false}
var currentGeoList = '';
//global function to be called by flash adManager for geolocation
var getPageLevelGeos = function() {
	if(debug){console.log('getPageLevelGeos called, returned: '+currentGeoList);}
	return currentGeoList;
}
var doStatusHeadingInjection = function(headerStatus) {
	if(debug){console.log('in header');}
	switch(headerStatus) {
	case 'headingUV':
		$('statusHeadingHolder').innerHTML = '<h1>Advanced TV Services</h1><h3 class="accent3" style="position:absolute; top:0px; right:0px; font-weight:normal"><img src="/homepage/Common/indc/watcher/images/thumbs_up.gif" alt="" style="vertical-align:middle" /> U-verse may be available in your area!</h3>';
	break;
	case 'headingATV':
		$('statusHeadingHolder').innerHTML = '<h1>AT&amp\;T | DIRECTV Services</h1><h3 class="accent3" style="position:absolute; top:0px; right:0px; font-weight:normal"><img src="/homepage/Common/indc/watcher/images/thumbs_up.gif" alt="" style="vertical-align:middle" /> We offer DIRECTV in your area!</h3>';
	break;
	case 'headingEC':
		$('statusHeadingHolder').innerHTML = '<h1>Advanced TV Services</h1><h3 class="accent3" style="position:absolute; top:0px; right:0px; font-weight:normal"><img src="/homepage/Common/indc/watcher/images/thumbs_up.gif" alt="" style="vertical-align:middle" />Thank you for being a U-verse customer!</h3>';
	break;
	default:
		$('statusHeadingHolder').innerHTML = '';
	}
}
function LandingTargeter(typeTrigger) {
	// class vars
	var contentDropletRequestURL = '/homepage/contentItemDroplet.jsp?q_name=';
	var teamsiteDirectRequestURL = '/homepage/slots/en_US/watcher/';
	var userDataHash = new Hash();
	var contentItems = new Hash();
	var metaTagsInHead = $$('head meta');
	var stateBucket;
	var existingCustomerType = 1;
	var accountType = '';
	var uverseEligible = '';
	var testing;
	var region = '';
	var region_13_state = new Array('AR','KS','MS','OK',"TX",'CA','NV','CT','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','CO','DE','DC','HI','ID','IA','ME','MD','MA','MN','MT','NE','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','Nevada','Connecticut','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','Colorado','Delaware','District of Columbia','Hawaii','Idaho','Iowa','Maine','Maryland','Massachusetts','Minnesota','Montana','Nebraska','New Hampshire','New Jersey','New Mexico','New York','North Dakota','Oregon','Pennsylvania','Rhode Island','South Dakota','Utah','Vermont','Virginia','Washington','West Virginia','Wyoming');
	var pageType = typeTrigger;
	var validTargetCodes;
	var greenDMA = new Array(524,561,501,505,513,635,651,605,800,862,825,866,811,623,650,693,616,602,535,510,669,588,533,807,803,641,618,609,528,548,563,617,658,527,517,659,630,678,765,670,633,828,648,551,547,542,671,600,534,560,546,545,640,686,529,716,622,718,557);
	this.runTargeting = function() {
		var userType = 'unknown';
		this.parseMap();
		if(debug){console.log('num green DMAs = '+greenDMA.length);}
		this.getContentItems();
		this.runWT();
	}
	this.getRegion = function() {
		return region;
	}
	this.isNumeric = function(inputVal) {
		if (isNaN(parseFloat(inputVal))) {
         	return false;
     	}
    	return true
	}
	
	this.setPageLevelGeos = function() {
		if(debug){console.log('in setGeos');}
		if(userDataHash.get('DCSext.wt_aka_region_code')) {
			currentGeoList += userDataHash.get('DCSext.wt_aka_region_code');
			if(debug){console.log('state set to '+currentGeoList);}
		}
		if(currentGeoList != '' && userDataHash.get('DCSext.wt_aka_dma')) {
			currentGeoList += ','+userDataHash.get('DCSext.wt_aka_dma');
			if(debug){console.log('added DMA '+currentGeoList);}
		} else if(currentGeoList == '' && userDataHash.get('DCSext.wt_aka_dma')) {
			currentGeoList += userDataHash.get('DCSext.wt_aka_dma');
			if(debug){console.log('added DMA '+currentGeoList);}
		}
		if(debug){console.log('PageLevelGeos set '+currentGeoList);}
	}
	this.getUserScheme = function() {
		if(debug){console.log('in getScheme')}
		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(uverseEligible != '') {
			pUserScheme = pUserScheme + '_' + uverseEligible;
			trackingPageParam = trackingPageParam + uverseEligible;
		}
		this.setPageLevelGeos();
		return pUserScheme;
	}
	this.parseMap = function() {
		switch(pageType) {
			case 'watcher' :
				validTargetCodes = new Array('2_13_UG','2_9_UG','2_13_UR','2_9_UR','3_13_U','3_9_U','2_OF_UR','1');
				if(debug){console.log('in parse for: '+pageType);}
				this.collectMeta();
			break;
			case 'surfer' :
				// surfer goes here
			break;
			case 'talker' :
				// talker goes here
			break;
			case 'bundles' :
				// bundles goes here
			break;
			default:
				if(debug){console.log('pageType not defined properly')}
		}
	}
	this.checkOverrideArgs = function() {
		var retval = false;
		overrideArgs = window.location.href.parseQuery();
		if(overrideArgs != '' && overrideArgs.testMode == 'testing') {
			retval = true;
			testing = true;
		}
		return retval;
	}
	// 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';
		}
	}
	this.flipGrid = function(gridToShow,gridToHide) {
		$(gridToShow).show();
		$(gridToHide).hide();
	}
	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()) {
			if(debug){console.log('in override')}
			var items = overrideArgs;
			//alert(items.dma + ' ' + items.region_code);
			if(typeof items.dma != 'undefined') {
				userDataHash.set('DCSext.wt_aka_dma', items.dma);
				if(items.region != 'OF' && items.ug == 'true') {
					userDataHash.set('isUverseGreen', true);
				}
				akaMetaCtr++;
			}
			if(typeof items.dma == 'undefined' && typeof items.region_code != 'undefined') {
				userDataHash.set('DCSext.wt_aka_region_code', items.region_code);
				if(items.region != 'OF' && items.ug == 'true') {
					userDataHash.set('isUverseGreen', true);
				}
				akaMetaCtr++;
			}
			if(typeof items.dma != 'undefined' && typeof items.region_code != 'undefined') {
				userDataHash.set('DCSext.wt_aka_region_code', items.region_code);
				if(items.region != 'OF' && items.ug == 'true') {
					userDataHash.set('isUverseGreen', true);
				}
				akaMetaCtr++;
			}
			if(typeof items.dma == 'undefined' && typeof items.region_code == 'undefined') {
				$('coldGrid').show();
			}
			if(debug){console.log('state set to: '+userDataHash.get('DCSext.wt_aka_region_code')+' dma set to: '+userDataHash.get('DCSext.wt_aka_dma'))}
		}
		else {
			if(debug){console.log('no override')}
			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(debug){console.log('got geo info from request')}
			//alert(userDataHash.get('DCSext.wt_aka_region_code'));
			if(typeof userDataHash.get('DCSext.wt_aka_region_code') != 'undefined') {
				this.setStateBucket(userDataHash.get('DCSext.wt_aka_region_code'));
				existingCustomerType = 2;
			}
			if(this.getRegion() != '') {
				this.parseCookies();
				this.flipGrid('warmGrid','coldGrid');
			} else {
				$('coldGrid').show();
			}
		} else {
			this.parseCookies();
		}
	}	
	this.determineGreenStatus = function() {
		switch(pageType) {
			case 'watcher' :
				if(debug){console.log('ptype: watcher')}
				greenDMA.each(function(item) {
					if(debug){console.log('curr. item: ' + item)}
					if(item == userDataHash.get('DCSext.wt_aka_dma')) {
						if(debug){console.log('found item')}
						userDataHash.set('isUverseGreen', true);
						if(accountType != 'U') {
							uverseEligible = 'UG';
							if(debug){console.log('doing header');}
							doStatusHeadingInjection('headingUV');
							if(debug){console.log('did header');}
						}
						if(debug){console.log('is uverse green');}
					} 
				});
				if(typeof userDataHash.get('isUverseGreen') == 'undefined') {
					userDataHash.set('isUverseGreen', false);
					uverseEligible = 'UR';
					doStatusHeadingInjection('headingATV');
					if(debug){console.log('is uverse red')}
				}
			break;
			case 'surfer' :
				// surfer goes here
			break;
			case 'talker' :
				// talker goes here
			break;
			case 'bundles' :
				// bundles goes here
			break;
			default:
				alert('pageType not defined properly');
		}
	}	
	this.setContentItems = function(userType) {
		//if(debug)alert(userType);
		var contentItemsForUser = this.getContentHash();
		var isValidType = validTargetCodes.indexOf(userType);
		if(isValidType == -1) {
			userType = 1;
		}
		if(userType != 1 && region != 'OF') {
			contentItemsForUser.set('marquee1', pageType + '_' + userType + '_marquee1');
			contentItemsForUser.set('slot1', pageType + '_' + userType + '_slot1');
			contentItemsForUser.set('slot2', pageType + '_' + userType + '_slot2');
			contentItemsForUser.set('slot3', pageType + '_' + userType + '_slot3');
			contentItemsForUser.set('slot4', pageType + '_' + userType + '_slot4');
			//contentItemsForUser.set('slot5', pageType + '_' + userType + '_slot5');
			if(debug) {
				console.log('usertype: '+userType);
				console.log(contentItemsForUser.get('marquee1'));
				console.log(contentItemsForUser.get('slot1'));
				console.log(contentItemsForUser.get('slot2'));
				console.log(contentItemsForUser.get('slot3'));
				console.log(contentItemsForUser.get('slot4'));
				//console.log(contentItemsForUser.get('slot5'));
			}
		} else if(region == 'OF') {
			contentItemsForUser.set('OFContent_Slot1', 'watcher_OF_slot1.html');
			contentItemsForUser.set('OFContent_Slot2', 'slot2/watcher_OF_slot2.html');
			contentItemsForUser.set('OFContent_Slot3', 'slot2/watcher_1_slot2.html');
			contentItemsForUser.set('OFContent_Slot4', 'slot3/watcher_1_slot3.html');
			$('warmGrid').hide();
			$('coldGrid').hide();
			$('OFContent').show();
			doStatusHeadingInjection();
			$('ld').hide();
		} else if(userType == 1 || userType == '1') {
			$('coldGrid').show();
		}
	}
	this.getContentHash = function() {
		return contentItems;
	}
	this.getContentItems = function() {
		var reqURI;
		var ajaxUpd;
		var found;
		var subst;
		contentItems.each(function(pair) {
			if(!pair.key.include('OFContent_')) {
				reqURI = contentDropletRequestURL + pair.value;
				if(pair.key == 'marquee1') {
					ajaxUpd = new Ajax.Updater(pair.key,reqURI, {method: 'get', evalScripts: 'true'});
				} else {	
					ajaxUpd = new Ajax.Updater(pair.key,reqURI, {method: 'get'});
				}
			} else {
				reqURI = teamsiteDirectRequestURL + pair.value;
				if(pair.key == 'OFContent_Slot1') {
					reqURI = '/homepage/' + pair.value;
				}	
				ajaxUpd = new Ajax.Updater(pair.key,reqURI, {method: 'get'});
			}
		});
	}
	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;
	}	
	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;
	    }
	  	if(debug){console.log('parsed: '+name)}
	  	return unescape(dc.substring(begin + prefix.length, end));
	}
	this.parseCookie = function(cookieToParse) {
		if(debug){console.log('parsing: '+cookieToParse)}
		var cookieCtr = 0;
		var myCookie = this.getCookie(cookieToParse);
		var pRegion = this.getRegion();
		if( myCookie != null) {
			switch(cookieToParse) {
				case 'attPersistantLocalization' :
					if(debug){console.log('read CLT cookie')}
					if($('warmGrid').style.display == 'none') {
						this.flipGrid('warmGrid','coldGrid');
					}
					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);
						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(accountType == '') {existingCustomerType = 2}
						}
						var localizedDMA = contentArray[4].substring(4);
						if(localizedDMA && localizedDMA != userDataHash.get('DCSext.wt_aka_dma')) {
							userDataHash.set('DCSext.wt_aka_dma', localizedDMA);
						}
					}
				break; 
				case 'colam_ctn' :
					if(this.isNumeric(myCookie.substr(0, 9))) {
						userDataHash.set('olam', true);
						cookieCtr++;
						accountType = accountType + 'M';
					}
				break;  
				case 'uvp_env' :
					if(debug){console.log('in uvp')}
					userDataHash.set('uverse', true);
					cookieCtr++;
					accountType = 'U';
					doStatusHeadingInjection('headingEC');
					uverseEligible = '';
				break; 
			}
			if(cookieCtr > 0 && accountType != '') {
				existingCustomerType = 3;
			}
		}
	}
	this.parseCookies = function() {
		var cookieList = new Array('attPersistantLocalization', 'uvp_env');
		if(debug){console.log('in parse cookies')}
		for(i = 0; i < cookieList.size(); i++) {
			this.parseCookie(cookieList[i]);
		}
		this.determineGreenStatus();
		this.setContentItems(this.getUserScheme());
	}
	
	this.runWT = function() {
		setTimeout('dcsMain()', 3000);
	}
}