/**
 * Copyright 2006, Internet Broadcasting Systems. All Rights Reserved.
 * Version:   $Name: REL_2_40_3 $
 * ID:        $Id: Localization.js,v 1.45 2007/04/09 19:51:16 breisinger Exp $
*/

using("nbcsp");
/**
 * Localization
 * Data and methods for localization
 *
 * Uses XMLHTTP connection to Tribune via Akamai (/localization/) for Providers(lineups) and affiliates by zip code
 *
 * @ prototype.js
**/

nbcsp.Localization = {
	debug:false,
	stationlistURL:'/portal/site/nbcsports/template.BINARYPORTLET/sportsontv/?javax.portlet.tpst=301f6ef80937cfe0818e6c10493c2d04_ws_BI&javax.portlet.prp_301f6ef80937cfe0818e6c10493c2d04_stationid=',
	//stationlistURL:'/staticnbcsports/localization/js/stationlist/detail.js',
	//affiliateWidgetId:'14158',
	affiliateWidgetId:'1122876',
	affiliateImageIndexID:'96475',
	affiliateAttempt:0,
	states:[['Alabama','AL'],['Alaska','AK'],['Arizona','AZ'],['Arkansas','AR'],['California','CA'],['Colorado','CO'],['Connecticut','CT'],['Delaware','DE'],['District of Columbia','DC'],['Florida','FL'],['Georgia','GA'],['Guam','GU'],['Hawaii','HI'],['Idaho','ID'],['Illinois','IL'],['Indiana','IN'],['Iowa','IA'],['Kansas','KS'],['Kentucky','KY'],['Louisiana','LA'],['Maine','ME'],['Maryland','MD'],['Massachusetts','MA'],['Michigan','MI'],['Minnesota','MN'],['Mississippi','MS'],['Missouri','MO'],['Montana','MT'],['Nebraska','NE'],['Nevada','NV'],['New Hampshire','NH'],['New Jersey','NJ'],['New Mexico','NM'],['New York','NY'],['North Carolina','NC'],['North Dakota','ND'],['Ohio','OH'],['Oklahoma','OK'],['Oregon','OR'],['Pennsylvania','PA'],['Rhode Island','RI'],['South Carolina','SC'],['South Dakota','SD'],['Tennessee','TN'],['Texas','TX'],['Utah','UT'],['Vermont','VT'],['Virgin Island','VI'],['Virginia','VA'],['Washington','WA'],['West Virginia','WV'],['Wisconsin','WI'],['Wyoming','WY']],
	affs:[],
	affiliate:{},
	loaded:false,
	tempAff:{},
	lineuplist:[],
	afflist:[],
	badlineupids:['4DTV:-', 'AFN:-', 'C-BAND:-'],
	stateColumnCount:5,
	rootElement:'localization',
	zipbasedrootelement:'zipcodelocalization',
	status:'not',
	initEvents:[	],
	aff:function (a,b,c,d,e,f,g,h,i,j,k,l,m,n){
		var thisaff = new Object();
		var afflist = nbcsp.Localization.affs
		thisaff.calls = a; thisaff.locto = b; thisaff.unique = c; thisaff.show = d; thisaff.dma = e; thisaff.satellites = f; thisaff.tz = g; thisaff.st = h; thisaff.zip = i; thisaff.pname = j; thisaff.dname = k; thisaff.stationid = l; thisaff.provider = m; thisaff.shopLink = n;
		thisaff.affectedStates=thisaff.st
		thisaff.position = afflist.length;
		thisaff.parent = false;
		thisaff.logocalls = thisaff.calls;
		thisaff.status = 'partial';
		thisaff.method = 'standard';
		thisaff.display = function(){	
			return '<span><img src="/images/affiliates/' + this.logocalls.toLowerCase() + '/affiliatelogo_small_' + this.logocalls.toLowerCase() + '.jpg" width="70" height="70" border="1" alt="'+this.dname+'" /><b>'+this.dname+'</b></span>'
		}
		afflist[afflist.length] = thisaff;
	},
	showError:function(err) {
		var errors=[
			function(){return 'Zip code "'+nbcsp.Localization.tempAff['zip'] + '" is not valid'},
			function(){return 'You have not yet selected an Affiliate'}
		];
		if($('loc_error')){
			$('loc_error').innerHTML = errors[err]();
			$('loc_error').style.display = 'block';
		}
		if(err == 0){
			if($('loc_enterzip').style.display == 'block'){
				$('zip').focus();
				$('zip').select();
			} else {
				$('newzip').focus();
				$('newzip').select();
			}
		}
	},
	clearError:function() {
		if($('loc_error')){
			$('loc_error').innerHTML = '';
			$('loc_error').style.display = 'none';
		}
	},
	loadStationData:function(whendone){
		var stationlist = new Ajax.Request(
			this.stationlistURL,
			{
				method: 'get', 
				onComplete:function(r){
					eval(r.responseText);
					var rollups = [];
					/* affsbycall is a lookup table for affilates that stores the index of the affilate in the affs array for the call letters */
					nbcsp.Localization.affsbycall = [];
					nbcsp.Localization.affs.each(function(a){
						/*append temporary list of affiliates by callletters with currrent affiliate*/
						nbcsp.Localization.affsbycall[a.calls] = a.position;
						if(a.calls != a.locto){
							/* if this affiliate localizes to a different affiliate add it to the list of rolled up affilaites */
							rollups[rollups.length] = a;
						}
					});
					/* go through the rollups and set their parent value to the parent station */
					rollups.each(function(a){
						a.parent = nbcsp.Localization.affsbycall[a.locto];
						a.logocalls = nbcsp.Localization.affs[nbcsp.Localization.affsbycall[a.locto]].calls;
					});
					nbcsp.Localization.loaded = true;
					if(typeof whendone == 'function') whendone();
				}
			}
		);
	},
	init:function(){
		this.runInitEvents();
		if(this.status != 'not' && $('getlocalfooterlink'))$('getlocalfooterlink').innerHTML = 'Update Localization Preferences';
		if($(this.zipbasedrootelement)) {
			var steps=$('loc_progress').getElementsByTagName('span');
			steps[0].onclick=function() {
				nbcsp.Localization.showStep(1);
			}
			steps[1].onclick=function() {
				nbcsp.Localization.showStep(2);
			}
			if(this.status != 'not') {
				$('loc_currentsettings').style.display = 'block';
				var afflogo = document.createElement('img');
				afflogo.src='/images/affiliates/'+this.affiliate.calls.toLowerCase()+'/affiliatelogo_large_'+this.affiliate.calls.toLowerCase()+'.jpg';
				afflogo.align = 'absmiddle';
				var affname = document.createElement('span');
				affname.innerHTML = this.affiliate.dname;
				var changelink = $('changelink');
				changelink.onclick = function() {
					nbcsp.Localization.clearCookie(); 
					nbcsp.Localization.init();
				}
				var curraffiliate = $('curraffiliate');
				curraffiliate.appendChild(afflogo);
				curraffiliate.appendChild(affname);
			} else {
				buttons = $(this.zipbasedrootelement).getElementsByTagName('button');
				for(var b=0; b<buttons.length; b++){
					buttons[b].onmousedown = function(){
						Element.addClassName(this, 'down');
					}
					buttons[b].onmouseover = function(){
						Element.addClassName(this, 'over');
					}
					buttons[b].onmouseout = function(){
						Element.removeClassName(this, 'over');
						Element.removeClassName(this, 'down');
					}
					buttons[b].onmouseup = function(){
						Element.removeClassName(this, 'down');
					}
				}

				$('loc_currentsettings').style.display = 'none';
				/* Get the station data and once it's loaded display the First step in localization */
				this.loadStationData(function() {
						$('loc_enterzip').style.display = 'block';
						$('loc_enterzip').getElementsByTagName('input')[0].onclick=function() {
							if(this.value.toLowerCase() == 'enter your zip code') this.value='';
						}
						$('loc_enterzip').getElementsByTagName('input')[0].onkeypress=function(e) {
							var code = (e && e.which)?e.which:event.keyCode;
							if(code == 13) {
								var getaffilates = nbcsp.Localization.getLineupsByZip($('zip').value);
								return false;
							} else {
								return true;
							}
						}
						$('loc_enterzip').getElementsByTagName('button')[0].onclick=function() {
							var getaffilates = nbcsp.Localization.getLineupsByZip($('zip').value);
							return false;
						}
						$('loc_selectprovider').getElementsByTagName('button')[0].onclick=function() {
							var getaffilates = nbcsp.Localization.getLineupsByZip($('newzip').value);
							return false;
						}
						$('loc_selectprovider').getElementsByTagName('input')[0].onkeypress=function(e) {
							var code = (e && e.which)?e.which:event.keyCode;
							if(code == 13) {
								var getaffilates = nbcsp.Localization.getLineupsByZip($('newzip').value);
								return false;
							} else {
								return true;
							}
						}
						if(nbcsp.qsdata['zip'] && typeof nbcsp.qsdata['zip'] != 'function') {
							$('loc_enterzip').value = nbcsp.qsdata['zip'];
							nbcsp.Localization.getLineupsByZip(nbcsp.qsdata['zip']);
						}
				});
			}
		}else if($(this.rootElement)){
			if(this.status != 'not') {
				/* Build display of current affiliate selected */
				$('localization').getElementsByTagName('h2')[0].innerHTML = 'You are currently associated with the following NBC TV Station:';
				var curraffiliate = document.createElement('div');
				curraffiliate.className = 'curraffiliate';
				var afflogo = document.createElement('img');
				afflogo.src='/images/affiliates/'+this.affiliate.calls.toLowerCase()+'/affiliatelogo_large_'+this.affiliate.calls.toLowerCase()+'.jpg';
				afflogo.align = 'absmiddle';
				var affname = document.createElement('span');
				affname.innerHTML = this.affiliate.dname;
				var changelink = document.createElement('div');
				changelink.style.marginTop = '20px';
				changelink.innerHTML = '<a href="#" onclick="return false;">To select a different NBC TV Station, click here</a>';
				changelink.onclick = function() {
					nbcsp.Localization.clearCookie(); 
					nbcsp.Localization.init();
				}
				curraffiliate.appendChild(afflogo);
				curraffiliate.appendChild(affname);
				curraffiliate.appendChild(changelink);
				$('loctop').appendChild(curraffiliate);
			} else {
				/* GEt the station data and once it's loaded display the map and the pulldown */
				$('loctop').innerHTML = '<b style="color:#f00;">Loading Station Data....</b>';
				this.loadStationData(function() {
					$('loctop').innerHTML = '<OBJECT style="float:right;" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" WIDTH="680" HEIGHT="360" id="USStates">'
						+'<PARAM NAME="movie" VALUE="/_public/swf/sports_localization_map.swf" />'
						+'<PARAM NAME="AllowScriptAccess" VALUE="always" />'
						+'<PARAM NAME="quality" VALUE="high" />'
						+'<PARAM NAME="bgcolor" VALUE="#FFFFFF" />'
						+'<PARAM NAME="wmode" VALUE="#transparent" />'
						+'</OBJECT>';
					nbcsp.Localization.buildStatePulldown();
				});
				return true;
			}
		}
	},
	addInitEvent:function(f) {
		if(typeof f == 'function'){
			nbcsp.Localization.initEvents[nbcsp.Localization.initEvents.length] = f;
		}
	},
	runInitEvents:function(){	
		for(a=0; a<nbcsp.Localization.initEvents.length; a++) {
			nbcsp.Localization.initEvents[a]();
		}
	},
	/* DEPRECATED */
	showAffiliiateLogo:function(elem) {
		var str = '<div id="getlocallogo" class="clearfix"><a href="/getlocal/"><img class="affiliateLogo" src="/images/structures/misc/localization_left.gif" width="135" height="70" border="0" alt="GET LOCAL!" /></a></div>';
		if(!elem){
			document.write(str);
		} else {
			$(elem).innerHTML = str;
		}
	},
	/* DEPRECATED */
	showAffiliiateLinks:function() {
	},
	buildStateList:function(){
		$('locbottom').innerHTML = '';
		var statelist = document.createElement('ul');
		statelist.className = 'statelist';
		statelist.id='states';
		for(var s=0; s<this.stateColumnCount; s++){
			statelist.appendChild(document.createElement('span')).className='fauxListCol';
		}
		$('locbottom').appendChild(statelist);
		var columns = $('states').getElementsByTagName('span');
		for (var s=0; s<this.states.length; s++){
			var thisstate = document.createElement('li');
			var thisstateA = document.createElement('a');
			thisstateA.href='javascript:return false;';
			thisstateA.onclick=function(){
				var self = nbcsp.Localization
				self.buildAffList(this.getAttribute('statecode'));
				$('locbottom').style.display = 'none';
				return false;
			}
			thisstateA.innerHTML = this.states[s][0];
			thisstateA.setAttribute('statecode' ,this.states[s][1]);
			thisstate.appendChild(thisstateA);
			columns[Math.floor(s/(this.states.length/columns.length))].appendChild(thisstate);
		}
	},
	buildStatePulldown:function(){
		$('locstates').innerHTML = '';
		var statelist = document.createElement('select');
		statelist.onchange = function(){
			var self = nbcsp.Localization
			self.buildAffList(this.options[this.options.selectedIndex].value);
			return false;			
		}
		var topoption = document.createElement('option');
		topoption.innerHTML = 'SELECT A STATE';
		statelist.appendChild(topoption);
		for (var s=0; s<this.states.length; s++){
			var thisstate = document.createElement('option');
			thisstate.innerHTML = this.states[s][0];
			thisstate.value = this.states[s][1];
			statelist.appendChild(thisstate);
		}
		$('locstates').appendChild(statelist);
	},
	getAffsByState:function(st){
		var afflist = this.affs;
		var stateaffs = new Array();
		for (a=0; a<afflist.length; a++){
			if(afflist[a].affectedStates.toLowerCase().indexOf(st.toLowerCase()) != -1 && afflist[a].show.toLowerCase() != 'no') stateaffs[stateaffs.length] = afflist[a];
		}
		/* SORT STATEAFFS BEFORE RETURNING */
		stateaffs = stateaffs.sort(function(a,b){
			adata = a.dname;
			bdata = b.dname;
			if (adata > bdata) {
			   return 1; 
			} else if(adata < bdata) {
			   return -1; 
			} else {
				return 0;
			}
		});
		return stateaffs;
	},
	buildAffList:function(shortlist){
		if(typeof shortlist == 'string') shortlist = this.getAffsByState(shortlist);
		$('loctop').innerHTML = '';
		var desc = document.createElement('h2');
		desc.innerHTML = 'Click on your local NBC station below';
		$('loctop').appendChild(desc);
		var affSelect = document.createElement('ul');
		for (var s=0; s<shortlist.length; s++){
			var thisaff = document.createElement('li');
			thisaff.setAttribute('pointer' ,shortlist[s].position);
			thisaff.onmouseover = function(e){
				this.style.textDecoration = 'underline'
			}
			thisaff.onmouseout = function(e){
				this.style.textDecoration = 'none'
			}
			thisaff.onclick=function(){
				var self = nbcsp.Localization;
				var pointer = this.getAttribute('pointer');
				self.affiliate = (self.affs[pointer].parent)?self.affs[self.affs[pointer].parent]:self.affs[pointer];
				self.setCookie({method:'manual'});
				/* TODO: This location should be configurable */
				if(document.referrer && document.referrer.toLowerCase().indexOf('nbcsports') != -1) {
					if(document.referrer.indexOf('/tvlistings/') != -1){
						/* hack to ensure that the new page gets the values from the new cookie */
						document.location.href= '/tvlistings/index.html';
					} else {
						document.location.href=document.referrer;
					}
				} else {
					document.location.href='/portal/site/nbcsports/';
				}
				return false;
			}
			thisaff.innerHTML=shortlist[s].display();
			affSelect.appendChild(thisaff);
		}
		$('loctop').appendChild(affSelect);
		$('localization').getElementsByTagName('h2')[0].innerHTML = 'Please select the NBC station in your hometown.<br />Stations are listed by the state, if you cannot find what you are looking for, select another state:';
	},
	showStep:function(step){
		var stepclasses = ['', 'first', 'second', 'third', 'third'];
		nbcsp.Localization.tempAff['selectedAffiliate'] = null;
		var steps =document.getElementsByClassName('loc_step');
		$('loc_progress').className = stepclasses[step];
		if(step < 5) {
			for(s =0; s<steps.length; s++) {
				steps[s].style.display = 'none';
			}
			steps[step].style.display = 'block';
		}
	},
	getLineupsByZip:function(z){
		if(z){ /* test z to ensure its a valid zip code?? */
			this.tempAff.zip = z;
			$('newzip').value = z;
			var lineups = new Ajax.Request(
				'/esihook_trb/nbcsports/servlet?zipcode='+z,
				{
					method: 'get', 
					onComplete:function(r){
						var satprovs = {localdirectv:false, localdish:false};
						var errors = r.responseXML.getElementsByTagName('error');
						if(errors.length > 0) {
							nbcsp.Localization.showError(nbcsp.Localization.getTextContent(errors[0]));
						}
						var providers = r.responseXML.getElementsByTagName('lineupItem');
						if(providers.length > 0){
							nbcsp.Localization.tempAff.city = r.responseXML.getElementsByTagName('localization')[0].getAttribute('city');
							nbcsp.Localization.tempAff.state = r.responseXML.getElementsByTagName('localization')[0].getAttribute('state');
							$('loc_cable').innerHTML = '';
							$('loc_satellite').innerHTML = '';
							$('loc_localbroadcast').innerHTML = '';
							nbcsp.Localization.showStep(2);
							for(p=0; p<providers.length; p++){
								/* NEED TO ADD A SORT AND FILTER OF THESE RESULTS PRIOR TO RENDERING */
								/* Create DOM element for display of the current lineup item */
								var lineupEl = document.createElement('li');
								lineupEl.onmouseover = function(){
									this.className = 'over';
								}
								lineupEl.onmouseout = function(){
									this.className = '';
								}
								lineupEl.onclick = function(){
									nbcsp.Localization.tempAff['provider'] = this.lineupid;
									nbcsp.Localization.tempAff['providername'] = this.title;
									/* IF THE LINEUP ID IS A NATIONAL SATTELITE PROVIDER GET AFFILIATES FOR LOCAL BROADCAST */
									var lidToSend = (this.lineupid == 'DITV:-' || this.lineupid == 'ECHOST:-' )? 'PC:'+nbcsp.Localization.tempAff.zip:this.lineupid;
									nbcsp.Localization.getaffiliatesBylineupid(lidToSend);
								}
								/* Create a new object and add it to the list of lineups in the Localization object */
								var thislineup = new Object();
								thislineup.name = nbcsp.Localization.getTextContent(providers[p].getElementsByTagName('name')[0]);
								thislineup.device = nbcsp.Localization.getTextContent(providers[p].getElementsByTagName('device')[0]);
								thislineup.location = nbcsp.Localization.getTextContent(providers[p].getElementsByTagName('location')[0]);
								thislineup.id = providers[p].getAttribute('lineupId');
								thislineup.displaydevice = (thislineup.device.toLowerCase().indexOf('digital') != -1)?' '+thislineup.device:'';
								if (thislineup.name.toLowerCase().indexOf('dish') == 0 && thislineup.id != 'ECHOST:-') satprovs.localdish = true;
								if (thislineup.name.toLowerCase().indexOf('directv') == 0 && thislineup.id != 'DITV:-') satprovs.localdirectv = true;
								lineupEl.id = thislineup.id;
								lineupEl.lineupid = thislineup.id;
								lineupEl.title = thislineup.name;
								lineupEl.innerHTML = thislineup.name+ thislineup.displaydevice + ' (' +thislineup.location + ')';
								if(nbcsp.Localization.badlineupids.join(',').indexOf(thislineup.id) == -1){
									if(thislineup.device.toLowerCase().indexOf('cable') != -1 || thislineup.device.toLowerCase().indexOf('digital') != -1){
										$('loc_cable').appendChild(lineupEl);
									} else if(thislineup.device.toLowerCase().indexOf('satellite') != -1) {
										$('loc_satellite').appendChild(lineupEl);
									} else if(thislineup.device.toLowerCase().indexOf('local broadcast') != -1) {
										$('loc_localbroadcast').appendChild(lineupEl);
									}
								}
							}
							if($('loc_cable').getElementsByTagName('li').length == 0) {
								$('loc_cableheader').style.display = 'none';
							} else {
								$('loc_cableheader').style.display = 'inline';
							}
							if(satprovs.localdish && $('ECHOST:-')) $('loc_satellite').removeChild($('ECHOST:-'));
							if(satprovs.localdirectv && $('DITV:-')) $('loc_satellite').removeChild($('DITV:-'));
						}
						/* set the users zip code to the cookie value not the value from the dataset */
					}
				}
			);
		}
		return true;
	},
	getaffiliatesBylineupid:function(l){
		$('loc_finish').onclick=function(){	
			var lzn = nbcsp.Localization;
			if(typeof lzn.tempAff['zip'] != 'undefined' && typeof lzn.tempAff['provider'] != 'undefined' && typeof lzn.tempAff['calls'] != 'undefined'){
				lzn.setCookie({status:'full', method:'manual', zip:lzn.tempAff['zip'], provider:lzn.tempAff['provider']});
				if(document.referrer && document.referrer.toLowerCase().indexOf('nbcsports') != -1) {
					if(document.referrer.indexOf('/tvlistings/') != -1){
						/* hack to ensure that the new page gets the values from the new cookie  TODO: REGEX to replace values in request */
						document.location.href= '/tvlistings/index.html?crf='+Math.floor(Math.random(1)*1000000);
					} else {
						document.location.href=document.referrer;
					}
				} else {
					document.location.href='/portal/site/nbcsports/';
				}
			} else {
				lzn.showError(1);
			}
			return false;
		}
		// REMOVE OLD ROWS IN THE TABLE
		var oldrows = $('affiliatetable').getElementsByTagName('tr');
		for(var r=oldrows.length-1; r>0; r--){
			oldrows[r].parentNode.removeChild(oldrows[r]);
		}
		
		var affiliates = new Ajax.Request(
			'/esihook_trb/nbcsports/servlet?lineupId='+l + '&affiliate=NBC+Affiliate',
			{
				method: 'get', 
				onComplete:function(r){
					var affiliates= r.responseXML.getElementsByTagName('stationItem');
						var lzn = nbcsp.Localization;
						var affiliatelist = [];
						/* NEED TO ADD A SORT AND FILTER OF THESE RESULTS PRIOR TO RENDERING */
						for(var a=0; a<affiliates.length; a++) {
							var affcalls = lzn.getTextContent(affiliates[a].getElementsByTagName('callSign')[0]).substring(0,4);
							if(typeof lzn.affsbycall[affcalls] == 'undefined' && typeof lzn.affsbycall[affcalls.substring(0,3)] != 'undefined') {
								affcalls = affcalls.substring(0,3);
							}
							if(typeof lzn.affsbycall[affcalls] != 'undefined') {
								/* Get Some Infor From The XML */
								var affsationid = lzn.getTextContent(affiliates[a].getElementsByTagName('stationNumber')[0]);
								var affchannel = lzn.getTextContent(affiliates[a].getElementsByTagName('channel')[0]);
								
								/* Update display with the values from the temporary object */
								$('tempzip').innerHTML = lzn.tempAff.zip;
								$('tempcity').innerHTML = lzn.tempAff.city+', '+lzn.tempAff.state;
								$('tempprovider').innerHTML = lzn.tempAff.providername;

								var affiliateObject =  lzn.affs[lzn.affsbycall[affcalls.toUpperCase()]];							
								var affimgcalls =  affiliateObject.logocalls;
								var affdma =  affiliateObject.dma;
								var affname =  affiliateObject.pname;
								var affdisplay =  affiliateObject.show;

								if((affchannel.indexOf('-') != -1 || affchannel < 80) && affdisplay.toLowerCase() != 'no') {
									var tablelength = $('affiliatetable').getElementsByTagName('tr').length;
									var newrow = $('affiliatetable').insertRow(tablelength);
									newrow.stationid = affsationid;
									newrow.affiliate = (affiliateObject.parent)? lzn.affs[affiliateObject.parent] : affiliateObject;
									newrow.calls = newrow.affiliate.calls;
									newrow.onmouseover=function(){Element.addClassName( this , 'over' );}
									newrow.onmouseout=function(){Element.removeClassName( this , 'over' );}
									newrow.onclick=function(){
										var lzn = nbcsp.Localization;
										/* Update Relevant Display Elements */
										if(lzn.tempAff['selectedAffiliate']) Element.removeClassName( lzn.tempAff['selectedAffiliate'] , 'selected' );
										Element.addClassName( this , 'selected' );
										$('loc_finish').className = 'active';
										/* Update Local Data Models */
										lzn.tempAff['calls'] = this.calls;
										lzn.affiliate = this.affiliate;
										lzn.tempAff['selectedAffiliate'] =this;
									}
									var colone = newrow.insertCell(0);
									colone.className = 'checkbox';
									colone.innerHTML ='';
									var coltwo = newrow.insertCell(1);
									coltwo.className = 'station';
									coltwo.innerHTML ='<img class="stationlogo" src="/images/affiliates/' + affimgcalls.toLowerCase() + '/affiliatelogo_small_' + affimgcalls.toLowerCase() + '.jpg" width="70" height="70" align="absmiddle"/>'+ affname;
									var colthree = newrow.insertCell(2);
									colthree.innerHTML =affchannel;
									var colfour = newrow.insertCell(3);
									colfour.innerHTML =affdma;
								}
							}
						}
						
						// IF THERE ARE NO ELEMENTS IN THE RESULTS ADD ONLY THE LOCAL BROADCAST
						if($('affiliatetable').getElementsByTagName('tr').length == 0) {
							lzn.affiliateAttempt++;
							if(lzn.affiliateAttempt == 1){
								/* Get the data for the local broadcast affilaites but do not change the provider value in the tempAff */
								lzn.getaffiliatesBylineupid('PC:'+lzn.tempAff['zip']);
								return;
							}
						}
						// IF THERE IS NOW ONLY ONE ROW IN THE LIST MAKE IT SELECTED
						if($('affiliatetable').getElementsByTagName('tr').length == 2) {
							var affcol = $('affiliatetable').getElementsByTagName('tr')[1];
							affcol.className = 'selected';
							nbcsp.Localization.tempAff['calls'] = affcol.calls;
							nbcsp.Localization.affiliate = affcol.affiliate;
							affcol.className = 'selected';
							nbcsp.Localization.tempAff['selectedAffiliate'] =affcol;
							$('loc_finish').className = 'active';
						}
						nbcsp.Localization.showStep(3);
				}
			}
		);
		return true;
	},
	fixProvider:function(p){
		this.setCookie({
			provider:p,
			method:this.affiliate.method,
			status:this.status
		});
	},
	setCookie:function(mods){
		var mydata = new Object();
		for (var a in this.affiliate){
			if(mods && mods[a]) mydata[a] = mods[a];
			else mydata[a] = this.affiliate[a];
		}
		if(mods['method']) {
			mydata['method']=mods['method'];
			this.affiliate.method = mods['method'];
		}
		if(mods['status']) {
			mydata['status']=mods['status'];
			this.status = mods['status'];
		}
		cString = 'stationid?'+mydata.stationid+'|calls?'+mydata.calls+'|zip?'+mydata.zip+'|tz?'+mydata.tz+'|provider?'+mydata.provider+'|status?'+mydata.status+'|method?'+mydata.method;
		ibsys.Cookies.set('affiliate', cString, '+7300');
	},
	clearCookie:function(){
		ibsys.Cookies.nuke('affiliate');
		this.status = 'not';
		$('localizationstatus').innerHTML = '<a href="/getlocal/"><img class="affiliateLogo" src="/images/structures/misc/localization_left.gif" width="135" height="70" border="0" alt="GET LOCAL!" /></a>';
		if($('getlocallinks')) $('getlocallinks').style.display = 'none';
		if($('getlocalfooterlink'))$('getlocalfooterlink').innerHTML = 'Get Local';
		return true;
	},
	getAffiliate:function(){
		return this.affiliate;
	},
	getCalls:function(){
		if(this.status != 'not') return this.affiliate.calls;
		else return '';
	},
	getStatus:function(){
		return this.status;
	},
	getMethod:function(){
		if (this.status != 'not'){
			return this.affiliate.method;
		}
	},
	setAffiliate:function (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){
		/* called when single affiliate is fetched from server via AJAX JSON request */
		var thisaff = new Object();
		var afflist = nbcsp.Localization.affs;
		/* Set these to the cookie value if it exists*/
		thisaff.calls = a; thisaff.locto = b; thisaff.unique = c; thisaff.show = d; thisaff.dma = e; thisaff.satellites = f; thisaff.tz = g; thisaff.st = h; thisaff.zip = i; thisaff.pname = j; thisaff.dname = k; thisaff.stationid = l; thisaff.provider = m; thisaff.button1text = n; thisaff.button1url = o; thisaff.button2text = p; thisaff.button2url = q; thisaff.shopLink = r;
		this.affiliate = thisaff;
		/* IF THIS IS AN AFFILIATE LOCALIZATION THERE WILL BE NO COOKIE FOR AFFILIATE */
		if(!ibsys.Cookies.get('affiliate')) this.setCookie({method:'affiliate',status:'partial'}); 
	},
	getTextContent:function(el){
		if(el && el.childNodes.length !=0) {
			return el.childNodes[0].nodeValue;
		}else {
			return '';
		}
	},
	callShopLink: function() {
		var url = this.affiliate.shopLink ? this.affiliate.shopLink : "http://www.nbcuniversalstore.com/index.php?v=nbunbcsposup"; 
		ibsys.utils.popUp(url,"width=900,height=700,top=50,left=50,resizable=yes,scrollbars,location=yes,menubar=yes,toolbar=yes,");
	}
};


