window.onerror=err;
var brName = navigator.appName;
var brVer = parseInt(navigator.appVersion);
var brVendor = brName.substring(0,9);
var brUA = navigator.userAgent.toLowerCase();
var ie6or7 = (brVendor == 'Microsoft') && brUA.match(/msie\s*(6|7)/);
var d2038;

function err() {return false;}

// Window Fns

function wo(URL,pwidth,pheight,usetoolbar,uselocationbar,usemenubar,rndURL) {

   // Check to see if user wants to use tabbed browsing .. disable pop-ups.
   var window_spec = '';
   var target = '_blank';

   if ( ! EnableTabsState ) {
      window_spec = 'directories=0,status=1, scrollbars=1,resizable=1';

      if(typeof(usetoolbar) == 'undefined') {
         usetoolbar = "1";
      }
      if(typeof(uselocationbar) == 'undefined') {
         uselocationbar = "1";
      }
      if(typeof(usemenubar) == 'undefined') {
         usemenubar = "1";
      }
      if(typeof(pwidth) == 'undefined') {
         pwidth = (typeof(screen.width) == 'undefined') ? "800" : Math.round(screen.width * 0.75);
      }
      if(typeof(pheight) == 'undefined') {
         pheight = (typeof(screen.height) == 'undefined') ? "560" : Math.round(screen.height * 0.75);
      }


      if(usetoolbar != null ) window_spec += ',toolbar=' + usetoolbar;
      if(uselocationbar != null) window_spec += ',location=' + uselocationbar;
      if(usemenubar != null) window_spec += ',menubar=' + usemenubar;
      if(pwidth != null && pwidth > 0) window_spec += ',width=' + pwidth;
      if(pheight != null && pheight > 0) window_spec += ',height=' + pheight;
   }

   if(rndURL) {
      if(URL.indexOf('?') > 0) {
			URL += '&RandKey=';
      } else {
			URL += '?RandKey=';
      }
      URL += Math.floor(Math.random() * 1000000);
   }


   window.open(URL, target, window_spec);
	
   return false;
}

function nw_s(item) {
   return nw(item, null, null, null, null, null, null, 1);
}

function nw(item,pwidth,pheight,usetoolbar,uselocationbar,usemenubar,rndURL,addScreenSize) {
   if( (brVendor=='Microsoft' && brVer < 4) || (typeof item.href == 'undefined')) {return true;}
   
   var URL = item.href;

   if(typeof(Session) != 'undefined') {
      setCookie('NN_Session', Session, null, '/A', '', 0, 1);
   } 
   
   if(addScreenSize) {
	// Add screen/windowimension data to URL
	if(URL.indexOf('?')) {
	   URL += '&';
	} else {
	   URL += '?';
	}
      
	URL += 'Q.screen_width=' + window.screen.width
	+ '&Q.screen_height=' + window.screen.height
	+ '&Q.window_width=' + window.innerWidth
	+ '&Q.window_height=' + window.innerHeight;
   }
   
   addRatingMenu(item.parentNode, 1);

   return wo( URL, pwidth,pheight,usetoolbar,uselocationbar,usemenubar,rndURL );
}

function ao(obj) {
	return nw(obj,720,480,1,0,0,1);
}

function fao(obj) {
	return nw(obj,640,500,0,0,0,0);
}

function oao(obj) {
	return nw(obj,640,570,1,1,1,0);
}

function fo(obj) {
	return nw(obj,640,550,0,0,0,0);
}


function box_focus() {
   var fcls = this._saved_class + ' focus';
   
   if(this.className != fcls) this.className = fcls;
   
   if(typeof(this._saved_value) == 'undefined') {
      this._saved_value = this.value;
      this.value = '';
      return;
   }
   
   if(this.value == this._saved_value) this.value = '';
}

function box_blur() {
   if(this.value == '') {
      this.value = this._saved_value;
      this.className = this._saved_class + ' blur';
      return;
   }
   
   this.className = this._saved_class;
}

function box_init(item, text) {
   item._saved_value = text;
   item._saved_class = item.className;
   item.onfocus = box_focus;
   item.onblur = box_blur;
   item.className = item._saved_class + ' blur';
}


function box_check_text(item) {
   if(item.value == item._saved_value || item.value == '') {
      alert('Please enter some keywords for which to search');
      return false;
   }
   return true;
}

function box_clear_text(item) {
   if(!item)
     return;
   if(item.value == item._saved_value ) item.value = '';
}

function dupbut(i) {
   var g_el = document.getElementById('g' + i);
   var b_el = document.getElementById('a' + i);
	
	if( g_el.className == 'dupOn' ) {
		g_el.className = 'dupOff';
		b_el.innerHTML = 'Show duplicates';
	}
	else {
		g_el.className = 'dupOn';
		b_el.innerHTML = 'Hide duplicates';
	}
	
   return false;
}

// Ads

var AdTags = {};
var AdTagPosOrder = new Array; 
var delayedAdLoad = 0;
var ads_override = parseInt(getCookieValue('NN_ADS_OVERRIDE'))||0;
var ads_type = parseInt(getCookieValue('NN_BG'))||0;
var ads_iframe = !ie6or7;

function insertAdDest2(pos, tag, width, height, slotWidth, slotHeight, attr, plId, posId, dims, PageID, FormatID) {
  if(ads_override==2) return;
   
  if (delayedAdLoad) {
     AdTags[posId] = [tag, width, height, plId, slotWidth, slotHeight, pos, PageID, FormatID];
     AdTagPosOrder.push(posId);
     var src = '/ico/1x1t.png';
     if (src) src = '<img src="' + src + '" height="' + height + '" width="' + width + '"/>'; else src = '';
     document.writeln('<DIV ID="Ad_' + plId + '">' + src + '</DIV>');
  }
  else {
     insertAdSrc2(pos, tag, width, height, slotWidth, slotHeight, attr, plId, PageID, FormatID);
   }
}

function insertAdSrc2(pos, tag, slotWidth, slotHeight, plId, PageID, FormatID) {
   if(typeof(window.adgroupid) == 'undefined') window.adgroupid = Math.round(Math.random() * 1000);

   if(ads_iframe) {
      document.writeln('<DIV ID="Ad_' + plId + '"><IFRAME SLOT="' + pos + '" FRAMEBORDER="0" STYLE="width: ' + slotWidth + 'px; height: ' + slotHeight + 'px;" SRC="/ads/iframe.html?2" FormatID="' + FormatID + '" PageID="' + PageID + '" Type="' + ads_type + '" Over="' + ads_override + '"></IFRAME></DIV>');
      return;
   }

   if(ads_override==1) {
      houseAd(pos, 'uk');
      return;
   }

   SmartAdServer(PageID,FormatID,ads_type);
}

function onAd(i) {
  if (typeof(AdTags[i]) == 'undefined') return true;

  var d = document.getElementById('Ad_' + AdTags[i][3]);

  if(d == undefined) return;

  if (typeof(window.adgroupid) == 'undefined')
    window.adgroupid = Math.round(Math.random() * 1000);

   if(AdTags[i][7]) {
      // New 'maroon spider' ad
      d.innerHTML = '<IFRAME SLOT="' + AdTags[i][6] + '" FRAMEBORDER="0" STYLE="width: ' + AdTags[i][4] + 'px; height: ' +  AdTags[i][5] + 'px;" SRC="/ads/iframe.html?2" FormatID="' + AdTags[i][8] + '" PageID="' + AdTags[i][7] + '"></IFRAME>';
   } else {
      eval ('adtech_adurl_' + AdTags[i][3] + "='http://adserver.adtech.de/addyn|3.0|" +  AdTags[i][0] + '|ADTECH;cookie=info;loc=100;target=_blank;grp=' + window.adgroupid+';misc='+new Date().getTime() + "'");

      d.innerHTML = '<IFRAME ID="ADTECH_IFRAME_' + AdTags[i][3] + '" SLOT="' + AdTags[i][6] + '" FRAMEBORDER="0" STYLE="width: ' + AdTags[i][4] + 'px; height: ' +  AdTags[i][5] + 'px;" SRC="/adtech/stubfile.html?10"></IFRAME>';
   }
}

