/*PROD1*/
$(document).ready(function(){

	/* start init search tabs */
	$("#search-box").tabs({
		cache: true,
		spinner: '',
		fx: { height: '100%' },
		select: function(event, ui) {
			// copy current query to all other queries
			var curr_tab = $('#search-box').tabs('option', 'selected');
			$('#search-box input.squery').each(function(){
				$(this).attr('value',$('#search-box input.squery:eq('+curr_tab+')').attr('value'));
			});
		}
	});
	$("#search-web input.text-input-big").focus();
	$("#search-boxB").tabs({
		cache: true,
		spinner: '',
		fx: { height: '100%' },
		select: function(event, ui) {
			// copy current query to all other queries
			var curr_tab = $('#search-boxB').tabs('option', 'selected');
			$('#search-boxB input.squery').each(function(){
				$(this).attr('value',$('#search-boxB input.squery:eq('+curr_tab+')').attr('value'));
			});
		}
	});
	/* end init search tabs */
	
	ELNK.contest.init();
	initTravelSearch();
	initTvListings();
	initLocalNews();
	initTravelWidget();
	
	// capture theme change events
	$('#theme-changer').change(function(){
		$('#theme-changer option:selected').each(function(){
			setTheme($(this).val());
		});	
	});
	
	// wdgt drag n drop
	if (ELNK.loggedIn) {
		$('#col-wrapper div.column').sortable({
			items: 'div.wdgt:not(.dsmb), #motd-wdgt',
			connectWith: '.column',
			handle: 'h2',
			start: function() {
				window.mw = true;
				removeWdgtScripts();
			},
			stop: function(e, ui) {
				$.ajax({ type: 'POST', url: '/ajax/save', data: ELNK.smb() });
			}
		});	
	}

	// min-max wdgts
	// $(".tools .minmax").click(function() {
	// 		$(this).toggleClass("min");
	// 		$(this).parents(".wdgt:first").find(".wdgt-body").toggle();
	// 	});

	// min-max 'more' channels
	$("#chn-link-max > li:last a").click(function() {
		$(this).parents(".chn-more:first").toggleClass("min");
		$(this).parents("#chn-wdgt").find(".chn-more-links").toggle();
	});

	$("#chn-wdgt ul li a + a").each(function(){
		$(this).addClass('chn-extra');
	});

	// append secure sign-in link
	$('#signin-util').append('<p class="small"><a href="javascript:self.location.href=\'https://\' + self.location.hostname + \'/channel/edit/signin_secure/\';">Secure Sign In</a></p>');

	// event h for help
	$('#elnkHelp').click(function(){
		 window.open('','elnkHelp','width=794,height=510,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,menubar=no,copyhistory=no');
	});

	// add time-stamp to weather header
	$('#weather p:first').prepend(ELNK.timestamp() + '<br/>');
	//loadWidget('news-headlines-wdgt', '/pub/html/jericho_ui_update/modules/news_headlines.html');

	// update the customize link
	if (ELNK.loggedIn) {
		$('#custom-edit a').attr('href', "/channel/edit/layout/" + (parseFloat(ELNK.page) + 1));
	}

	// load mrec
	ELNK.ads.load_mrec();
	
	// load skyscraper
	ELNK.ads.load_sky();

	// legacy call to function for refreshing iframed content
	setIframeTimeout('#mrec-wdgt iframe', 600000);
	setIframeTimeout('#sky-wdgt iframe', 660000);

	ELNK.today = new Date();
	setDateStamps();
	setTimeStamps();
	
if (ELNK.loggedIn) {
	initCollapsedWidgets();
		ELNK.mail.init();
	}
	
	$('#nav h1 a, #footer-nav h1 a').supersleight();
	emRS=new Date();
	
}); // end .ready()

var removeWdgtScripts = function() {
	$('#horoscopes-wdgt script').html('');
	$('#localnews-wdgt script').remove();
	$('#localnews-wdgt iframe').remove();
	$('#theaters-wdgt script').remove();
	$('#theaters-wdgt iframe').remove();
}

/**
 * ELNK object
 * going forward, should use this for all internal vars and helper functions to
 * avoid namespace collisions
 */