if(ibsys.Cookies.get('affiliate')){	
	//alert("affiliate cookie found");
} else {
	//alert("affiliate cookie not present");
}
/* POPULATE THE LOCALIZED AFFILIATE IF THERE IS ONE */
if(ibsys.Cookies.get('affiliate')){	
	var cookiedata = new Object();
	var tmp = ibsys.Cookies.get('affiliate').split('|');
	tmp.each(function(a){
		cookiedata[a.split('?')[0]]=a.split('?')[1];
	});
	/* Get the affiliate data via JSON service call */
	var affiliateData = new Ajax.Request(
		nbcsp.Localization.stationlistURL + cookiedata['calls'],
		{
			method: 'get', 
			onComplete:function(r){
				eval(r.responseText);
				/* set the users zip code to the cookie value not the value from the dataset */
				if(cookiedata['status']) nbcsp.Localization.status=cookiedata['status'];
				if(cookiedata['zip']) nbcsp.Localization.affiliate.zip=cookiedata['zip'];
				if(cookiedata['method']) nbcsp.Localization.affiliate.method=cookiedata['method'];
				if(cookiedata['provider']) nbcsp.Localization.affiliate.provider=cookiedata['provider'];
				/* IF the current cookie has an incorrcect value in the provider attribute reset it */
				if(cookiedata['provider'].toLowerCase().indexOf('PC:') == -1 && cookiedata['provider'].toLowerCase().indexOf(':-') == -1 && cookiedata['status'] == 'partial') {
					var newProvID = cookiedata['provider']+':-';
					nbcsp.Localization.fixProvider(newProvID);
				}
			}
		}
	);
	nbcsp.Localization.status=cookiedata['status'];
/*  IF THE URL CONTAINS AN AFFILIATE SET THE USERS AFFILIATE  */
} else if(nbcsp.qsdata['aff']) { 
	var cookiedata = new Object();
	cookiedata['calls'] = nbcsp.qsdata['aff'];
	nbcsp.Localization.status='partial';
	nbcsp.Localization.affiliate.calls=nbcsp.qsdata['aff'];
	var affiliateData = new Ajax.Request(
		nbcsp.Localization.stationlistURL+ nbcsp.qsdata['aff'].toUpperCase(),
		{
			method: 'get', 
			onComplete:function(r){
				eval(r.responseText);
				if(nbcsp.Localization.affiliate.stationid) nbcsp.Localization.setCookie({status:'partial', method:'affiliate'});
			}
		}
	);
}
/*
nbcsp.Localization.addInitEvent(function(){
		document.getElementsByClassName('tv_station_name').each(function(a){if(a.innerHTML.toLowerCase() == nbcsp.Localization.affiliate.calls.toLowerCase()) a.innerHTML = nbcsp.Localization.affiliate.pname});
	}
);
*/
/* BUILD AFFILIATE WIDGET WHEN THE LOCALIZATION OBJECT INITIALIZES */
nbcsp.Localization.addInitEvent(function(){
		var locObj = nbcsp.Localization;
		if(locObj.getStatus() != 'not' && $('swContent'+locObj.affiliateWidgetId)){
			/* wipe out default get local image */
			var oldwidg = document.getElementsByClassName("localizationWidgetParent",$('swContent'+locObj.affiliateWidgetId))[0];
			oldwidg.style.display = "none";
			
			/* BUILD LOCAL LOGO */
			var newAffiliateWidget = ''
			+ '<div class="affiliateWidgetJsRewritten">'
			+ ''
			+ '<span id="localizationstatus">'
			+ '<div class="clearfix" id="getlocallogo">'
			+ '<img width="135" height="70" hspace="0" border="0" alt="'+locObj.getCalls()+'" src="/images/affiliates/' +  locObj.getCalls().toLowerCase() + '/affiliatelogo_large_' + locObj.getCalls().toLowerCase() + '.jpg" class="affiliateLogo"/>'
			+ '</div>'
			+ '<div id="localizedLinks"></div></span>'
		    + '<br style="clear: both;" />'
			+ '</div>';
			$('swContent'+locObj.affiliateWidgetId).innerHTML = newAffiliateWidget + $('swContent'+locObj.affiliateWidgetId).innerHTML;
			/* How should we make this happen...should we rewrite the entire widget in the script or address the elements individually */
			/* $('affiliatepromoimage').style.visibility = 'hidden'; */
					
			/* BUILD BUTTONS */
			var buttonparent = document.createElement('ul');
			buttonparent.id = 'getlocallinks';
			buttonparent.className = 'clearfix';
			$('localizationstatus').appendChild(buttonparent);
			
			var button1 = document.createElement('li');
			var loc = nbcsp.Localization.affiliate.button1url;
			var prefix = (loc.indexOf('http://') == 0)?'':'http://';
			var href = prefix+loc;
			button1.innerHTML = '<a href="' + href + '" target="_blank">' + locObj.affiliate.button1text + "<a>";
			
			var button2 = document.createElement('li');
			var loc = nbcsp.Localization.affiliate.button2url;
			var prefix = (loc.indexOf('http://') == 0)?'':'http://';
			var href = prefix+loc; 
			button2.innerHTML = '<a href="' + href + '" target="_blank">' + locObj.affiliate.button2text + "</a>";
			
			/* var button3 = document.createElement('li');
			button3.innerHTML = '<a href="/nhl/131528/detail.html">NHL on NBC</a>';
			*/	
			buttonparent.appendChild(button1);
			if(locObj.affiliate.button2url != 'N/A') {buttonparent.appendChild(button2);}
			//buttonparent.appendChild(button3);
			
			$('localizedLinks').appendChild(buttonparent);
			
			/* affiliate promo image (went away for redesign)*/
			//$('swContent'+locObj.affiliateWidgetId).innerHTML += '<img id="affiliatepromoimage" border="0" alt="" src=""/>';
			// var lineups = new Ajax.Request(
				// '/_object/'+locObj.affiliateImageIndexID+'/detail.html?rnd='+Math.floor(Math.random(1)*10000000),
				// {
					// method: 'get', 
					// onComplete:function(r){
						// /* IF THE HOTLINE DOES NOT HAVE A URL THIS OPERATION FAILS */
						// var linkurl = locObj.getTextContent(r.responseXML.getElementsByTagName('url')[0]);
						// var indexElements = r.responseXML.getElementsByTagName('co');
						// var selRnd = Math.floor(Math.random(1)*indexElements.length);
						// var theImages = indexElements[selRnd].getElementsByTagName('ibs_image')[0].getElementsByTagName('src');
						// var theHeadline = indexElements[selRnd].getElementsByTagName('headline')[1].firstChild.nodeValue;
						// var theBlurb = indexElements[selRnd].getElementsByTagName('teaser')[1].firstChild.nodeValue;
						// var container = $('swContent'+locObj.affiliateWidgetId);
						// 
						// var newHTML = '<ul class="InBL objList"><li class="InBL"><div class="coImage"><span>'
									// + '<img id="affiliatepromoimage" border="0" alt="" src="' + ibsys.utils.getElementsByAttribute('width','168', 'src', theImages)[0].childNodes[0].nodeValue + '" />'
									// + '</div></span>'
									// + '<div class="coHeadline"><a class="item">' + theHeadline + '</a></div>' 
									// + '<span class="coTeaser">' + theBlurb + '</span></li></ul>';
						// container.innerHTML += newHTML;
// 
						// $('affiliatepromoimage').onclick=function() {document.location.href=linkurl}
						// /* set the users zip code to the cookie value not the value from the dataset */
						// 
					// }
				// }
			// );
			
		}
		if($('swContent'+locObj.affiliateWidgetId)) $('swContent'+locObj.affiliateWidgetId).style.display='block';
	}
);

function buildAffiliateList(st) {
	nbcsp.Localization.buildAffList(st);
}


// Build HTML ELement with attributes (eg.  var errorEl = buildElement('div', [['id', 'locError'],['class', 'error'], ['style','color:#f00;']]);  )
function buildElement(nodename, attributes) { // nodename:string  attributes:array
    var tmpNode = document.createElement(nodename);
    for(var a in attributes)  {
	tmpNode.setAttribute(attributes[a][0], attributes[a][1]);
	if(attributes[a][0] == 'class') tmpNode.setAttribute('className', attributes[a][1]);
    }
    return tmpNode;
}