function enableAds() {
  var j = 1;
  for (var i in AdTagPosOrder)
    if (AdTags[AdTagPosOrder[i]]) {
         setTimeout("onAd(" + AdTagPosOrder[i] + ")", j*500);
         j++;
    }

  return true;
}

// (C)-bar

function RedoPageBottom() {
   return 0 - page_bottom.offsetHeight + (
					  document.documentElement.clientHeight ?
					  document.documentElement.clientHeight : document.body.clientHeight ) +
     ( ignoreMe = document.documentElement.scrollTop ?
       document.documentElement.scrollTop : document.body.scrollTop ) +
     'px';
}

// Utils

function setCookie(name, value, expires, path, domain, secure, noescape) {
    if( d2038 == undefined ) d2038 = new Date('Tue, 19 Jan 2038 03:00:00 GMT');
    if( expires == 'd2038' ) expires = d2038;
    
    var curCookie = name + "=" + (noescape ? value : escape(value)) +
      (expires ? "; expires=" + expires.toGMTString() : '') +
      ("; path=" + (path ? path : "/")) +
      (domain ? "; domain=" + domain : "") +
      (secure ? "; secure" : "");
   
    document.cookie = curCookie;
}

function setCookieElement(name, key, value, expires, path, domain, secure) {
   var vals = getCookieElements(name);
   if(vals) {
        vals = vals.map(unescape).filter(filter_not_like, new RegExp('^' + key + '='));
   } else {
      vals = new Array;
   }
   
   vals.push(key + '=' + value);
   setCookie(name, vals.join('&'), expires, path, domain, secure, 1);
}

/*
  name - name of the desired cookie
  return string containing value of
  specified cookie or null
  if cookie does not exist
  */

function getArg(str,tag,del) 
{
   var prefix = tag + "=";

   var begin = str.indexOf(del + prefix);
   
   if (begin == -1) {
	begin = str.indexOf(prefix);
	if (begin != 0) return null;
   } else begin += del.length;
   
   var end = str.indexOf(del, begin);
   if (end == -1)
     end = str.length;
   
   return str.substring(begin + prefix.length, end);
}

function getCookie(name,tag)
{
    return getArg(unescape(getArg(document.cookie,name,'; ')),tag,'&');
}

function getCookieValue(name)
{
    return getArg(document.cookie, name, '; ');
}

function getCookieElements(name)
{
    var x = getCookieValue(name);
    if( x == null ) return null;
   if(x == '') return null;
    return x.split("&");
}

function getCookieElementKeyValue( el, key )
{
    var a = getArg(el, key, '&');
    if( a == null ) return null;
    return unescape( a.replace(/\+/ig,' ') );
}

function HTMLescaper(str)
{
    var out = '';
    for(i = 0; i < str.length; i++) {
	out = out + '&#' + str.charCodeAt(i) + ';';
    }
    return out;
}

function escapeHTML(str) {
   
   var newStr = '';
   
   for(var i = 0; i < str.length; i++) {
      if(str.charAt(i).match(/[^A-Za-z0-9\+\*\-\.\,\@\_ ]/)) {
	 newStr += '&#' + str.charCodeAt(i) + ';';
      } else {
	 newStr += str.charAt(i);
      }
   }
   return newStr;
}


function escapeJS(str) 
{
    return str.replace('\'', '\\\'');
}


function URLescaper(str) {
   return escape(str);
}

function escapeCookie(str) {
   // Escape only those items absolutely necessary to escape, to avoid inflating cookie size excessively
   str = str.replace(/%/g, '%25');
   str = str.replace(/;/g, '%3B');
   str = str.replace(/=/g, '%3D');
   str = str.replace(/ /g, '%20');
   str = str.replace(/&/g, '%26');
   // Escape non-ASCII character entities
   str = str.replace(/[\u0080-\uFFFF]/g, URLescaper);
   return str;
}

function unescapeCookie(str) {
   return unescape(str);
}

function filter_like(item)
{
    if(this.test(item))
    {
	return true;
    }
    return false;
}

function filter_not_like(item)
{
    if(this.test(item))
    {
	return false;
    }
    return true;
}

function filter_not_equal(item)
{
    if(this == item)
    {
	return false;
    }
    return true;
}

function filter_equal(item)
{
    if(this == item)
    {
	return true;
    }
    return false;
}

// 'some' is available from JavaScript 1.6 onwards
// Extend Array to add 'some' method if not defined

if(Array.prototype.some == null) {
   Array.prototype.some = function(filter_fn, arg) {
      for(var i = 0; i < this.length; i++) {
	 if(filter_fn.call(arg, this[i])) {
	    return true;
	 }
      }
      return false;
   }
}

// 'map' is available from JavaScript 1.6 onwards
// Extend Array to add 'map' method if not defined

if(Array.prototype.map == null) {
   Array.prototype.map = function(map_fn) {
      var result = new Array;
      for(var i = 0; i < this.length; i++) {
	 result.push(map_fn.call(this, this[i]));
      }
      return result;
   }
}

// 'filter' is available from JavaScript 1.6 onwards
// Extend Array to add 'filter' method if not defined

if(Array.prototype.filter == null) {
   Array.prototype.filter = function(filter_fn, arg) {
      var result = new Array;
      for(var i = 0; i < this.length; i++) {
	 if(filter_fn.call(arg, this[i])) {
	    result.push(this[i]);
	 }
      }
      return result;
   }
}

// Histories

var hist_ids = new Object();
function initHistoryHash() {
   
   var hist = getCookieElements('NN_History');
   for(var i = 0; hist && i < hist.length; i++) {
      var e = unescapeCookie(hist[i]);
      var ID = getCookieElementKeyValue(e, 'I');
      var V = getCookieElementKeyValue(e, 'V');
      hist_ids[ID] = (V == undefined) ? '0' : V;
   }
   
}

function resizeHistory( v, len, histType )
{
    var c = getCookie('NN_UI', histType + 'HistHeight');
    var cv = parseInt(c);
    if(isNaN(cv) || cv == null ) cv = 10;
   if(cv > len) cv = len;
    cv += v;
   if(cv < 0) cv = 0;
   // All items shown => remove limit
    if( cv >= len ) cv = 10;
   setCookieElement('NN_UI', histType + 'HistHeight', cv, 'd2038', '/h/');
   if( histType == 'Newsfeed' ) {
      //updateNewsfeedHistory();
   } else {
      updateHistory();
   }
}

function addToHistory(ID, Text, Source, Nat, TimeDate, ReadTime, UTimeDate, UReadTime)
{
    var els = getCookieElements('NN_History');

    // Check if history already contains this article
      if(els && els.some(filter_like, new RegExp('I%3D' + ID + '(%26|$)')))
    {
	return;
    }


   var cookieData = 
     [
      'I=' + escapeCookie(ID),
      'H=' + escapeCookie(Text),
      'S=' + escapeCookie(Source),
      'N=' + escapeCookie(Nat),
/*    'T=' + escapeCookie(TimeDate),
      'R=' + escapeCookie(ReadTime), */
      'UT=' + escapeCookie(UTimeDate),
      'UR=' + escapeCookie(UReadTime)
      ];
   
    var cookieVal = getCookieValue('NN_History');

    cookieVal = escapeCookie(cookieData.join('&')) + ( cookieVal ? '&' + cookieVal : '' );
    // Limit number of items to 10
      while( cookieVal.split( '&' ).length > 10 ) {
	  cookieVal = cookieVal.replace(/&[^&]+$/, '');
      }

    setCookie('NN_History', cookieVal, 'd2038', '/h/', '', 0, 1);
    updateHistory();
}