var ELNK = {
	'mail': {
		'count': 0,
		'prev_count': 0,
		'soundpath': '/snd/mailsound1.wav',
		'init': function() {
			var prevEmails = $.cookie("elnk_Emails");
			this.prev_count = (prevEmails) ? parseInt(prevEmails) : 0;
			if (this.host && this.email) {
				$.ajax({
					type: "GET",
					url: this.host + "mailCount.json?emailAddress=" + this.email + "&var=emailCount&callback=ELNK.mail.callback",
					dataType: "script"
				});
			}
		},
		'isAlertSoundOn': function() {
			return ($.cookie("mailTruck")) ? parseInt($.cookie("mailTruck")) : 0;
		},
		'playSound': function() {
			var embedCode = '';
			
			if ((this.count != 0) && (this.count != this.prev_count) && (this.isAlertSoundOn() == 1)) {
				if (navigator && navigator.mimeTypes && navigator.mimeTypes["audio/wav"] && (navigator.mimeTypes["audio/wav"].enabledPlugin != null)) {
					if (navigator.appName.indexOf("WebTV") >= 0 ) { 
						embedCode = '<embed src = "' + this.soundpath + '" autostart="true" hidden="true" style="position:absolute;">' + '<bgsound src = "' + this.soundpath + '">';
					} else {
						embedCode = '<embed src = "' + this.soundpath + '" autostart="true" hidden="true" style="position:absolute;">';
					}
				} else if (navigator.appName.indexOf("Netscape") >= 0) {
					embedCode = '<!-- no sound -->'; 
				} else { 
					embedCode = '<bgsound src = "' + this.soundpath + '">'; 
				}
			}
			
			if (embedCode != '') {
				$('#wam-wdgt div.wdgt-section:last').parent().append(embedCode);
			}
		},
		'callback': function() {
			if (typeof(emailCount) != 'undefined' && emailCount != null && emailCount.errorCode == 0) {
				var str = ELNK.mail.count = emailCount.unreadCount;
				var str = '('+str+')';
				$('#lColMt').text(str);
				$('#uNavMt').text(str + ' ');
				
				ELNK.mail.playSound();
				$.cookie('elnk_Emails', ELNK.mail.count, {'domain':ELNK.domain, 'path': '/'});
			}
		}
	},
	'contest': {
		'init': function() {
			this.cookie = $.cookie('contest');
			if (!this.cookie && this.isActive) {
				this.showPromo();
			} else if (this.cookie == 'off') {
				this.isPromoOff = true;
			} else if (this.isActive) {
				this.showWidget();
			}
		},
		'cookie': null,
		'isActive': true,
		'isPromoOff': false,
		'isWidgetOn': false,
		'turnPromoOff': function() {
			this.isPromoOff = true;
			$.cookie("contest", 'off', {'domain':ELNK.domain, 'expires': 200});
		},
		'showPromo': function() {
			if (!this.isPromoOff && this.isActive) {
				$('.contest-promo').show();
				$('.contest-promo .close').click(function() {
					$('.contest-promo').hide();
					ELNK.contest.turnPromoOff();
					return false;
				});
				$('.contest-promo .play').click(function() {
					// inital state: 'on'
					// after selecting from drop down: team id (see changeTeam())
					$.cookie("contest", 'on', {'domain':ELNK.domain, 'expires': 200});
					$('.contest-promo').hide();
					ELNK.contest.showWidget();
				});
			}
		},
		'showWidget': function() {
			$('#contest-wdgt').show();
			var teamid = 7; // default
			if (this.cookie != 'on') {
				teamid = this.cookie;
			}
			domWrite('contest-iframe-w', 'http://earthlink.profootball.upickem.net/profootball/football/SingleGameWidget.asp?teamid='+teamid+'&affid=ELNK');
		},
		'changeTeam': function(teamid) {
			if (teamid > 0) {
				$.cookie("contest", teamid, {'domain':ELNK.domain, 'expires': 200});
				domWrite('contest-iframe-w', 'http://earthlink.profootball.upickem.net/profootball/football/SingleGameWidget.asp?teamid='+teamid+'&affid=ELNK')
			}
		},
		'removeWidget': function() {
			$('#contest-wdgt').hide();
			$.cookie("contest", 'off', {'domain':ELNK.domain, 'expires': 200});
		}
	},
	'ads': {
		'mrec': { 'iframe_url': '', 'link_html': '' },
		'load_mrec': function() {
			$('#mrec-wdgt').append('<iframe src="' + this.mrec.iframe_url + '" width="300" height="250" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no">' + this.link_html + '</iframe>')
		},
		'sky': { 'iframe_url': '', 'link_html': '' },
		'load_sky': function() {
			$('#sky-wdgt').append('<iframe src="' + this.sky.iframe_url + '" width="160" height="600" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no">' + this.link_html + '</iframe>')
		}
	},
	'wdgts': { 'min': {'page1': [],'page2': [] } },
	'theaters': { 'show': []},
	'tvg': { 'isLoaded': false },
	'today': { },
	'getMonthName': function(month) {
		// todo: extend Date object to do this
		var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
		return m_names[month];
	},
	'getTime': function(date) {
		var curr_hour = date.getHours();
		var curr_min = date.getMinutes() + ''; //to string
		var ampm = "pm";
		if (curr_hour < 12) {
			ampm = "am";
		}
		if (curr_hour == 0) {
			curr_hour = '12';
		}
		if (curr_hour > 12) {
			curr_hour = curr_hour - 12;
		}
		if (curr_min.length == 1) {
			curr_min = "0" + curr_min;
		}
		return curr_hour + ':' + curr_min + ampm;
	},
	'timestamp': function() {
		var d = new Date();
		var curr_date = d.getDate();
		var curr_month = d.getMonth();
		return ELNK.getMonthName(curr_month) + ' ' + curr_date + ', ' + d.getFullYear() + ' ' + ELNK.getTime(d);
	},
	'datestamp': function() {
		var d = new Date();
		var curr_date = d.getDate();
		var curr_month = d.getMonth();
		return ELNK.getMonthName(curr_month) + ' ' + curr_date + ', ' + d.getFullYear();
	},
	'smb': function() {
		var wdgt_arr = ['edit.submit=Save+Changes','action=Save+Changes', 'edit.pageTitles.update=' + $('#pers h2').text(), 'edit.pageTitles.update=' + $('#pers h2').text()];
		
		$('#col1 div.wdgt:not(.dsmb)').each(function(){		 
			wdgt_arr.push('edit.layout.page.' + ELNK.page + '.column.1.update=' + (($(this).attr('id').split("-",1).toString()=="motd")?"email":$(this).attr('id').split("-",1).toString()));
			//TODO:  put me back! wdgt_arr.push('edit.layout.page.' + ELNK.page + '.column.1.update=' + $(this).attr('id').split("-",1).toString());
		});
		$('#col2 div.wdgt:not(.dsmb)').each(function(){
			wdgt_arr.push('edit.layout.page.' + ELNK.page + '.column.2.update=' + (($(this).attr('id').split("-",1).toString()=="motd")?"email":$(this).attr('id').split("-",1).toString()));
			//TODO:  put me back! wdgt_arr.push('edit.layout.page.' + ELNK.page + '.column.2.update=' + $(this).attr('id').split("-",1).toString());
		});
		
		return wdgt_arr.join('&');
	}
};
ELNK.host = self.location.hostname;
ELNK.domain = self.location.hostname.substring(self.location.hostname.lastIndexOf(".",(self.location.hostname.length - 5)), self.location.hostname.length);
ELNK.vdomains = ['earthlink.net','corp.earthlink.net','m80apps.com','support.earthlink.net','sprintmail.com','mac.com','mcihispeed.net','startrek.net','mindspring.com','mspg','pipeline.com','ix.netcom.com','sprynet.com','gowebway.com','interserv.com','travelin.com','igc.org','infi.net','infionline.net','zoomnet.net','mtneer.net','ramlink.net','together.net','penn.com','sunlink.net','uplink.net','csrlink.net','ipa.net','radiks.net','rconnect.com','willowtree.com','millcomm.com','salamander.com','powerbank.net','gate.net','joimail.com','aaahawk.com','access4less.net','onemain.com','lightspeed.net','thegrid.net','jps.net','corpmail1.jps.net','corpmail2.jps.net','usit.net','midwest.net','fgi.net','ldd.net','supernet.com','virtual.supernet.com','ezonline.net','cyberia.com','wjtl.net','fm.supernet.com','usmo.com','indy.net','ctlnet.com','mdn.com','early.com','vws1.early.com','tir.com','shianet.org','memphis.magibox.net','accutherm.com','arrow-mo.com','bickbroadcasting.com','bleigh.com','drobrock.com','dstream.net','gray-hunter-stenn.com','grizz.com','hannibalbpw.org','hrhonline.org','huck-fyc.com','khqa.com','mcccomm.com','nemodev.org','nemonet.com','perrymachine.com','pjprinting.com','printexec.com','psbwestquincy.com','quanada.org','roquetteamerica.com','spcgraphics.com','titan-intl.com','rnet.com','capecod.net','virtual.capecod.net','neaccess.net','iag.net','brevard.net','palmnet.net','teleport.com','mcn.net','southwind.net','hit.net','grid.net','cyberia.net','capecode.net','uid.onemain.com','fm.supernet.net','evilla.com','netcom.com','mycidco.com','mailstation.com','mymailstation.com','ionet.net','surfree.com','telepath.com','tiac.net','zebra.net','wolfenet.com','balista.com','comnetcom.net','cmn.net','davesworld.net','doitnow.com','fn.net','futureone.com','inconnect.com','info2000.net','iopener.net','kc.rmi.net','lanminds.com','oneimage.com','ria.net','rmi.net','webzone.net','planetebay.net','abts.net','abtsnet.net','apex.net','alec.net','boone.net','coastalnet.com','digital.net','digitalexp.com','digitalexp.net','edge.net','gibralter.net','greenvillenc.com','ahoskienc.com','ahoskienc.net','albemarlenet.com','creswellnc.com','currituckco.com','elizabethcitync.com','gatesco.com','goldsboronc.net','jamesvillenc.com','plymouthnc.com','ropernc.com','williamstonnc.com','gulf.net','powerh.net','icx.net','ioa.com','a-o.com','cheta.net','ioa.net','internetofamerica.com','kih.net','mpinet.net','intersrv.com','metrolink.net','n-jcenter.com','shelby.net','hickory.net','spartanburg.net','surfsouth.com','surfsouth.net','kleanet.com','tsixroads.com','twave.net','vol.com','voyageronline.net','voy.net','voyageronline.com','elizabethcitync.net','volaris.com','peoplepc.com'];


// set theme name
function setTheme(p_theme) {
	$(document.body).removeClass().addClass(p_theme);
}

// AJAX in a widget into container "p_id" from url "p_url"
var loadWidget = function(p_id, p_url) {
	if (p_id && p_url) {
		$("#" + p_id + ' .wdgt-body').load(p_url);
	} else {
		//alert('no');
	}
}

var setIframeTimeout = function(p_frame, p_delay) {
	$(p_frame).attr('src', $(p_frame).attr('src'));
	if (!p_delay) {
		p_delay = 300000;
	}
	setTimeout("setIframeTimeout('"+p_frame+"',"+p_delay+")", p_delay);
}

var needSignin = function() {
	alert("You need to sign-in to access this feature.");
	$('#email_address').focus().select();
}


// Widget Collapsing
var initCollapsedWidgets = function() {
	if ($.cookie('collapsed_p1')) {
		ELNK.wdgts.min.page1 = $.cookie('collapsed_p1').split(',');
		var elnkWdgtsMinPage1 = $.cookie('collapsed_p1').split(',');
		for (i = 0; i < elnkWdgtsMinPage1.length; i++) {
			collapseWidget(elnkWdgtsMinPage1[i]);
		}
	}
	if ($.cookie('collapsed_p2')) {
		ELNK.wdgts.min.page2 = $.cookie('collapsed_p2').split(',');
		var elnkWdgtsMinPage2 = $.cookie('collapsed_p2').split(',');
		jQuery.each(elnkWdgtsMinPage2, function(index, value){
			collapseWidget(value);
		});
	}
}
var setCollapseCookie = function(wdgt, flag) {
	var cookieName = 'collapsed_p1';
	var minWdgts = ELNK.wdgts.min.page1;
	if (ELNK.page != 0) {
		cookieName = 'collapsed_p2';
		minWdgts = ELNK.wdgts.min.page2;
	}
	if (flag) {
		if (jQuery.inArray(wdgt, minWdgts) < 0) {
			minWdgts.push(wdgt.toString());
		}
	} else {
		if (jQuery.inArray(wdgt, minWdgts) >= 0) {
			minWdgts.splice(jQuery.inArray(wdgt, minWdgts), 1);
		}
	}
	saveCollapseCookies();
}
var collapseWidget = function(wdgt) {
	//todo: remove this functionality and instead use jquery to handle event using selectors on load
	if (wdgt == 'rssnews') { wdgt = 'news' } //todo: fix Id/Keyword in widgetChrome
	$("#" + wdgt + "-wdgt .wdgt-body").toggle('fast', switchMinMaxButton(wdgt));
}
var switchMinMaxButton = function(wdgt) {
	var tImg = $("#" + wdgt + "-wdgt img.collapseImg");
	if ($("#" + wdgt + "-wdgt .wdgt-body").css("display") == "block") {
		//collapse
		tImg.attr('src', '/img/elements/collapse_on.gif');
		setCollapseCookie(wdgt, true);
	} else {
		tImg.attr('src', '/img/elements/collapse_off.gif');
		setCollapseCookie(wdgt, false);
	}
}
var saveCollapseCookies = function() {
	$.cookie("collapsed_p1", ELNK.wdgts.min.page1.join(','), {'domain':ELNK.domain, 'path':'/', 'expires': 256});
	$.cookie("collapsed_p2", ELNK.wdgts.min.page2.join(','), {'domain':ELNK.domain, 'path':'/', 'expires': 256});
}