function removeFromHistory(ID) {
   var els = getCookieElements('NN_History');
   var elsUnescaped = els.map(unescape);
   var newCookie = '';
   
   for(var i = 0; i < elsUnescaped.length; i++) {
      var ThisID = getCookieElementKeyValue(elsUnescaped[i], 'I');
      if(ThisID == ID)
	{
	   // Skip this item - remove it from the list
	}
       else 
	{
	   if(newCookie)
	     newCookie += '&';
	   newCookie += els[i];
	}
   }

   setCookie('NN_History', newCookie, 'd2038', '/h/', '', 0, 1);
   updateHistory();
   return false;
}

function updateHistoryElement(ID, Rating, Done) {
   var els = getCookieElements('NN_History');
   var elsUnescaped = els.map(unescape);
   var newCookie = '';
   
   var rep = '%26V%3D' + (Done ? '!' : '') + ((Rating == undefined) ? '$1' : Rating);
   
   for(var i = 0; i < elsUnescaped.length; i++) {
      
      var ThisID = getCookieElementKeyValue(elsUnescaped[i], 'I');
      
      if(ThisID == ID) {
	 els[i] = els[i].replace(/(?:%26V%3D!?(-?\d+)?)?$/, rep);
      }
      
      if(newCookie) newCookie += '&';
      newCookie += els[i];
   }

   setCookie('NN_History', newCookie, 'd2038', '/h/', '', 0, 1);
   updateHistory();
   return false;
}

function renderHistory( id, child, first )
{

    var els = getCookieElements('NN_History');

    if( els == null ) return '';

    var ui_hh = getCookie('NN_UI', 'HistHeight');
    if(ui_hh == null) ui_hh = 10;

    var html = '<table class="header" id="neutral" style="width: 300px"><tr><td><img src="/ico/right.gif" alt="&gt;"/></td><th>My Recently Read</th>';
    html += '<th class="teaser_more">' +
		'<a onclick="resizeHistory(-1,' + els.length + ', \'\')"' + ( ui_hh <= 0 ? ' style="visibility: hidden"' : '' ) + '>less</a> ' +
		'<a onclick="resizeHistory(1,' + els.length + ', \'\')"' + ( ui_hh >= els.length ? ' style="visibility: hidden"' : '' ) + '>more</a>' +
	    '</th></tr></table>';
   
    html += '<table class="box" id="neutral" style="width: 300px"><tr><td class="headlines"><div class="top_stories fs_'
     + getCookieValue('NN_FontSize') + ' b_' + (getCookieValue('NN_FontBold') == 1 ? 'on' : 'off') + '" id="newsfeed_9">';

    for(var i = 0; i < els.length && i < ui_hh; i++) {

	var e = unescapeCookie(els[i]);

	var ID = getCookieElementKeyValue(e, 'I');
        if(!ID) continue;

	var style = '';
	var Text = getCookieElementKeyValue(e, 'H');
	var Source = getCookieElementKeyValue(e, 'S');
	var Nat = getCookieElementKeyValue(e, 'N');
	var TimeDate = getCookieElementKeyValue(e, 'T');
	var ReadTime = getCookieElementKeyValue(e, 'R');
	var UT = getCookieElementKeyValue(e, 'UT');
	var UR = getCookieElementKeyValue(e, 'UR');
	var V = getCookieElementKeyValue(e, 'V');
       
       if(UT != undefined) TimeDate = getArticleDate(UT);
       if(UR != undefined) ReadTime = getArticleDate(UR);
       
	 html +=
	 '<a href="" onclick="return removeFromHistory(\'' + ID + '\')" style="float: right">' +
	  '<img style="padding: 2px" src="/ico/delete.jpg" alt="Delete" title="Click to remove this article from the list" border="0"/></a>' +
	 '<p id="mrr_' + ID + '" i="' + ID + '">' +
	 '<img src="/F' + Nat + '.gif"><a href="' +
	  '/A/' + ID + '"' +
	  ' title="Read: ' + escapeHTML(ReadTime) + '"' +
	  ' target="_blank" onClick="return nw(this)">' +
	  escapeHTML(Text) + '</a><br/>' +
	  '<span class="src">' + escapeHTML(Source) +
		      ' ' + escapeHTML(TimeDate) +
	  '</span>' +
       /* '<a onClick="createRatingMenu(this.parentNode,' + ID + ')">Rating</a>' +
	 ': ' + getCookieElementKeyValue(e, 'V') + */
	 '</p>'
	  ;
       
    }
    html += '</div>';
    html += i + ' shown of ' + els.length;
   
    html += '</td></tr></table>';
    return html;
}

function getTitle( name ) {
   if(name == null)
     return '';
   var i = name.lastIndexOf(';');
   if(i >= 0) 
	return name.substring(i + 1);
   return name;
}

function clearNewsfeedHistory() {
   setCookie('NN_NewsfeedHistory', '', 'd2038', '/h/', '', 0, 1);
   location.reload(1);
}

var nH;

function renderNewsfeedHistory( id, type, threshold )
{

   if(nH == null || !nH.length) return '';
	
    if( threshold == null ) threshold = 0;

    var ui_hh = getCookie('NN_UI', 'NewsfeedHistHeight');
    if(ui_hh == null) ui_hh = 10;

    var html;
    switch(type) {
      
      case 'ul':
       html = '<li class="s" title="Shows a list of your most-visited feeds, with the most visited at the top"><a href="/h/?nfh=1">My Most Viewed</a><ul>';
        break;
      
      default:
        html = '<table class="header" id="neutral" style="width: 300px"><tr><td><img src="/ico/right.gif" alt="&gt;"/></td><th>My Most Viewed Feeds</th><th class="teaser_more">' +
		'<a onclick="resizeHistory(-1,' + els.length + ', \'Newsfeed\')"' + ( ui_hh <= 0 ? ' style="visibility: hidden"' : '' ) + '>less</a> ' +
		'<a onclick="resizeHistory(1,' + els.length + ', \'Newsfeed\')"' + ( ui_hh >= els.length ? ' style="visibility: hidden"' : '' ) + '>more</a>' +
		'</th></tr></table>';
      
        html += '<table class="box" id="neutral" style="width: 300px"><tr><td><div class="links"><ul>';
    }

    for(var i = 0; i < nH.length && i < ui_hh; i++) {
       
      // Skip newsfeeds with less than a certain number of hits
      if(nH[i][3] < threshold || (nH[i][0] == '' && nH[i][2]  == '')) {
	 continue;
      }
   
       var URI = '';
       if(nH[i][0])
          URI += 'N=' + escape(nH[i][0]);
       if(nH[i][2]) {
	  if(URI.length)
	    URI += '&' 
          URI += 'search=' + escape(nH[i][2]);
       }
    
       switch(type) {
       case 'ul': 
	html +=
	 '<li class="nfh" id="nfh_' + nH[i][0] + '|' + escape(nH[i][2]) + '">' +
	 '<a href="/?' + URI + '">' +
	 (i + 1) + '. ' +
	 (nH[i][0] ? escapeHTML(nH[i][1]) : '') +
	 (nH[i][2] ? (nH[i][0] ? ' &raquo; ' : 'Headline search: ') + escapeHTML(nH[i][2]) : '') +
	 '</a>' +
	  '</li>'
	  ;
	  break;
	  
       case 'html': 
	html +=
	 '<li class="nfh" id="nfh_' + nH[i][0] + '|' + nH[i][2] + '">' +
	 '<a href="?' + URI + '">' +
	 (i + 1) + '. ' +
	 (nH[i].Node ? escapeHTML(nH[i][1]) : '') +
	 (nH[i].Search ? (nH[i].Node ? ' &raquo; ' : 'Headline search: ') + escapeHTML(nH[i][2]) : '') +
	 ' (' + nH[i][3] + ')' +
	 '</a>' +
	  '</li>'
	  ;
	  break;
	  }
	  
    }
    
   switch(type) {
      
    case 'ul':
      html += '<li class="s"/>';
      html += '<li class="l"><a href="javascript:clearNewsfeedHistory()">Clear this list</a></li>';
      html += '</ul>';
      break;
    default:
      html += '<li class="l"><a href="javascript:clearNewsfeedHistory()">Clear this list</a></li>';
      html += '</ul></div>';
      html += i + ' shown of ' + els.length;
      html += '</td></tr></table>';
   }
   return html;
}