// start: legacy auth
function isValidDomain(p_domain){
	var vdomains = ",earthlink.net,corp.earthlink.net,m80apps.com,support.earthlink.net,sprintmail.com,mac.com,mcihispeed.net,startrek.net,mindspring.com,mspg,pipeline.com,ix.netcom.com,sprynet.com,gowebway.com,interserv.com,travelin.com,igc.org,infi.net,infionline.net,zoomnet.net,mtneer.net,ramlink.net,together.net,penn.com,sunlink.net,uplink.net,csrlink.net,ipa.net,radiks.net,rconnect.com,willowtree.com,millcomm.com,salamander.com,powerbank.net,gate.net,joimail.com,aaahawk.com,access4less.net,onemain.com, lightspeed.net,thegrid.net,jps.net,corpmail1.jps.net,corpmail2.jps.net,usit.net,midwest.net,fgi.net,ldd.net,supernet.com,virtual.supernet.com,ezonline.net,cyberia.com,wjtl.net,fm.supernet.com,usmo.com,indy.net,ctlnet.com,mdn.com,early.com,vws1.early.com,tir.com,shianet.org,memphis.magibox.net,accutherm.com,arrow-mo.com,bickbroadcasting.com,bleigh.com,drobrock.com,dstream.net,gray-hunter-stenn.com,grizz.com,hannibalbpw.org,hrhonline.org,huck-fyc.com,khqa.com,mcccomm.com,nemodev.org,nemonet.com,perrymachine.com,pjprinting.com,printexec.com,psbwestquincy.com,quanada.org,roquetteamerica.com,spcgraphics.com,titan-intl.com,rnet.com,capecod.net,virtual.capecod.net,neaccess.net,iag.net,brevard.net,palmnet.net,teleport.com,mcn.net,southwind.net,hit.net,grid.net,cyberia.net,capecode.net,uid.onemain.com,fm.supernet.net,evilla.com,netcom.com,mycidco.com,mailstation.com,mymailstation.com,ionet.net,surfree.com,telepath.com,tiac.net,zebra.net,wolfenet.com,balista.com,comnetcom.net,cmn.net,davesworld.net,doitnow.com,fn.net,futureone.com,inconnect.com,info2000.net,iopener.net,kc.rmi.net,lanminds.com,oneimage.com,ria.net,rmi.net,webzone.net,planetebay.net,abts.net,abtsnet.net,apex.net,alec.net,boone.net,coastalnet.com,digital.net,digitalexp.com,digitalexp.net,edge.net,gibralter.net,greenvillenc.com,ahoskienc.com,ahoskienc.net,albemarlenet.com,creswellnc.com,currituckco.com,elizabethcitync.com,gatesco.com,goldsboronc.net,jamesvillenc.com,plymouthnc.com,ropernc.com,williamstonnc.com,gulf.net,powerh.net,icx.net,ioa.com,a-o.com,cheta.net,ioa.net,internetofamerica.com,kih.net,mpinet.net,intersrv.com,metrolink.net,n-jcenter.com,shelby.net,hickory.net,spartanburg.net,surfsouth.com,surfsouth.net,kleanet.com,tsixroads.com,twave.net,vol.com,voyageronline.net,voy.net,voyageronline.com,elizabethcitync.net,volaris.com,";
	var vdomains = ['earthlink.net','corp.earthlink.net','m80apps.com','support.earthlink.net','sprintmail.com','mac.com','mcihispeed.net','startrek.net','mindspring.com','mspg','pipeline.com','ix.netcom.com','sprynet.com','gowebway.com','interserv.com','travelin.com','igc.org','infi.net','infionline.net','zoomnet.net','mtneer.net','ramlink.net','together.net','penn.com','sunlink.net','uplink.net','csrlink.net','ipa.net','radiks.net','rconnect.com','willowtree.com','millcomm.com','salamander.com','powerbank.net','gate.net','joimail.com','aaahawk.com','access4less.net','onemain.com',' lightspeed.net','thegrid.net','jps.net','corpmail1.jps.net','corpmail2.jps.net','usit.net','midwest.net','fgi.net','ldd.net','supernet.com','virtual.supernet.com','ezonline.net','cyberia.com','wjtl.net','fm.supernet.com','usmo.com','indy.net','ctlnet.com','mdn.com','early.com','vws1.early.com','tir.com','shianet.org','memphis.magibox.net','accutherm.com','arrow-mo.com','bickbroadcasting.com','bleigh.com','drobrock.com','dstream.net','gray-hunter-stenn.com','grizz.com','hannibalbpw.org','hrhonline.org','huck-fyc.com','khqa.com','mcccomm.com','nemodev.org','nemonet.com','perrymachine.com','pjprinting.com','printexec.com','psbwestquincy.com','quanada.org','roquetteamerica.com','spcgraphics.com','titan-intl.com','rnet.com','capecod.net','virtual.capecod.net','neaccess.net','iag.net','brevard.net','palmnet.net','teleport.com','mcn.net','southwind.net','hit.net','grid.net','cyberia.net','capecode.net','uid.onemain.com','fm.supernet.net','evilla.com','netcom.com','mycidco.com','mailstation.com','mymailstation.com','ionet.net','surfree.com','telepath.com','tiac.net','zebra.net','wolfenet.com','balista.com','comnetcom.net','cmn.net','davesworld.net','doitnow.com','fn.net','futureone.com','inconnect.com','info2000.net','iopener.net','kc.rmi.net','lanminds.com','oneimage.com','ria.net','rmi.net','webzone.net','planetebay.net','abts.net','abtsnet.net','apex.net','alec.net','boone.net','coastalnet.com','digital.net','digitalexp.com','digitalexp.net','edge.net','gibralter.net','greenvillenc.com','ahoskienc.com','ahoskienc.net','albemarlenet.com','creswellnc.com','currituckco.com','elizabethcitync.com','gatesco.com','goldsboronc.net','jamesvillenc.com','plymouthnc.com','ropernc.com','williamstonnc.com','gulf.net','powerh.net','icx.net','ioa.com','a-o.com','cheta.net','ioa.net','internetofamerica.com','kih.net','mpinet.net','intersrv.com','metrolink.net','n-jcenter.com','shelby.net','hickory.net','spartanburg.net','surfsouth.com','surfsouth.net','kleanet.com','tsixroads.com','twave.net','vol.com','voyageronline.net','voy.net','voyageronline.com','elizabethcitync.net','volaris.com'];
	p_domain = ","+p_domain.toLowerCase()+",";
	var founddomain = (vdomains.indexOf(p_domain)==-1)? false: true;
	if (!founddomain) {
		alert("The email address you entered does not appear to be valid, please check your input and try again.");
	}
	return founddomain;
}
function validateAuth(p_email) {
 var uname = p_email.substring(0, p_email.indexOf("@")).toLowerCase();
 var domain = p_email.substring(p_email.indexOf("@")+1).toLowerCase();
 var isGoodDomain = true;
	$('#signin-form input[name=authUsername]').attr('value', uname);
	if (domain == "mac.com") {
		$('#signin-form input[name=authDomain]').attr('value', 'earthlink.net');
	} else if ($('#signin-form input[name=authDomain]').attr('value').indexOf("igc.org") == -1) {
		$('#signin-form input[name=authDomain]').attr('value', 'conflictnet.org');
	} else if ($('#signin-form input[name=authDomain]').attr('value').indexOf("zoomnet.net") == -1) {
		$('#signin-form input[name=authDomain]').attr('value', 'ianet.net');
	} else if ($('#signin-form input[name=authDomain]').attr('value').indexOf("mspg") == -1) {
		$('#signin-form input[name=authDomain]').attr('value', '');
	}
	$('#signin-form input[name=authDomain]').attr('value', 'earthlink.net');
	//alert("todo: fix this: " + $("#signin-form input[name=authDomain]").attr('value'));
	if (!document.cookie) {
		$("#signin-form").attr('method', 'POST').attr('action', '/msgs/process_error.jsp?eid=0');
	} 

	if (jQuery.inArray(domain.toLowerCase(), ELNK.vdomains) != -1) { //Begin auth tracking code
		if (ELNK.host.indexOf("usaa") > -1) {
			$("#AuthTokenImage").attr("src","/track?id=1031786&add=1&url=http://my.eimg.net/img/x.gif");
		} else if (ELNK.host.indexOf("sprint") > -1) {
			$("#AuthTokenImage").attr("src","/track?id=1031785&add=1&url=http://my.eimg.net/img/x.gif");
		} else {
			$("#AuthTokenImage").attr("src","/track?id=1031784&add=1&url=http://my.eimg.net/img/x.gif");
		}
	} else {
		alert("The email address you entered does not appear to be valid, please check your input and try again.");
		isGoodDomain = false;
		$('#email_address').focus().select();
	}

	return isGoodDomain;
}
// end: legacy auth

// start: search form save local
function gS(f) {
	doPersistLocation(f);
	f.elements["id"].value=searchInputs[currentlyCheckedOption][2];
	toggleInput(
		getElementsByClassName("a","tab_" + currentlyCheckedOption, f)[0],
		currentlyCheckedOption
	);
}
function submitActiveForm(refObj) {
	f = getParentFormElement(refObj);
	if (f) {
		gS(f);
		f.submit();
	} else {
		/* this condition should NEVER happen */
		alert("Please try pressing the \"Search\" Button. ");
	}
}
function setLocalValue(s) {
	$.cookie('localValue',escape(s), {'domain':ELNK.domain, 'expires': 256});
}//setLocalValue
function getLocalValue() {
	return unescape($.cookie('localValue'));
}//getLocalValue
function doPersistLocation(f) {
	if (f && f.near && (v = f.near.value)) {
		setLocalValue(v);
	}
}//doPersistLocation()
function setFormSavedLocation(f) {
	if (f && f.near) {
		f.near.value = getLocalValue();
	}
}
// end: search form save local


// start: travel widget
/* Expedia JS */
var _currentLOB = "flight";

function updateLOB() {
	var _newLOB;
	var f=document.getElementById("lobForm");

	for (i=0; i<f.lob.length; i++)
	{   if(f.lob[i].checked)    _newLOB = f.lob[i].value;   }

	document.getElementById(_currentLOB + "Div").style.display = "none";
	document.getElementById(_newLOB + "Div").style.display = "block";
	_currentLOB = _newLOB
}