function updateHistory(id)
{
    document.getElementById('myrecent').innerHTML = renderHistory(id, window);
}

function updateNewsfeedHistory(id)
{
    document.getElementById('myrecentnewsfeeds').innerHTML = renderNewsfeedHistory(id);
}

//

function toggleMore(moreLink, itemsId) {
    var items = document.getElementById(itemsId);
    
    if(items.style.display == 'inline') {
	items.style.display = 'none';
       moreLink.style.display = 'inline';
    } else {
	items.style.display = 'inline';
       moreLink.style.display = 'none';
    }
}

// Tools Menu

function toggleControlBox() {
   if( document.getElementById('controlbtn').className == 'controlbtn' )
     document.getElementById('controlbtn').className = 'controlbtn cbon';
   else
     document.getElementById('controlbtn').className = 'controlbtn';

    return false;
}

function normalizeCookieValue( cookie, defaultValue ) {
  var value = parseInt( getCookieValue( cookie ) );

  return ( value == null || isNaN( value ) )? defaultValue : value;
}

var curfontSize = parseInt(getCookieValue('NN_FontSize'));
var deffontSize = 12;
var stepfontSize = 2;
var publicationFilterClass = '';

function toggleBoldFont() {
  var isBold = normalizeCookieValue( 'NN_FontBold', 0 );
  isBold = isBold? 0 : 1;
  setCookie( 'NN_FontBold', isBold, 'd2038', '/h/', '', 0, 0 );

  var size = curfontSize;
  var newsfeed_el;
  for ( var i = 1; i < 10; i++ ) {
    if ( newsfeed_el = document.getElementById( 'newsfeed_' + i ) ) {
      if ( newsfeed_el.className.indexOf( 'top_stories' ) != -1 ) {
        newsfeed_el.className =
          'top_stories fs_' + size +
	   ( isBold == 1 ? ' b_on' : ' b_off' ) + (publicationFilterClass ? (' ' + publicationFilterClass) : '');
      } else {
        newsfeed_el.className =
          'newsfeed f_' + size +
	   ( isBold == 1 ? ' b_on' : ' b_off' ) + (publicationFilterClass ? (' ' + publicationFilterClass) : '');
      }
    }
  }
}

function isChecked( cookie ) {
  var isChecked = normalizeCookieValue( cookie, 0 );

  return ( isChecked == 1 )? ' checked="checked"' : '';
}

function fontSize(newsize) {
  if ( newsize == 0 ) return;
   var bold = normalizeCookieValue( 'NN_FontBold', 0 );

   var newsfeed_el;
   for(var i = 1; i< 10; i++) {
      if(newsfeed_el = document.getElementById('newsfeed_' + i)) {
	 if(newsfeed_el.className.indexOf('top_stories') != -1) {
	    newsfeed_el.className = 'top_stories fs_' + newsize + (bold == 1 ? ' b_on' : ' b_off') + (publicationFilterClass ? (' ' + publicationFilterClass) : '');
	 } else {
	    newsfeed_el.className = 'newsfeed f_' + newsize + (bold == 1 ? ' b_on' : ' b_off') + (publicationFilterClass ? (' ' + publicationFilterClass) : '');
	 }
      }
   }
   
   if( curfontSize == newsize ) return;
   curfontSize = newsize;
   setCookie('NN_FontSize', newsize, 'd2038', '/h/', '', 0, 0);
}

var fontSizeDropdown = {
  "10" : "Small",
  "12" : "Normal",
  "14" : "Large",
  "16" : "Extra Large",
  "18" : "Very Large" };

var fontSizeDropdownAttrs = {
  "id"       : "FontSize",
  "name"     : "FontSize",
  "style"    : "vertical-align:middle",
  "onchange" : "fontSize(document.controlfrm.FontSize.value); return false" };

var filterMapping = {
  'FilterBlogs'  : 'NN_FilterBlogs',
  'FilterRating' : 'NN_FilterRating',
  'FilterPR'     : 'NN_FilterPR',
  'FilterReg'    : 'NN_FilterReg',
  'FilterWords'  : 'NN_FilterWords'
  };

var filterDefaults = {
  'FilterBlogs'  : 'Show',
  'FilterRating' : 'Any',
  'FilterPR'     : 'Show',
  'FilterReg'    : 'Show',
  'FilterWords'  : 'Remove'
  };

function renderList( listHash, selectedValue, attrsHash ) {
  var attrs = "";
  if ( attrsHash )
    for ( var attr in attrsHash )
      attrs = attrs + ' ' + attr + '="' + attrsHash[attr] + '"';

  document.write( '<select' + attrs + '>' );
  for ( var key in listHash ) {
    document.write( '<option  value="' + key + '"' );
    if ( key == selectedValue )
      document.write( ' selected="selected"' );
    document.write( '>' + listHash[key] + '</option>' );
  }
  document.write( '</select>' );
}

function renderTypeFaceControls() {
  document.write(
    '<table style="width:100%;border:0">' +
    '<tr><td style="font-size:11px;padding-left:4px">' +
    '<label><input type="checkbox" name="Bold" style="vertical-align:middle" onclick="javascript:return toggleBoldFont()"' +
    isChecked( 'NN_FontBold' ) +
    ' />Bold</label></td>' +
    '<td style="text-align:right;font-size:11px">Size:' );
  var savedFontSize = getCookieValue( 'NN_FontSize' );
  savedFontSize = savedFontSize? savedFontSize : "12";
  renderList( fontSizeDropdown, savedFontSize, fontSizeDropdownAttrs );
  document.write( '</td></tr></table>' );
}

function setFilterCookie( cookie, value ) {
  setCookie( cookie, value, '/h/', '', 0, 0 );
}

function setFilterPrefs( filterform ) {

  for (var filter in filterMapping)
    if (filterform[filter])
      setCookie(filterMapping[filter],filterform[filter].value,'d2038','/h/','',0,0);

  location.reload(1);

  return false;
}


function resetFilters() {

  for ( var filter in filterMapping )
    setCookie( filterMapping[filter], filterDefaults[filter], 'd2038', '/h/', '', 0, 0 );

  location.reload( 1 );

  return false;
}

// Tabs

var EnableTabsState = parseInt(getCookieValue('NN_Tabs'));

function ToggleTabs() {

   var inst = '';

   if ( ! EnableTabsState ) { /* Off, so the user wishes to switch it on */
     if ( (brUA.indexOf("msie") != -1) && (brUA.indexOf("opera") == -1) ) {
       var temp=navigator.appVersion.split("MSIE")
       var version=parseFloat(temp[1])
       if ( version >= 7.0 )
         inst = "Go to Tools => Internet Options, and in the Tabs section click the Settings button. Then under 'Open Links From Other Programs' select 'a new tab in the current window'.\n\n";
       else {
         alert("I'm sorry your browser does not support tabs"); // should never happen - we are using conditional comments in HTML
         return false;
       }
     } else if ( brUA.indexOf("opera") != -1 ) {
       inst = ''; // works by default
     } else if ( brUA.indexOf("gecko") != -1 ) {
       if ( brUA.indexOf("win") != -1 ) 
         inst = "Go to Tools => Options... and in the Tabs section under 'Open Links From Other Programs' select 'a new tab in the most recent window'.\n\n";
       else // assume linux?
         inst = "Got to Edit => Preferences, and in the Tabs section under 'New pages should be opened in:' select 'a new tab'.\n\n";
     } else {
       inst = ' '; // assume it works by default?? or ...
       //alert("I'm sorry your browser does not support tabs");
       //return false;
     }
   }

   var resp = 1;
   if ( inst ) {
     resp = confirm( 'WARNING: for this to work you need to configure your ' +
                     'browser to open new windows in a new tab.\n\n' + inst +
                     'Click \'OK\' to continue or click \'Cancel\' to keep ' +
                     'current behaviour.' );
   }

   if ( resp ) {
     EnableTabsState = EnableTabsState ? 0 : 1; // do the toggle bit.
     setCookie('NN_Tabs', EnableTabsState, 'd2038', '/h/', '', 0, 0);
     SetEnableTabs(EnableTabsState);
   } else {
     document.controlfrm.tabscheck.checked=false;
   }

    return false;
}