function initTravelWidget() {
	$('#ExpeSF input.date').each(function(){
		$(this).attr('value', 'mm/dd/yy').css('color','#999');
	});
	$('#ExpeSF input.date').bind('focus', function(){
		if (this.value == 'mm/dd/yy') {
			$(this).attr('value', '').css('color', '#000');
		}
	});
	$('#ExpeSF input.date').bind('blur', function(){
		if (this.value == '') {
			$(this).attr('value', 'mm/dd/yy').css('color', '#999');
		}
	});
	window.setTimeout("initTravelWidgetDatepicker()", 1)
}
function initTravelWidgetDatepicker() {
	$("input.date").datepicker({
		duration: '',
		maxDate: '+10m +24d',
		minDate: '0',
		dateFormat: 'mm/dd/yy',
		beforeShow: limitFromDate
	});
};
function limitFromDate() {
	var fromdate = new Date($(this).parents('fieldset').find("input.fromdate").attr('value'));
	if ($(this).hasClass('fromdate')) {
		return {minDate: '0'};
	} else {
		if (!isNaN(fromdate)) {
			return {minDate: fromdate};
		} else {
			return {minDate: '0'};
		}
	}
}
// end: travel widget

// start: music widget
function launchPlayer(stationId){
	var newWinPath = "/entertainment/music/radioPlayer.html?radioStation="+stationId;
	window.open(newWinPath);
}
// end: music widget

// start: wotd widget
function jump2form() {
	document.dict_form.q.select();
	document.dict_form.q.focus();
}
function isblank(s) {
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) {
			return false;
		}
	}
	return true;
}
function formcheck() {
	var d = document.dict_form.db[1].checked;
	var e = document.dict_form.q.value;
	if ((e == null) || (e == "") || isblank(e)) {
		alert("Please enter a word to look up.");
		jump2form();
	} else if (d == 1) {
		window.open("/track?id=1026336&add=1&url=http://thesaurus.reference.com/search%3Fq%3D" + escape(e));
	} else {
		window.open("/track?id=1026119&add=1&url=http://dictionary.reference.com/search%3Fq%3D" + escape(e));
	}
	return false;
}
// end: wotd widget


// start: local news widget
var localNewsZipTitle = "";
var localNewsZipKey = "";
var localNewsSearch = function(form) {
	form.elements["search.zip"].value = "";
	form.elements["search.state"].value = "";
	form.elements["search.city"].value = "";
	var srchstrng = form.elements["search.dummycity"].value
	var temparray = new Array();
	temparray[0] = srchstrng;
	if (srchstrng.match(/\d{5}/)) {
		temparray=srchstrng.match(/\d{5}/);
		form.elements["search.zip"].value = temparray[0];
		srchstrng=srchstrng.replace(/\d{5}/,"");
	}
	if (srchstrng.match(/,\s*[A-Za-z]{2}\b/)) {
		temparray = srchstrng.match(/,\s*[A-Za-z]{2}\b/);
		if (temparray[0].match(/\w{2}/)) {
			temparray=temparray[0].match(/\w{2}/);
			form.elements["search.state"].value = temparray[0].toUpperCase();
			srchstrng = srchstrng.replace(/,\s*[A-Za-z]{2}\b/,"");
		}
	} else if (srchstrng.match(/\s+[A-Za-z]{2}\b/)) {
		temparray = srchstrng.match(/\s+[A-Za-z]{2}\b/);
		if (temparray[temparray.length-1].match(/\w{2}/)) {
			temparray = temparray[temparray.length-1].match(/\w{2}/);
			form.elements["search.state"].value = temparray[0].toUpperCase();
			srchstrng = srchstrng.replace(/\s+[A-Za-z]{2}\b/,"");
		}
	}
	srchstrng = srchstrng.replace(/\d/g,"");
	form.elements["search.city"].value = escape(srchstrng.replace(/^\s+/g, '').replace(/\s+$/g, ''));
	form.elements["search.pref1key"].value = localNewsZipKey;
	form.elements["search.pref1name"].value = localNewsZipTitle;
	form.submit();
}
// end: local news widget

// start: myemail.html
function checkFormSubmit(form, email, password, headers) {
	if (email == null || email == '' || email.indexOf('@', 0) == -1) {
		alert('You are missing the email address or your email address is not valid. Please enter a proper email address.');
	} else if (password == '') {
		alert('You are missing the password. Please enter the password.');
	} else if (headers == '') {
		alert('You are missing the number of messages displayed. Please enter the number of Messages displayed.');
	} else if (!IsNumeric(headers)) {
		alert('Please enter a numeric value for the number of Messages displayed between 5 and 10');
	} else if (parseInt(headers) > 10 || parseInt(headers) < 5) {
		alert('Please enter a valid number for messages displayed between 5 amd 10');
	} else {
	 form.submit();
	}
}
function IsNumeric(sText) {
	var ValidChars = "0123456789";
	var IsNumber = true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}