function SetEnableTabs(newstate) {
   if(newstate == null) newstate = EnableTabsState;
   EnableTabsState = newstate;
}

// Refresh

var element_counter;
var refresh_interval; // Interval ID
var refresh_counter = 0; // Counts total seconds
var refresh_limit1 = 270; // No. of seconds to be counted in the step below;
var refresh_limit1_step = 10; // Step for above.
var refresh_limit2 = 30; // No. of seconds to be counted in 1s;
var idle_limit = 30;
var idle_since;

function detectRefresh(s) {

   if( (refresh_counter += s) < refresh_limit1 ) return;
   
   if( refresh_counter == refresh_limit1 ) {
      clearInterval(refresh_interval);
      refresh_interval = window.setInterval("countRefresh(1)", 1000);
      return;
   }
   
   if( refresh_counter < refresh_limit1 + refresh_limit2 ) return;
   
   window.clearInterval(refresh_interval);
   
   if(idle_since >= idle_limit) setCookie('NN_BG', '1', null, '/h/', '', 0, 1);
   
   if( brVer >= 4 || window.location.replace ) window.location.replace(window.location.href);
   else window.location.href = window.location.href;
   
}

function countRefresh(s) {
   detectRefresh(s);
   var x = refresh_limit1+refresh_limit2-refresh_counter;
   element_counter.innerHTML = x;
}

function idleReset() {
   if(refresh_counter >= refresh_limit1 ) refresh_counter = refresh_limit1 - 1;
   idle_since = refresh_limit1 + refresh_limit2 - refresh_counter;
}

function initRefresh() 
{
   idleReset();
   
   element_counter = document.getElementById('counter');
   element_counter.innerHTML = refresh_limit1+refresh_limit2-refresh_counter;
   refresh_interval = window.setInterval('countRefresh(' + refresh_limit1_step + ')', refresh_limit1_step*1000);
   
   window.onscroll = idleReset;
   document.onmousemove = idleReset;
   document.onkeypress = idleReset;
   
   setCookie('NN_BG', '0', null, '/h/', '', 0, 1);
   
}

// Ratings

initHistoryHash();

function addRatingMenu(n, m) {
   return;
   
   var i = n.getAttribute('i');
   if( m || hist_ids[i] ) {
      if( m || hist_ids[i].charAt(0) != '!' )
	createRatingMenu(n, i);
      
      n.getElementsByTagName('a').item(0).className = 'read';
   }
}

function removeRatingMenu(aid) {
   updateHistoryElement(aid, undefined, 1);
   
   var el = document.getElementById('rating_' + aid);
   
   if(el) el.parentNode.removeChild(el);
}

function getRatingMenu(aid) {

   var v = hist_ids[aid];
   
   if( v != undefined && v.charAt(0) == '!' ) v = v.substr(1);
   
   var html =
     '<div class="rating">' +
     '<form><fieldset><legend>Rate this article</legend>';
   
   for(var i = -2; i <= 2; i++)
     html += '<span><label for="r'+aid+'_'+i+'">'+i+' </label><input onclick="updateHistoryElement(' + aid + ', '+i+')" type="radio" id="r'+aid+'_'+i+'" name="rating" value="'+i+'"' + ((i == v) ? ' checked' : '') + '></span> ';
   
   html +=
     '<input type="submit" value="Close" onClick="removeRatingMenu(' + aid + '); return false">' +
     '</fieldset></form></div>';
   
   return html;
}

function createRatingMenu(el, aid) {
   
   var old = document.getElementById('rating_' + aid);
   if(old) old.parentNode.removeChild(old);
   
   var d = document.createElement('div');
   d.id = 'rating_' + aid;   
   d.innerHTML = getRatingMenu(aid);
   el.appendChild(d);
}

// ArticleDates

var my_ut_midnight;

function getArticleDate(ut) {
   
   var myDate = new Date(ut*1000);
   var h = myDate.getHours();
   var m = myDate.getMinutes();
   var d = myDate.toDateString().split(' ');
   
   if( my_ut_midnight == undefined) {
      var utDate = new Date(NN_UT*1000);
      var uth = utDate.getHours();
      var utm = utDate.getMinutes();

      my_ut_midnight = NN_UT - ((uth*60)+utm)*60;
   }
   
   return (
     ((h < 10) ? ('0'+h) : h) + ':' +
     ((m < 10) ? ('0'+m) : m) + ' ' +
     ( (ut < my_ut_midnight) ?
       d[0] + ', ' + d[2] + ' ' + d[1] + ' ' + d[3].substring(2)
       : '' )
	   );
}

function setArticleDate(src) {
   // Set time to client's localtime
   src.getElementsByTagName('u').item(0).innerHTML = getArticleDate( src.getAttribute('ut') );
}

function setArticleDates(id) {
   var r = document.getElementById(id);
   if(!r) return;

   var spans = r.getElementsByTagName('span');
   
   for(var i=0; i < spans.length; i++) {
      if( spans.item(i).className == 'src' ) {
	 setArticleDate(spans.item(i));
	 addRatingMenu( spans.item(i).parentNode );
      }
   }
}

var source_popup;

function sourceMouseClick(e) {
   if(!e) var e = window.event;
   var tg = e.target ? e.target : e.srcElement;

   if( (tg.nodeName == 'B' || tg.nodeName == 'U') && tg.parentNode.nodeName == 'SPAN' && tg.parentNode.className.match(/src/)) tg = tg.parentNode;
   
   if( tg.className != 'src' ) return;

   hidePubMenu();
   
   source_popup = tg;
   
   createPubMenu( source_popup );
}

function hidePubMenu() {
   // Prevent bubbling events, triggering on children of required element, from being processed.
   if( source_popup ) {

      if(source_popup.lastChild.nodeName == 'DIV') {
         // DIV already there - delete it.
	 source_popup.removeChild(source_popup.lastChild);
      }

      source_popup.className = 'src';
      
      source_popup = undefined;
   }
}

function createPubMenu(src) {
   var txt;
   var hndlr;
   var html;
   
   if( src.parentNode.className.match(/pub_hidden/) ) {
      html = '<a onclick="setPubAndFilter(\'+\')">Highlight publication</a>';
      html += '<a onclick="setPubAndFilter(\'\')">Show publication</a>';
   }
   else if( src.parentNode.className.match(/pub_marked/) ) {
      html = '<a onclick="setPubAndFilter(\'\')">De-highlight publication</a>';
      html += '<a onclick="setPubAndFilter(\'-\')">Hide publication</a>';
   }
   else {
      html = '<a onclick="setPubAndFilter(\'+\')">Highlight publication</a>';
      html += '<a onclick="setPubAndFilter(\'-\')">Hide publication</a>';
   }
   
   if(src.lastChild.nodeName == 'DIV') {
      // DIV already there - delete it.
      src.removeChild(src.lastChild);
   }
      
   var div = document.createElement('div');
   
   div.className = 'src_ctrl';
   div.innerHTML = '<div>' + src.getElementsByTagName('b').item(0).innerHTML + '</div>' + html;
   
   src.appendChild(div);
   
   src.className = 'src ctrl';
}

var Publications;

function getPubs() {
   if(Publications != undefined) return Publications;
   
   Publications = new Object;
   
   var pubCookie = getCookieValue('NN_PUBS');
   
   if(pubCookie) {
      var a = pubCookie.split('|');
      
      for( var i = 0; i < a.length; i++ ) {
	 if(a[i]) {	      
	      var sign = a[i].charAt(0);
	      var src = a[i].substr(1);
	      Publications[ src ] = sign;
	   }
 
      }
      return Publications;
   }

   return Publications;
}

function storePubs(h) {
   var x = new Array();
   for( var a in h ) {
      if( h[a] == '-' || h[a] == '+' ) x.push( h[a] + a );
   }
   
   setCookie('NN_PUBS', x.join('|'), 'd2038', '/h/', '', 0, 1);
}

function resetPubs() {
   if(!confirm("This option will reset your publication preferences.\n\nAre you sure you want to proceed?")) return;

   setCookie('NN_PUBS', '', 'd2038', '/h/', '', 0, 1);   
   Publications = undefined;
   
   initPubFilters();
}

function setPub(src, mode) {
   
   var Pubs = getPubs();
   Pubs[src] = mode;
   storePubs(Pubs);
   
}

function setPubAndFilter(mode) {
   if (!source_popup) return;
   
   var src = source_popup.parentNode.getAttribute('src');

   setPub(src, mode);
   
   hidePubMenu();
   
   initPubFilters();
}

function toggleHiddenPubs() {
   
   // Enable hidden publications simply using cascading classes.
   var hidTxt;
   
   if( PubFilterIDs['newsfeed_1'] == undefined ) return;
   
   if( PubFilterIDs['newsfeed_1'].className.match(/ pub_hide$/) ) {
     
      for(var i in PubFilterIDs)
	PubFilterIDs[i].className = PubFilterIDs[i].className.replace(/( pub_show| pub_hide)?$/, ' pub_show');
      
     publicationFilterClass = 'pub_show';
     hidTxt = 'Click to hide';
   }
   else {
      
      for(var i in PubFilterIDs)
	PubFilterIDs[i].className = PubFilterIDs[i].className.replace(/( pub_show| pub_hide)?$/, ' pub_hide');
      
      publicationFilterClass = 'pub_hide';
      hidTxt = 'Click to show';
   }
   
   document.getElementById('hidden_headlines_toggle').innerHTML = hidTxt;
   return;
   
}

var PubFilterIDs = new Object;
var PubFilterTotalHidden = 0;

function initPubFilters() {
   var hidden = 0;
   
   PubFilterTotalHidden = 0;
   
   for(var i in PubFilterIDs) 
     initPubFilter(i);

}

function initPubFilter(id) {
   
   if( brVer < 4 ) return;

   if(id == undefined) id = 'newsfeed_1';

   document.body.onclick = function(e) {
      if (!e) var e = window.event;
      var tg = e.target ? e.target : e.srcElement;
      
      if(tg.nodeName == 'SPAN' && tg.className.match(/src/)) return;
      if(tg.nodeName == 'B' && tg.parentNode.nodeName == 'SPAN' && tg.parentNode.className.match(/src/)) return;
      
      hidePubMenu();
   };
   
   var newsfeed = document.getElementById(id);
   if(newsfeed == undefined) return;
   
   // First run on this id?
   if( PubFilterIDs[id] == undefined ) {
      PubFilterIDs[id] = newsfeed;
      newsfeed.className = newsfeed.className.replace(/( pub_show| pub_hide)?$/, ' pub_hide');
      
      // Ensure appropriate CSS applies, if javascript is enabled and the client-side functionality is enabled.
      if(publicationFilterClass == '') publicationFilterClass = 'pub_hide';
   }
   
   var Pubs = getPubs();
   
   var numHidden = 0;

   var lastDiv;
   var TimeSlotTotal = 0;
   var TimeSlotHidden = 0;
   var BreakTotal = 0;
   var BreakHidden = 0;
   
   var n = newsfeed.firstChild;
   
   while(n) {
      if(n.nodeName == 'P') {
	 if( n.className.match(/break/) ) {
	    if(BreakHidden == BreakTotal) {
	       n.className = 'break pub_hidden';
	    }	 
	    else n.className = 'break';
	    
	    BreakTotal = 0;
	    BreakHidden = 0;
	 }
	 else {
	    TimeSlotTotal++;
	    BreakTotal++;
	    
	    var publication = n.getAttribute('src');
	    
	    if(Pubs[publication] == '-') {
	       n.className = 'pub_hidden';
	       numHidden++;
	       TimeSlotHidden++;
	       BreakHidden++;
	    }
	    else if(Pubs[publication] == '+') {
	       n.className = 'pub_marked';
	    }
	    else {
	       if( n.className.match(/pub_(hidden|marked)/) ) n.className = '';
	    }
	    
	    var spans = n.getElementsByTagName('span');
	    
	    // Handle search results headlines, that include multiple <span>s
	    for(var i=0; i < spans.length; i++) {
	       if( spans[i].className == 'src' ) {
		  var src = spans[i];
		  src.onclick = sourceMouseClick;
	       
		  // Set time to client's localtime
		  setArticleDate(src);
	       
		  addRatingMenu(n);
		  
		  break;
	       }
	    }
	 }
      }
      
      if(n.nodeName == 'DIV') {
	 
	 if(lastDiv) {
	    if(TimeSlotHidden == TimeSlotTotal) {
	       lastDiv.className = 'tsl pub_hidden';
	    }
	    else 
	      lastDiv.className = 'tsl';
	 }
	 
	 if(n.className.match(/tsl/)) {
	    lastDiv = n;
	    TimeSlotTotal = 0;
	    TimeSlotHidden = 0;
	    BreakTotal = 0;
	    BreakHidden = 0;
	 }
	 
      }
      
      if(n.nodeName == 'BR') {
	 if(TimeSlotHidden == TimeSlotTotal) {
	    n.className = 'pub_hidden';
	 }	 
	 else n.className = '';
      }
      
      n = n.nextSibling;
   }
   
   var helpMessage = !Pubs['?'];
   
   PubFilterTotalHidden += numHidden;
   initPubFilterMsg(PubFilterTotalHidden, helpMessage);

}

// States: 0=help message; 1=no help message; 2=no help message+headlines

function initPubFilterMsg(numHidden, helpMessage) {
   
   var newsfeed = PubFilterIDs['newsfeed_1'];
   if( newsfeed == undefined ) return;
   
   // Display message about hidden publications
   var hidMsg = document.getElementById('pubfilter');

   if(!hidMsg) {
      
      if(helpMessage || numHidden)
	{
	   hidMsg = document.createElement('div');
	   hidMsg.id = 'pubfilter';
	   hidMsg.style.textAlign = 'center';
	   newsfeed.insertBefore(hidMsg, newsfeed.firstChild);
	}
      else return;
   }
   
   if(helpMessage && !numHidden) 
     {
	var hidTxt = '<span class="infobox bold">' +
	  'Tip:' +
	  // 'NEW!' +
	  " Highlight the publications you do like, and hide the ones you don't! Just click on any publication name." +
	  ' <a id="pubfilter_infobox_hidehelp" onclick="setPub(\'?\',\'-\');initPubFilter();">(Hide this tip)</a>' +
	  '</span>';
	
	hidMsg.innerHTML = hidTxt;
	return;
     }
   
   var hhn = document.getElementById('hidden_headlines_no');
      
   if(!hhn) {
      if(!numHidden) { 
	 if(hidMsg.firstChild) hidMsg.removeChild(hidMsg.firstChild);
	 return;
      }
      
      var hidTxt = '<span class="infobox"><span id="hidden_headlines_no">' + numHidden + '</span> headlines marked \'hidden\'.' +
	' <a id="hidden_headlines_toggle" href="javascript:toggleHiddenPubs()">Click to show</a>' +
	'. <a id="hidden_headlines_reset" href="javascript:resetPubs()">Reset</a>.</span>';
      
      hidMsg.innerHTML = hidTxt;
      
      hhn = document.getElementById('hidden_headlines_no');
   }
   
   if(!numHidden) hidMsg.removeChild(hidMsg.firstChild);
   else hhn.innerHTML = numHidden;
}