function checkEditForm(form, password, password1, headers) {
	if (password != password1) {
		alert('The password fields should match');
	} else if (!IsNumeric(headers)) {
		alert('Please enter a numeric value for the number of Messages displayed between 5 and 10');
	} else if (parseInt(headers) > 10 || parseInt(headers) < 5) {
		alert('Please enter a valid number for messages displayed between 5 amd 10');
	} else {
		form.submit();
	}
}
function playVoiceMail(vmFrom, vmDuration, vmPath) {
	if (navigator.userAgent.toLowerCase().indexOf("windows") != -1) {
		// var mimeType="application/x-mplayer2" Having trouble with this.
		var mimeType = "audio/x-wav";
	} else {
		var mimeType = "audio/x-wav";
	}
	voiceMailPlayer = window.open('','_vmPlayer','width=320,height=240,resizable=0,scrollbars=0,titlebar=0,toolbar=0,menubar=0,status=0,directories=0');
	voiceMailPlayer.focus();
	voiceMailPlayer.document.write("<html><head><title>" + vmFrom + "</title></head><body><p><b>From: "+vmFrom+"<br />Duration: "+vmDuration+"</b></p><center><object width='280' height='70'><param name='src' value='" + vmPath + "'><param name='type' value='" + mimeType + "'><param name='autostart' value='1'><param name='showcontrols' value='1'> <param name='showstatusbar' value='1'><embed src ='" + vmPath + "' type='" + mimeType + "' autoplay='true' width='280' height='70' controller='1' showstatusbar='1' kioskmode='true'></embed></object><p><input type='button' value='Close this window' onclick='javascript:window.close();'></p></center></body></html>");
	voiceMailPlayer.document.close();
}
// end: myemail.html

// start: sports widget
function initSports() {
	$("#sports-wdgt .wdgt-section:first").addClass("wdgt-section-first");
	$("#sports-wdgt").find(".box").each(function(){
		$("#" + $(this).attr('id') + "-box").tabs( {selected: 1} );
		var togButton = $("#" + $(this).attr('id') + " h4 span");
		togButton.click(function(e){
			$("#" + e.currentTarget.parentNode.parentNode.id + "-box").slideToggle("slow",function () {
				if (togButton.text() == "[hide]") {
					togButton.text("[display]")
				} else {
					togButton.text("[hide]")
				}
			});
		});
	});
}
// end: sports widget

// start: tvguide widget
//
// end: tvguide widget

// start: travel header search
var initTravelSearch = function() {
	// init travel search form switch
	$('input.tr-input').click(function(){
		$('.travel-panel').hide();
		$('#'+$(this).attr('id')+'-panel').show();
	});
	// copy to/from values between fields
	$('input.tr-fr, input.tr-to').keyup(function(event){
		$('.'+event.currentTarget.className).each(function(){
			$(this).attr('value', event.currentTarget.value);
		});
	});
	// travel datepicker
	$(function() {
		$("input.dates").datepicker({
			duration: '',
			maxDate: '+10m +24d',
			minDate: '0',
			dateFormat: 'mm/dd/yy',
			beforeShow: limitFromDate
			});
	});
	function limitFromDate() {
		var fromdate = new Date($(this).parents('fieldset').find("input.fromdate").attr('value'));
		if ($(this).hasClass('fromdate')) {
			return {minDate: '0'};
		} else {
			if (!isNaN(fromdate)) {
				return {minDate: fromdate};
			} else {
				return {minDate: '0'};
			}
		}
	}
}
// end: travel header search

// start: tvlistings tabs
var initTvListings = function() {
	$('#tvlistings-box').tabs({'cache': true});
	$('#tvlistings-box').bind('tabsselect', function(event, ui) {
		if (ui.index == 1) {
			domWrite('tvguide-news', '/html/tvlistings_news.js');
		}
	});
};
// end: tvlistings tabs

// start: localnews wdgt
var initLocalNews = function() {
	// nasty hack to remove crazy inline css in widget iframe content
	$('#localnews-wdgt ul li div + div span').css({'float':'right','position':'static','right':'auto','top':'auto'});
	$('#localnews-wdgt ul li div + div').each(function(){
		$(this).css({'overflow':'hidden','position':'static'});
		var tTime = $(this).find('span').text();
		$(this).find('span').remove();
		var tText = $(this).text();
		var tLength = tText.indexOf(' printAge');
		if (tLength >=0) {
			$(this).html('<span style="float:left">' + tText.substring(0, tText.indexOf(' print')) + '</span><span style="float:right">' + tTime + '</span>')
		} else {
			$(this).html('<span style="float:left">' + tText + '</span><span style="float:right">' + tTime + '</span>')
		}
	});
	
};
// end: localnews wdgt

// start: theaters wdgt
var initTheaters = function() {
	var theaterIDs = $.cookie('showTheaters');
	ELNK.theaters.wdgts = $('#theaters-wdgt .listings');
	if (ELNK.theaters.wdgts.length > 0) {
		if (theaterIDs) {
			ELNK.theaters.showList = theaterIDs.split("%2C");
			ELNK.theaters.wdgts.css('display', 'none');
			if (ELNK.theaters.showList.length > 0 && ELNK.theaters.showList[0] != "") {
				for (i = 0; i < ELNK.theaters.showList.length; i++) {
					showText(ELNK.theaters.showList[i]);
				}
			}
			var first = ELNK.theaters.wdgts.eq(0);
			if (first.css('display') == 'none') {
				first.parent().find('div.displayButton').text('display showtimes');
			}
		} else {
			ELNK.theaters.wdgts.css('display', 'none');
			ELNK.theaters.wdgts.each(function() {
				if ($(this).parent().find('div.displayButton').text() == 'hide showtimes') {
					$(this).css('display', 'block');
				}
			});
		}
	}
}
function showText(tId) {
	//$("#theaterRow_" + tId).css('border-top', '1px solid #fff');
	//$("#theaterTitle_" + tId).css('background-color','#aaa');
	if ($("#listings_" + tId).css('display') == 'block') {
		$("#displayButton_" + tId).text('display showtimes');
		$("#listings_" + tId).css('display', 'none');
	} else {
		$("#displayButton_" + tId).text('hide showtimes');
		$("#listings_" + tId).css('position','relative');
		$("#listings_" + tId).css('display','block');
	}	
	var nArray = []
	$('#theaters-wdgt .listings').each(function(){
		if($(this).css('display') != 'none') {
			nArray.push($(this).attr('id').substring(9));
		}
	});
	$.cookie("showTheaters", escape(nArray), {'domain':ELNK.domain, 'expires': 256});
}
function adjustTheaterDisplays(){
	initTheaters();
};
// end: theaters wdgt