function AsyncHTTPRequest() {
   var obj;
   var requestCompleted = false;
   try { obj = new XMLHttpRequest(); }
   catch (e) { try { obj = new ActiveXObject("Msxml2.XMLHTTP"); }
      catch (e) { try { obj = new ActiveXObject("Microsoft.XMLHTTP"); }
	 catch (e) { obj = false; }}}
   if (!obj) return null;
   this.connect = function(URL, method, queryString, completedCallback, errorCallback, progressCallback, noCache) {
      if (!obj) return false;
      requestCompleted = false;
      method = method.toUpperCase();
      
      try {
	 if (method == "GET") {
	    obj.open(method, URL + '?' + queryString, true);
	    queryString = '';
	 } else {
	    obj.open(method, URL, true);
	    obj.setRequestHeader('Method', 'POST ' + URL + ' HTTP/1.1');
	    obj.setRequestHeader('Content-Type',
				     'application/x-www-form-urlencoded');
	 }
	 
	 if(noCache) {
	    obj.setRequestHeader('Pragma', 'no-cache');
	    obj.setRequestHeader('Cache-control', 'no-cache');
	    // For servers which ignore the cache-control directives, this
	    // aims to ensure a 200 OK response by setting an If-Modified-Since
	    // date in the past.
	    obj.setRequestHeader('If-Modified-Since', 'Wed, 11 Nov 2000 11:10:54 GMT');
	 }
	 
	 obj.onreadystatechange = function(){
	    if (obj.readyState == 4 && !requestCompleted) {
	       requestCompleted = true;
	       if(obj.status != 200 || obj.statusText == 'NewsNow-Error') {
		  errorCallback();
	       } else {
		    completedCallback(obj);
	       }
	       if(progressCallback)
		 progressCallback(false);
	       
	    }};
	 obj.onerror = errorCallback;
	 obj.send(queryString);
	 if(progressCallback)
	   progressCallback(true);
      }
      catch(z) { return false; }
      return true;
   };
   return this;
}

function validateEmail(e) {
   if(!e.match(/^([^@\s,\"<>]+)@[^@\s,%\/\"<>]+\.[^@\s,%\/\.\"<>]+$/))
     return 'Please enter a valid email address';
   return '';
}

function validateRequired(f) {
   if(f == '' || f.match(/^\s+$/))
      return 'This field is compulsory';
   return '';
}

function validateTelephone(t) {
   return '';
   return 'Please enter a valid telephone number';
}

function validateLowerCaseAlpha(f) 
{
   if(!f.match(/^[a-z]*$/)) {
      return 'Please enter only lower-case letters.';
   }
   return '';
}

function validateExactLength(f, len) {
   if(len && f.length != len) {
      return 'Please enter exactly ' + len + ' characters.';
   }
   return '';
}

var validators = 
{
   'E': validateEmail,
     'R': validateRequired,
     'T': validateTelephone,
     'L': validateExactLength,
     'a': validateLowerCaseAlpha
};

var lastErrorFields = [];

function AJAXFormSubmit(frm, validation, successCallback, failureCallback, successMsgElem, errorMessageJoiner, progressCallback ) {
   // Perform client-side validation of form fields.
   if(validation) {
      var has_errors = false;
      var fields = validation.fields;
      for(var field in fields) {
	 var types = fields[field].split('');
	 var error_message = '';
	 for(var i = 0; i < types.length; i++) {
	    var validator;
	    var elem;
	    if((validator = validators[types[i]]) && (elem = frm[field])) {
	       var validation_error;
	       if(validation_error = validator(elem.value, elem.maxLength)) {
		  // Apply custom validation message, if supplied
		  if(validation.messages && validation.messages[type])
		    validation_error = validation.messages[type];
		  has_errors = true;
		  error_message += (error_message ? errorMessageJoiner : '') + validation_error;
	       }
	    }
	 }
	 var msgElem;
	 if(msgElem = document.getElementById(frm.getAttribute('id') + '_' + field + '_err'))
	   msgElem.innerHTML = error_message;
      }
      if(has_errors)
	return false;
   }
   
   var myConn = new AsyncHTTPRequest();
   if (!myConn) {
      alert("Your browser doesn't seem to support submitting this form. Please use the latest version of Mozilla Firefox, Internet Explorer, Opera, Safari or Google Chrome.");
      return false;
   }
   
   
   var onComplete = function(oXML) {
      // Clear any previous errors
      for(var i = 0; i < lastErrorFields.length; i++){
	   lastErrorFields[i].innerHTML = '';
      }
      lastErrorFields = [];
      
      var response = eval('(' + oXML.responseText + ')');
      if(response.success) {
	 if(successMsgElem)
	   successMsgElem.innerHTML = response.message;
	 if(successCallback)
	   successCallback(oXML);
	 return;
      }
      // else: failure. Apply error messages to form fields.
      for(var i = 0; i < response.errors.length; i++) {
	 var msgElem;
	 if(msgElem = document.getElementById(frm.getAttribute('id')  + '_' + response.errors[i].field + '_err')) {
	      msgElem.innerHTML = response.errors[i].message;
	      lastErrorFields.push(msgElem);
	   }
      }
   };
   
   var onError = function() {
      alert("There was a problem submitting the form. Please try again in a few moments.");
   };

   var form_fields = '';
   for(var i = 0; i < frm.elements.length; i++) {
      if(!frm.elements[i].name)
	continue;
      if(form_fields != '')
	form_fields += '&';
      form_fields += escape(frm.elements[i].name) + '=' + escape(frm.elements[i].value);
   }
   
   var method = frm.method ? frm.method : 'post';
   var URL = frm.action;
   var post_data;
   if(method.toLowerCase == 'get') {
      URL += '?' + form_fields;
      post_data = '';
   } else {
      post_data = form_fields;
   }
   
   myConn.connect(URL, method, post_data,
		  onComplete,
		  onError,
		  progressCallback
		  );
   return false;
}

function hideSubscribe(hideid) {
   var el = document.getElementById('sub_box');
   el.parentNode.removeChild(el);
   if(hideid) document.getElementById(hideid).style.display = 'block';
   return false;
}

function hideSubscribeAfterPause() {
   window.setTimeout(hideSubscribe, 5000);
}

function subscribeFormProgress(state) {
   var throbber = document.getElementById('sub_throbber');
   var box = document.getElementById('sub_box');
   var button = document.getElementById('sub_button');
   if(throbber) {
      throbber.style.visibility = state ? 'visible': 'hidden';
   }
   if(box) {
      box.style.cursor = state ? 'wait' : '';
   }
   if(button) {
      button.disabled = state;
   }
}

function doSubscribe(frm) {
   return AJAXFormSubmit(frm, 
			 {
			    'fields': {'Email': 'RE', 'Captcha': 'RLa'}
			 },
			 null,
			 null,
			 frm,
			 '<br/>',
			 subscribeFormProgress
			 );
}

function setupCaptcha(id, oXML) {
   var data = eval('(' + oXML.responseText + ')');
   document.getElementById(id + '_img').src = '/ico/captcha.gif?k=' + data.key;
   document.getElementById(id + '_key').value = data.key;
   document.getElementById(id + '_text').maxLength = data.len;
}


function newCaptcha(id) {
   // Initiate AJAX request to set up captcha graphic
   var myConn = new AsyncHTTPRequest();
   if (!myConn)
     alert("Your browser doesn't seem to support our 'captcha' anti-spam system. Please use the latest version of Mozilla Firefox, Internet Explorer, Opera, Safari or Google Chrome.");
   
   var fnErr = function() {
      alert("There was a problem retrieivng the anti-spam graphic. Please try again in a few moments.");
   };
   
   myConn.connect('/captcha.html', 'get', '',
		  function(xml) { setupCaptcha(id,xml) },
		  fnErr,
		  null,
		  true
		  );
}

function showSubscribe(id, hideid) {
   
   var subBox = document.getElementById('sub_box');
   if(subBox) return;
   
   subBox = document.createElement('div');
   subBox.id = 'sub_box';
   
   subBox.innerHTML =
     '<form onsubmit="return doSubscribe(this)" id="subscribe" action="/subscribe.html" method="post">' +
     '<p>To subscribe to updates via email on News@NewsNow, please enter your details below and click on \'Subscribe\'.</p>' +
     '<p>Your email address:<br/><input type="text" name="Email" style="width: 95%"/><span id="subscribe_Email_err" class="error"></span></p>' +
     '<p>Your name:<br/><input type="text" name="DisplayName" style="width: 95%"/><span id="subscribe_DisplayName_err" class="error"></span></p>' +
     '<p>Please enter the text shown below:</p>' + 
     '<p style="text-align: center"><img id="sub_box_captcha_img"/> <a style="cursor:pointer; text-decoration: none; border: none" onclick="newCaptcha(\'sub_box_captcha\');"><img src="/ico/refresh.png" title="Reload graphic" style="vertical-align: top"/></a></p>' +
     '<p><input id="sub_box_captcha_text" type="text" name="Captcha" style="width: 95%"/><span id="subscribe_Captcha_err" class="error"></span></p>' +
     '<input id="sub_box_captcha_key" type="hidden" name="Key" value=""/>' +
     '<input type="hidden" name="ListID" value="2"/>' +
     '<p><input id="sub_button" type="submit" value="Subscribe"> <img src="/C/NNv4/_/ico/spinner3-white.gif" style="visibility: hidden; width: 23px; height: 23px; vertical-align: middle" id="sub_throbber"></p>' +
     '</form>' +
     '<p style="text-align: right; margin: 0; padding: 0"><img class="jlink" border="0" title="Close the subscribe box" alt="Close" src="/ico/delete.jpg" onclick="hideSubscribe(\'' + (hideid || '') + '\')"/></p>';
   
   subBox.style.display = 'block';
   
   document.getElementById(id).appendChild(subBox);
   
   if(hideid) document.getElementById(hideid).style.display = 'none';
   newCaptcha('sub_box_captcha');
   return false;

}

function signinFormProgress(state) {
   var throbber = document.getElementById('signin_throbber');
   var frm = document.getElementById('signin_form');
   var button = document.getElementById('signin_button');
   if(throbber) {
      throbber.style.visibility = state ? 'visible': 'hidden';
   }
   if(frm) {
      frm.style.cursor = state ? 'wait' : '';
   }
   if(button) {
      button.disabled = state;
   }
}


function doSignin(frm, elID) {
   var onSuccess = function ()  {
      document.getElementById(elID).innerHTML = '<p><b>You are now signed in.</b> <a href="/h/?signed_in=1">Click here</a> to go back to the NewsNow site and use the My Feeds menu on the left to manage your feeds.</p>';
   };
   
   return AJAXFormSubmit(frm,
			 {
			    'fields': {'Email': 'RE', 'Password': 'R'}
			 },
			 onSuccess,
			 null,
			 frm,
			 '<br/>',
			 signinFormProgress
			 );
}

function showSignin(elID) {
document.getElementById(elID).innerHTML =
     '<form id="signin" action="/signin.html" method="post" style="position: relative; background-color: #FFFFFF" onsubmit="return doSignin(this, \'' + elID + '\')">' +
     '<table id="signin_form" style="background-color: #FFFFFF; position: absolute; z-index: 100; left: 0px; top: 0px; padding: 5px; margin-top: 10px; border: 1px solid #666; width: auto">' +
     '<tr><th colspan="2">Enter your details to log in to OpenSearch:</th></tr>' +
     '<tr><th>Email:</th><td><input type="text" name="Email"/><span id="signin_Email_err" class="error"></span></td></tr>' +
     '<tr><th>Password:</th><td><input type="password" name="Password"/><span id="signin_Password_err" class="error"></span></td></tr>' +
     '<tr><td colspan="2"><input type="submit" id="signin_button" value="Sign in"/>' + 
     '<img src="/C/NNv4/_/ico/spinner3-white.gif" style="visibility: hidden; width: 23px; height: 23px; vertical-align: middle" id="signin_throbber"/>' +
     '</td></tr>' + 
     '</table>' +
     '</form>';
}

function doSignout(elID) {
   var myConn = new AsyncHTTPRequest();
   if (!myConn) {
      alert("Your browser doesn't seem to be allowing you to sign out.");
      return;
   }
   
   var onComplete = function(oXML) {
      document.getElementById(elID).innerHTML = '';
   };
   
   var onError = function() {
      alert("There was a problem signing out. Please try again in a few moments.");
   };

   myConn.connect('/signout.html', 'post', null,
		  onComplete,
		  onError,
		  null // Progress callback
		  );

}

function editFeedProgress(state) {
   var throbber = document.getElementById('editfeed_throbber');
   var frm = document.getElementById('editfeed_form');
   var button = document.getElementById('editfeed_button');
   if(throbber) {
      throbber.style.visibility = state ? 'visible': 'hidden';
   }
   if(frm) {
      frm.style.cursor = state ? 'wait' : '';
   }
   if(button) {
      button.disabled = state;
   }
}

function doEditFeed(frm) {
   return AJAXFormSubmit(frm,
			 {
			    'fields': {'Name': 'R', 'HeadlineSearch': '', 'BodySearch': '', 'ExcludeSearch': '', 'Language': '', 'Country': ''}
			 },
			 null,
			 null,
			 frm,
			 '<br/>',
			 editFeedProgress
			 );
}

function deleteFeed(feedName, feedID) {
   if(!confirm('Really delete "' + feedName + '"?')) return;
   
   var myConn = new AsyncHTTPRequest();
   if (!myConn) {
      alert("Your browser doesn't seem to be allowing you to sign out.");
      return;
   }
   
   var onComplete = function(oXML) {
      alert("Feed deleted.");
   };
   
   var onError = function() {
      alert("There was a problem deleting the feed. Please try again in a few moments.");
   };

   myConn.connect('/delete_feed.html', 'post', 'id=' + escape(feedID),
		  onComplete,
		  onError,
		  null // Progress callback
		  );

   
   
}


function onLoad() {
   //   enableAds();
}

function installSearchEngine( host ) {
  var url = '';
  var imgurl ='';
  if ( host ) {
    url = 'http://' + host;
    imgurl = url;
  }
  url = url + '/searchplugin.';
  if (window.external && ("AddSearchProvider" in window.external)) {
  // Firefox 2 and IE 7, OpenSearch
    url = url + 'xml';
    window.external.AddSearchProvider(url);
  }
  else {
    // No search engine support (IE 6, Opera, etc).
    // Right now we're not supporting FF 1.x or Sherlock (and Sherlock has
    // been declared dead by Apple anyway, as of Mac OS X 10.5)
    alert("No search engine support");
  }
  return false;
}

function setPopup( id, display ) {
  var ovl = document.getElementById( id + '_overlay' );
  var pop = document.getElementById( id + '_popup' );
  if ( !ovl || !pop ) return(false);

  document.getElementById( 'linuxFlash' ).style.display = display;
  ovl.style.display = display;
  pop.style.display = display;

  return(false);
}

var submenus = {};

function homepageHelpText( path ) {
var HelpText;
if ( (brUA.indexOf("msie") != -1) && (brUA.indexOf("opera") == -1) ) {
  HelpText = 'Click on the "down" arrow just to the right of the "house" ' +
    'icon in your Internet Explorer toolbar and choose "Add or '  +
    'change Home Page." Then click on "Use this webpage as your ' +
    'only home page" or "Add this webpage to your home page '     +
    'tabs," depending on your preference.';
} else if ( brUA.indexOf("gecko") != -1 ) {
  HelpText = 'To make this page your home page, simply drag ' +
    '<a href="' + path + '">this link</a> onto ' +
    'the "home" icon in your toolbar.';
} else if ( brUA.indexOf("opera") != -1 ) {
  HelpText = 'You can make this page your home page by setting it in ' +
    'Tools => Preferences => General.';
} else {
  HelpText = 'You can set your home page through the preferences of your ' +
    'browser.';
}
 return HelpText;

}