// Set Date/Timestamps on page
var setDateStamps = function() {
	$('.date-holder').each(function(){
		$(this).html(ELNK.datestamp());
	});
}

var setTimeStamps = function() {
	$('.time-holder').each(function(){
		$(this).html(ELNK.timestamp());
	});
}

// iframed content swap
function showDynCt(targetContainerId, contentString) {
 document.getElementById(targetContainerId).innerHTML = contentString;
}

function printAge(timeStamp) {
	//do nothing
}


// jQuery Plugins

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('q.5=x(k,d,a){4(m d!=\'H\'){a=a||{};4(d===p){d=\'\';a=$.A({},a);a.3=-1}2 g=\'\';4(a.3&&(m a.3==\'u\'||a.3.s)){2 f;4(m a.3==\'u\'){f=F C();f.B(f.z()+(a.3*y*o*o*v))}n{f=a.3}g=\'; 3=\'+f.s()}2 b=a.7?\'; 7=\'+(a.7):\'\';2 e=a.9?\'; 9=\'+(a.9):\'\';2 l=a.t?\'; t\':\'\';6.5=[k,\'=\',L(d),g,b,e,l].K(\'\')}n{2 h=p;4(6.5&&6.5!=\'\'){2 c=6.5.E(\';\');D(2 i=0;i<c.8;i++){2 j=q.G(c[i]);4(j.r(0,k.8+1)==(k+\'=\')){h=I(j.r(k.8+1));J}}}w h}};',48,48,'||var|expires|if|cookie|document|path|length|domain|||||||||||||typeof|else|60|null|jQuery|substring|toUTCString|secure|number|1000|return|function|24|getTime|extend|setTime|Date|for|split|new|trim|undefined|decodeURIComponent|break|join|encodeURIComponent'.split('|'),0,{}))

var domWrite = (function(){            // by Frank Thuerigen
	// private 

	var dw = document.write,              // save document.write()
		myCalls = [],                // contains all outstanding Scripts
		t = '';                      // timeout

	function startnext(){                 // start next call in pipeline
		if ( myCalls.length > 0 ) {
			//if ( Object.watch ) console.log( 'next is '+myCalls[0].f.toString() );
			myCalls[0].startCall();
		}
	}

	function evals( pCall ){            // eval embedded script tags in HTML code
		var scripts = [],
			script,
			regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
		while ((script = regexp.exec(pCall.buf))) scripts.push(script[1]);
		scripts = scripts.join('\n');
		if (scripts) {
			eval(scripts);
		}
	}

	function finishCall( pCall ){
		pCall.e.innerHTML = pCall.buf;             // write output to element
		evals( pCall );
		document.write=dw;                        // restore document.write()
		myCalls.shift();
		window.setTimeout( startnext, 50 );
	}

	function testDone( pCall ){
		var myCall = pCall;
		return function(){
			if ( myCall.buf !== myCall.oldbuf ) {
				myCall.oldbuf = myCall.buf;
				t=window.setTimeout( testDone( myCall ), myCall.ms );
			} else {
				finishCall( myCall );
			}
		}
	}

	function MyCall( pDiv, pSrc, pFunc ){                    // Class
		this.e = ( typeof pDiv == 'string' ? 
		document.getElementById( pDiv ) : pDiv ),                     // the div element
		this.f = pFunc || function(){},
		this.stat = 0,                         // 0=idle, 1=waiting, 2=running, 3=finished
		this.src = pSrc,                       // script source address
		this.buf = '',                         // output string buffer
		this.oldbuf = '',                      // compare buffer
		this.ms = 100,                         // milliseconds
		this.scripttag;                        // the script tag 
	}

	MyCall.prototype={
		startCall: function(){
			this.f.apply( window );                 // execute settings function
			this.stat=1;
			var that = this;                            // status = waiting
			document.write = (function(){
				var o=that,
				cb=testDone( o ),
				t;
				return function( pString ){            // overload document.write()
					window.clearTimeout( t );
					o.stat=2;                             // status = running
					window.clearTimeout(t);
					o.oldbuf = o.buf;
					o.buf += pString;                     // add string to buffer
					t=window.setTimeout( cb, o.ms );
				};
			})();
			var s=document.createElement('script');
			s.setAttribute('language','javascript');
			s.setAttribute('type','text/javascript');
			s.setAttribute('src', this.src);
			document.getElementsByTagName('head')[0].appendChild(s);
		}
	}

	return function( pDiv, pSrc, pFunc ){  // public
		var c = new MyCall( pDiv, pSrc, pFunc );
		myCalls.push( c );
		if ( myCalls.length === 1 ){
			startnext();
		}
	}
})();

jQuery.fn.supersleight = function(settings) {
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: 'x.gif',
		apply_positioning: true
	}, settings);
	
	return this.each(function(){
		if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
			jQuery(this).find('*').andSelf().each(function(i,obj) {
				var self = jQuery(obj);
				// background pngs
				if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
					var bg = self.css('background-image');
					var src = bg.substring(5,bg.length-2);
					var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
					var styles = {
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
						'background-image': 'url('+settings.shim+')'
					};
					self.css(styles);
				};
				// image elements
				if (settings.imgs && self.is('img[src$=png]')){
					var styles = {
						'width': self.width() + 'px',
						'height': self.height() + 'px',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
					};
					self.css(styles).attr('src', settings.shim);
				};
				// apply position to 'active' elements
				if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')){
					self.css('position', 'relative');
				};
			});
		};
	});
};

