/***************************************************************
 *                   CROPfm client side JS library             *
 ***************************************************************/

function openGuestWin(guest_id) {
  var guest_url = host_name + "/cropfm/jsp/getguestinfo.jsp?guestid=" + guest_id;

  if ( guest_win == null || guest_win.closed == true || typeof guest_win.current_guest != 'string' ) {
    guest_win = window.open("about:blank", guest_win_obj.name, guest_win_obj.properties);
    try {
      // try catch for IE...
      guest_win.document.title = getDisplayName(guest_id);
      guest_win.document.open();
      guest_win.document.write(header_style + loading_res_style + footer);
      guest_win.document.close();
    } catch (e) {
      guest_win = window.open("about:blank", guest_win_obj.name, guest_win_obj.properties);
    }
    guest_win.location.href = guest_url;
  } else {
    if ( guest_win.top.current_guest != guest_id ) {
      if ( guests_cache[guest_id] && 
           guests_cache[guest_id].html != null ) {
        // set the correct guest id, name and write html (order!)
        guest_win.current_guest = guest_id;
        guest_win.document.title = getDisplayName(guest_id);
        guest_win.document.body.innerHTML = guests_cache[guest_id].html;
      } else {
        guest_win.current_guest = guest_id;
        guest_win.document.title = getDisplayName(guest_id);
        guest_win.document.body.innerHTML = top.loading_res_style;
        guest_win.location.href = guest_url;
      }
    }
  }
  try {
    // FIXME IE...
    guest_win.focus();
  } catch (e) {
  }
}

function openOptionsWin() {
  /*** opens the options window **/
  if ( top.options_win == null || top.options_win.closed == true ) {
    top.options_win = top.open( host_dir + "options.htm", options_win_obj.name, options_win_obj.properties);
  }
  
  try {
    // FIXME IE...
    options_win.focus();
  } catch (e) {
  }
}

function lib_openMail() {
  var to = "cropfm" + "@" + "mur.at";
  location.href = "mailto:" + to;
}

function lib_openGuestMail(mail) {
  location.href = "mailto:" + mail;
}

function lib_checkOpener() {
  // see if opener exists in guest win
  return true;
}

function lib_displayPermalink(aShowId, aShowTitle) {
  // shows the directlink to show in a pop up
  var display_title = aShowTitle ? aShowTitle : " ";
  var display_url = top.show_link_server_url + aShowId;
  
  if( window.clipboardData && clipboardData.setData ) {
      clipboardData.setData("Text", display_url);
  }
  
  perma_win = window.open(top.host_dir + "permalink.htm" + "?title=" + display_title + "&url=" + display_url, perma_win_obj.name, perma_win_obj.properties);
  perma_win.focus();
}

// **** functions to determine a link target *****

function lib_getLinkTarget(URL) {
  // checks if supplied URL is absolute and returns target
  if ( URL.match("^http:") ) {
    return "_blank";
  } else {
    return "_top";
  }
}

function lib_isExtTarget(URL) {
  // checks if supplied URL is absolute and returns target
  if ( URL.match("^http:") ) {
    return true;
  } else {
    return false;
  }
}


function lib_setStartDate(silent) {
  // sets the new startdate in current_query when input hold valid date
  if ( !top.frames["contentFrame"].document.forms[0] )
    return;

  var silent = (silent) ? silent:false;
  var is_start_date = top.startDateChooser.prs_date(top.frames["contentFrame"].document.forms[0].startdate_inp.value, silent);

  if ( is_start_date ) {
    top.tmp_searchform.startdate = top.frames["contentFrame"].document.forms[0].startdate_inp.value;
  } else {
    top.frames["contentFrame"].document.forms[0].startdate_inp.value = top.tmp_searchform.startdate;
  }
}

function lib_setEndDate(silent) {
  // sets the new enddate in current_query when input hold valid date
  if ( !top.frames["contentFrame"].document.forms[0] )
    return;

  var silent = (silent) ? silent:false;
  var is_end_date = top.endDateChooser.prs_date(top.frames["contentFrame"].document.forms[0].enddate_inp.value, silent);

  if ( is_end_date ) {
    top.tmp_searchform.enddate = top.frames["contentFrame"].document.forms[0].enddate_inp.value;
  } else {
    top.frames["contentFrame"].document.forms[0].enddate_inp.value = top.tmp_searchform.enddate;
  }
}

function lib_prepareDateForUI(aDBDateString) {
  // converts dates used in DB dates into dates that can be displayed, date must be valid!
  if ( aDBDateString == notset )
    return notset;
  var date_exp = new RegExp ( "(\\d{4})-?(\\d{2})-?(\\d{2})" );
  var date_parts = date_exp.exec(aDBDateString);
  return date_parts[3] + "-" + date_parts[2] + "-" + date_parts[1];
}

function lib_prepareDateForDB(aUIDateString) {
  // converts dates displayed in UI into dates that the backend understands, date must be valid!
  var date_exp = new RegExp ( "(\\d{2})-(\\d{2})-(\\d{4})" );
  var date_parts = date_exp.exec(aUIDateString);
  return date_parts[3] + "" + date_parts[2] + "" + date_parts[1];
}

function lib_formatDateString(aDate) {
	return [
    ((aDate.getDate() < 10) ? "0":""), aDate.getDate(), ".", 
    ((aDate.getMonth() < 9) ? "0":""), aDate.getMonth() + 1, ".",
    aDate.getFullYear(), ", ",
    ((aDate.getHours() < 10) ? "0":""), aDate.getHours(), ":", 
    ((aDate.getMinutes() < 10) ? "0":""), aDate.getMinutes(), ":", 
    ((aDate.getSeconds() < 10) ? "0":""), aDate.getSeconds() ].join("");
}

function lib_boolToString(aBool) {
  // IE (5.0) doesn't know toString()...
  if (aBool) 
    return "true";
  else
    return "false";
}

function lib_getFirstProperty(anObject) {
  // returns the name of the first property in the anObject
  if ( anObject == null ) 
    return;
  for ( var pn in anObject )
    return pn;
}

function getDefaultEntriesString() {
  var the_entries = "0";

  if ( page_size > 1 ) {
    for (var e=1;e<page_size;e++) {
      the_entries+= "," + e;
    }
  }
  return the_entries;
}

function lib_getOptionsCookie() {
  var my_cookie = document.cookie;
  var ret_obj = {
                  pagesize: notset,
                  sortorder: notset,
                  textsize: notset
                };

  var my_pagesize = new RegExp( c_pagesize + "=(\\d+)").exec(my_cookie);
  var my_sortorder = new RegExp( c_sortorder + "=(\\w+)").exec(my_cookie);
  var my_textsize = new RegExp( c_textsize + "=(\\d+)").exec(my_cookie);

  if ( my_pagesize && my_pagesize[1] != null ) 
    ret_obj.pagesize = my_pagesize[1];

  if ( my_sortorder && my_sortorder[1] != null ) 
    ret_obj.sortorder = my_sortorder[1];

  if ( my_textsize && my_textsize[1] != null ) 
    ret_obj.textsize = my_textsize[1];
  
  return ret_obj;
}

function lib_storeComOptionsCookie(aSortorder, aTextsize) {
  /** stores options settings in cookie **/
  // cookie expires date 
  var cookie_expires = new Date(new Date().getTime() + (3 * 24 * 60 * 60 * 1000 )).toGMTString();
  if (aSortorder != null) 
	  document.cookie = c_comsort + "=" + aSortorder + "; expires=" + cookie_expires + ";path=" + home_dir;
  
  if (aTextsize != null)
	  document.cookie = c_comsize + "=" + aTextsize + "; expires=" + cookie_expires + ";path=" + home_dir;
}

function lib_getComOptionsCookie() {
  var my_cookie = document.cookie;
  var ret_obj = {
                  comsize: notset,
                  comsort: notset
                };
  var my_comsize = new RegExp( c_comsize + "=(\\d+)").exec(my_cookie);
  var my_comsort = new RegExp( c_comsort + "=(\\d+)").exec(my_cookie);
	  
  if ( my_comsize && my_comsize[1] != null ) 
    ret_obj.comsize = my_comsize[1];

  if ( my_comsort && my_comsort[1] != null ) 
    ret_obj.comsort = my_comsort[1];
  
  return ret_obj;
}

function lib_storeOptionsCookie(aPagesize, aSortorder, aTextsize) {
  /** stores options settings in cookie **/
  // cookie expires date 
  var cookie_expires = new Date(new Date().getTime() + (3 * 24 * 60 * 60 * 1000 )).toGMTString();

  document.cookie = c_pagesize + "=" + aPagesize + "; expires=" + cookie_expires + ";path=" + home_dir;
  document.cookie = c_sortorder + "=" + aSortorder + "; expires=" + cookie_expires + ";path=" + home_dir;
  document.cookie = c_textsize + "=" + aTextsize + "; expires=" + cookie_expires + ";path=" + home_dir;
}

function lib_storeTextsizeCookie( aTextsize ) {
  /** stores textsize setting in cookie **/
  // cookie expires date 
  var cookie_expires = new Date(new Date().getTime() + (3 * 24 * 60 * 60 * 1000 )).toGMTString();

  document.cookie = c_textsize + "=" + aTextsize + 
  "; expires=" + cookie_expires + ";path=" + home_dir;
}

function hasStoredQuery() {
  /**** checks cookie for stored query and requests shows if so ****/

  var my_cookie = document.cookie;
  var flag_exp = new RegExp( c_flag + "=true" );

  if ( my_cookie.match(flag_exp) &&
       top.the_hash == '' &&
       top.the_search == '' ) {

    var mode = new RegExp( c_mode + "=(\\d+)").exec(my_cookie);
    
    if (mode == null)
      return false;
      
    switch (mode[1]) {
      case "1":
        var andit = new RegExp( c_andit + "=(\\w+)").exec(my_cookie);
        var whole = new RegExp( c_whole + "=(\\w+)").exec(my_cookie);
        var ftquery = new RegExp( c_ftquery + "=([\\w|\\s]+)").exec(my_cookie);

        if ( andit && andit[1] != null && andit[1] == "true" )
          andit = true;
        else
          andit = false;
          
        if ( whole && whole[1] != null && whole[1] == "true" )
          whole = true;
        else
          whole = false;

        if ( ftquery && ftquery[1] != null ) {
          getContentQueryShows ( ftquery[1] ,andit, whole);
          return true;
        }
      break;
      case "2":
        var guest_id = new RegExp( c_guestid + "=(\\w+)").exec(my_cookie);
        if ( guest_id && guest_id[1] != null ) {
          getGuestShows ( guest_id[1] );
          return true;
        }
      break;
      case "3":
        var startdate = new RegExp( c_startdate + "=(\\w+)").exec(my_cookie);
        var enddate = new RegExp( c_enddate + "=(\\w+)").exec(my_cookie);
        var subject = new RegExp( c_subject + "=(\\w+)").exec(my_cookie);
        
        // all three values can be false (=default query)
        startdate = ( startdate && startdate[1] == null ) ? false : startdate[1];
        enddate = ( enddate && enddate[1] == null ) ? false : enddate[1];
        subject = ( subject && subject[1] == null ) ? false : subject[1];
        
        getCronologicalShows( startdate, enddate, subject );
        return true;
      break;
      case "4":
        var show_id = new RegExp( c_showid + "=(\\w+)").exec(my_cookie);
        if ( show_id && show_id[1] != null ) {
          getSinglemodeShow ( show_id[1] );
          return true;
        }
      break;
    }
  }
  // no query is stored in cookie
  return false;
}

function lib_isSameQuery(cmpQuery) {
  var isSame = true;
  for (var qp in cmpQuery) {
    if ( top.current_query[qp] != cmpQuery[qp] )
      isSame = false;
  }
  return isSame;
}

// compares current_query and last_query with default_query
function lib_hasDefaultQuery () {
  // compare to last query if exists
  var isSame = true;
  if (top.last_query != null) {
	for (var qp in top.default_query) {
	  if ( top.last_query.query[qp] != top.default_query[qp] )
	    isSame = false;
	}
  } else {
    isSame = false;
  }
  return lib_isSameQuery(top.default_query) || isSame;
}

function storeQueryCookie() {
  /** stores current_query in the cookie, must be called in channel **/
  
  var cookie_expires = new Date(new Date().getTime() + top.ttl_global_query_cache ).toGMTString();

  document.cookie = c_flag + "=true" + "; expires=" + cookie_expires;
  document.cookie = c_mode + "=" + current_query.mode + "; expires=" + cookie_expires;
  document.cookie = c_ftquery + "=" + current_query.ftquery + "; expires=" + cookie_expires;
  document.cookie = c_andit + "=" + (( current_query.ftflags.substring ( 0, 1 ) == "1" ) ? "true" : "false") + "; expires=" + cookie_expires;
  document.cookie = c_whole + "=" + (( current_query.ftflags.substring ( 1, 2 ) == "1" ) ? "true" : "false") + "; expires=" + cookie_expires;
  document.cookie = c_guestid + "=" + current_query.guestid + "; expires=" + cookie_expires;
  document.cookie = c_startdate + "=" + current_query.startdate + "; expires=" + cookie_expires;
  document.cookie = c_enddate + "=" + current_query.enddate + "; expires=" + cookie_expires;
  document.cookie = c_subject + "=" + current_query.subject + "; expires=" + cookie_expires;
  document.cookie = c_showid + "=" + current_query.showid + "; expires=" + cookie_expires;
}

function storeCurrentQuery() {
  /** stores the current query if exists. Used for "back to last search" button **/
  if ( shows_cache.length != 0 && current_query.mode != null ) {
    top.last_query = {
                       query: top.current_query,
                       shows: top.shows_cache,
                       page: top.current_page,
                       rslength: top.rs_length
                     };
  }
}

function restoreLastQuery() {
  /** restores the last query and paints the listing **/
  if ( last_query == null )
    return;
  
  // restore the last query and save in cookie  
  top.current_query = last_query.query;
  storeQueryCookie();
 
  top.tmp_searchform = {
                         ftquery: last_query.query.ftquery,
                         andit: last_query.query.ftflags.substring ( 0, 1 ) == "1",
                         whole: last_query.query.ftflags.substring ( 1, 2 ) == "1",
                         guestid: last_query.query.guestid,
                         startdate: lib_prepareDateForUI ( last_query.query.startdate ),
                         enddate: lib_prepareDateForUI ( last_query.query.enddate ),
                         subject: last_query.query.subject
                       };
  
  top.shows_cache = last_query.shows;
  top.rs_length = last_query.rslength;
  top.current_page = last_query.page;

  // page size could have changed...
  var my_num_pages = Math.ceil(rs_length/page_size) - 1;
  if ( top.current_page > my_num_pages )
    top.current_page = my_num_pages;
  
  // set active search tab according to search mode
  switch (last_query.query.mode) {
    case 1: top.active_search_tab = 0; break;
    case 2: top.active_search_tab = 1; break;
    case 3: top.active_search_tab = 2; break;
    default: top.active_search_tab = 0;
  }
  
  top.last_query = null;
    
  top.paint();
}

function lib_reverseShowsCache() {
  var tmp_shows_cache = [];
  // reverse shows cache
  for ( var s=1; s<=top.rs_length; s++ ) {
    if ( top.shows_cache[s-1] != null )
      tmp_shows_cache [ top.rs_length - s ] = top.shows_cache [ s - 1 ];
  }
  top.shows_cache = tmp_shows_cache;
  tmp_shows_cache = [];
  
  // reverse last_query shows cache if exists
  if ( top.last_query != null ) {
    for ( var s=1; s<=top.last_query.rslength; s++ ) {
      if ( top.last_query.shows[s-1] != null )
        tmp_shows_cache [ top.last_query.rslength - s ] = top.last_query.shows[s-1];
    }
    top.last_query.shows = tmp_shows_cache;
  }  
}

function lib_hasInvalidChars(anFTString) {
  var char_exp;
  for ( ic=0; ic<top.invalid_chars.length; ic++ ) {
    char_exp = new RegExp(top.invalid_chars[ic]);
    if ( anFTString.search ( char_exp ) > -1 )
      return true;
  }
  return false;
}

function lib_isValidSearchString(anFTString, anAnditFlag) {

  var raw_strings = anFTString.split(" ");
  var search_strings = [];

  // remove multiple spaces...
  for ( var rs=0; rs<raw_strings.length; rs++ ) {
    if ( raw_strings[rs].length > 0 )
      search_strings [ search_strings.length ] = raw_strings[rs];
  }
  
  if ( !anAnditFlag ) {
    for ( var ss=0; ss<search_strings.length; ss++ ) {
      if ( search_strings[ss].length < 3 )
        return false;
    }
    return true;
  } else {
    for ( var ss=0; ss<search_strings.length; ss++ ) {
      if ( search_strings[ss].length > 2 )
        return true;
    }
    return false;
  }
}

function clearClientCache() {
	top.shows_cache = [];
	top.current_page = 0;
}


function clearChannel() {
  // URL must be reset so data (cookie!) is not overwritten on reload
  top.comFrame.location.href = "about:blank";

}

function getDisplayName(guestID) {
	//Constructs the display name otut of guest data
	var display_name = "";
	
	if ( top.guests_cache[guestID] ) {
	
  	  if ( top.guests_cache[guestID].title != "" )
  	  	   display_name += top.guests_cache[guestID].title + " ";
		 
	  if ( top.guests_cache[guestID].firstname != "" )
		   display_name += top.guests_cache[guestID].firstname + " ";
		 
	  if ( top.guests_cache[guestID].middlename != "" )
		   display_name += top.guests_cache[guestID].middlename + " ";
		 
	  if ( top.guests_cache[guestID].lastname != "" )
		   display_name += top.guests_cache[guestID].lastname;
   	  
   	  return display_name;
   	} else {
   	  // guest not in db, just return the id
   	  return guestID;
   	}
}

function lib_getSubjectTitle(aSubjectID) {
  // returns the subject title or ID if unknown subject
  if ( subjects_cache[aSubjectID] ) {
    return subjects_cache[aSubjectID].title;
  } else {
    return aSubjectID;
  }
}

function paintVerticalLink(aBullet, aLabel, aHref, aFunc, aTarget, anAlign) {
  link_html = "<div style='width:100%; text-align:" + anAlign + ";'>" + 
              paintLink(false, aBullet , getVerticalHtml(aLabel), aHref, aFunc, aTarget) +
              "</div>";
  return ( link_html );
}

function paintLink(paragraph, aBullet, aLabel, aHref, aFunc, aTarget) {
  var link_html = '';

  if (paragraph)
    link_html += "<p>";

  if (aBullet)
    link_html += aBullet;

  link_html += "<a href='" + aHref + "'";

  if (aFunc)
    link_html += " onClick='" + aFunc + ";void(0)'";

  if (aTarget)
    link_html += " target='" + aTarget + "'";

  link_html += ">" + aLabel + "</a>";

  if (paragraph)
    link_html += "</p>";

  return ( link_html );
}
    

function paintAppLink(aType, aLabel, aFunc, aHref, anAlign) {
  var link_html = '';
  
  if (!top.req_pending) {
    // when no request is pending links are active
    switch (aType) {
      case "less":
        link_html = "<p align='" + anAlign + "' style='font-size:14px;'>&lt;&lt; " +
                    "<a class='appLink' href='" + aHref + 
                    "' onClick='" + aFunc + "; void(0);'>";
        if (aLabel)
          link_html += aLabel;
        else            
          link_html += "less";
        link_html += "</a></p>";
   	  break;
      case "more":
        link_html = "<p align='" + anAlign + "' style='font-size:14px;'>&gt;&gt; " + 
                    "<a class='appLink' href='" + aHref + 
                    "' onClick='" + aFunc + "; void(0);'>";
        if (aLabel)
          link_html += aLabel;
        else            
          link_html += "more";
        link_html += "</a></p>";
      break;
      case "show":
        link_html = top.link_bullet + " <a class='appLink' href='" + aHref + 
                    "' onClick='" + aFunc + "; void(0);'>";
        link_html += aLabel;
        link_html += "</a>";
      break;
      case "inline":
        link_html = "<a class='appLink' href='" + aHref + 
                    "' onClick='" + aFunc + "; void(0);'>";
        link_html += aLabel;
        link_html += "</a>";
      break;
      case "vertical":
        if (!anAlign)
          anAlign = "center";
          
        link_html = "<div class='inactiveAppLink' style='width:100%; text-align:" + anAlign + "'>" +
                    "<a style='font-size:14px;' href='" + aHref + 
                    "' onClick='" + aFunc + "; void(0);'>";
        if (aLabel)
          link_html += getVerticalHtml(aLabel);
        else            
          link_html += "m<br>o<br>r<br>e";
          
        link_html += "</a></div>";
	  break;
	}
  } else {
    // request pending, links deactivated...
    switch (aType) {
      case "less":
        link_html = "<p align='" + anAlign + "' class='inactiveAppLink' style='font-size:14px;'>&lt;&lt; ";
        if (aLabel)
          link_html += aLabel;
        else            
          link_html += "less";
        link_html += "</p>";
   	  break;
      case "more":
        link_html = "<p align='" + anAlign + "' class='inactiveAppLink' style='font-size:14px;'>&gt;&gt; ";
        if (aLabel)
          link_html += aLabel;
        else            
          link_html += "more";
        link_html += "</p>";
      break;
      case "show":
        link_html = "<span class='inactiveAppLink'>" + top.link_bullet_inactive;
        link_html += " " + aLabel;
        link_html += "</span>";
	  break;
      case "inline":
        link_html = "<span class='inactiveAppLink'>";
        link_html += aLabel;
        link_html += "</span>";
	  break;
      case "vertical":
        if (!anAlign)
          anAlign = "center";
        link_html = "<div style='width:100%; text-align:" + anAlign + "' class='inactiveAppLink' font-size:14px;>";
        if (aLabel)
          link_html += getVerticalHtml(aLabel);
        else            
          link_html += "m<br>o<br>r<br>e";
        link_html += "</div>";
 	  break;
	}
  }
    
  return ( link_html );
}

function getVerticalHtml(aText) {
  var hor_label = new Array();
  for (c=0;c<aText.length;c++)
    hor_label[c] = aText.substring(c,c+1); 
  return hor_label.join("<br>");
}

function paintButton(aLabel, aFunction, anOverClass, isActive, anActiveClass, anInactiveClass, aWidth, anInlineFlag) {
  // returns the HTML of a button, default label "x"
  var the_html = [];

  // the (hopfully) unique id
  var my_id = Math.round(Math.random() * 1000000);
  
  if ( isActive ) {
    if ( anActiveClass ) {
      var active_class = anActiveClass;
    } else {
      var active_class = "cropfmButtonActive";
    }
  } else {
    if ( anInactiveClass ) {
      var active_class = anInactiveClass;
    } else {
      var active_class = "cropfmButtonInactive";
    }
  }
  
  if ( anOverClass ) {
    var over_class = anOverClass;
  } else {
    var over_class = "cropfmButtonOver";
  }
  
  var table_style = ( anInlineFlag ) ? "style='display:inline-table" : "style='";
  table_style += ( isActive ) ? ";cursor:hand'" : "'"
  
  var my_width = ( aWidth ) ? aWidth + ":px" : "";
  var my_left = ( isActive ) ?  top.icon_location + top.button_left : top.icon_location + top.button_left_inactive;
  var my_top = ( isActive ) ?  top.icon_location + top.button_top : top.icon_location + top.button_top_inactive;
  var my_right = ( isActive ) ?  top.icon_location + top.button_right : top.icon_location + top.button_right_inactive;
  var my_bottom = ( isActive ) ?  top.icon_location + top.button_bottom : top.icon_location + top.button_bottom_inactive;
  
  // start of button table
  if ( isActive ) {
    the_html[the_html.length] = [ "<table id='button", my_id, "' onclick='", aFunction, "; return void(0);' onmouseover='top.lib_buttonMouseOver(\"", my_id, "\",\"", over_class, "\")' onmouseout='top.lib_buttonMouseOut(\"", my_id, "\",\"", active_class, "\")' border='0' cellpadding='0' cellspacing='0'", table_style, "><tr>" ].join("");
  } else {
    the_html[the_html.length] = [ "<table border='0' cellpadding='0' cellspacing='0'", table_style, "><tr>" ].join("");
  }
  
  the_html[the_html.length] = [ "<td rowspan='3'><img src='", my_left, "' width='10' height='30'></td>" ].join("");
  the_html[the_html.length] = [ "<td style='height: 6px; background: url(", my_top, ") repeat-x'><img width='", my_width, "' height='1' src='", icon_location, "empty.gif'></td>" ].join("");
  the_html[the_html.length] = [ "<td rowspan='3'><img src='", my_right, "' width='10' height='30'></td>" ].join("");
  the_html[the_html.length] = [ "</tr><tr><td id='", my_id, "' class='", active_class, "'>" ].join("");
  
  // the label "x" is default
  if (aLabel) 
    the_html[the_html.length] = aLabel;
  else
    the_html[the_html.length] = "x";
  
  // end of button table
  the_html[the_html.length] = [ "</td></tr><tr><td style='height: 6px; background: url(", my_bottom, ") repeat-x'></td>" ].join("");
  the_html[the_html.length] = "</tr></table>";
  
  
  return the_html.join("");
}

function lib_paintMediaEgg(anID, aType, show) {
  // returns the HTML of a media egg (link to audio files)
  var egg_html = [];
  var show_id = show.showid;
  var download_extension = ( aType == "real" ) ? ".rm" : ".mp3";
  var online_extension = ( aType == "real" ) ? ".ram" : ".m3u";
  var speaker_icon = ( aType == "real" ) ? top.real_speaker[0].src : top.mp3_speaker[0].src;
  var disk_icon = ( aType == "real" ) ? top.real_disk[0].src : top.mp3_disk[0].src;
  var file_size = ( aType == "real" ) ? show.ra:show.mp3;
  file_size = lib_prepareSizeInfo ( file_size );
  

  switch (aType) {
    case "real":
      egg_html[egg_html.length] = "<table cellspacing=0 cellpadding=0 border=0 style='display:inline'><tr><td width=60 height=22>";
      // the speaker
      egg_html[egg_html.length] = [ "<a href='", top.listen_servlet, "?type=", aType, "&id=", show_id, 
                                    "' onMouseOver='top.", anID, ".openSpeaker()' onMouseOut='top.", anID, ".closeSpeaker()'><img src='", speaker_icon, "'",
                                    " border='0' id='", anID, "_speaker' title='", top.title_real_ol, "'></a>" ].join("");

      egg_html[egg_html.length] = "</td></tr><tr><td width=60 height=22>";

      // the disk
      egg_html[egg_html.length] = [ "<a href='", ( top.use_dl_servlet_in_ps ? [ dl_servlet, "?file=sendung_", show_id, download_extension, "&path=", real_dl_path ].join("") : [ real_dl_path, "sendung_", show_id, download_extension ].join("") ), 
                                    "' onMouseOver='top.", anID, ".openDisk()' onMouseOut='top.", anID, ".closeDisk()'", (document.all?" target='_dl'":""), "><img src='", disk_icon, "'",
                                    " border='0' id='", anID, "_disk' title='", top.title_real_dl, file_size, " MB","'></a>" ].join("");
              
      egg_html[egg_html.length] = "</td></tr></table>";
    break;
    case "mp3":
      egg_html[egg_html.length] = "<table cellspacing=0 cellpadding=0 border=0 style='display:inline'><tr><td width=60 height=22>";
      // the speaker
      egg_html[egg_html.length] = [ "<a href='", top.listen_servlet, "?type=", aType, "&id=", show_id,
                                    "' onMouseOver='top.", anID, ".openSpeaker()' onMouseOut='top.", anID, ".closeSpeaker()'><img src='", speaker_icon, "'",
                                    " border='0' id='", anID, "_speaker' title='", top.title_mp3_ol, "'></a>" ].join("");

      egg_html[egg_html.length] = "</td></tr><tr><td width=60 height=22>";

      // the disk
      egg_html[egg_html.length] = [ "<a href='", ( top.use_dl_servlet_in_ps ? [ dl_servlet, "?file=sendung_", show_id, download_extension, "&path=", mp3_dl_path ].join("") : [ mp3_dl_path, "sendung_", show_id, download_extension ].join("") ),
                                    "' onMouseOver='top.", anID, ".openDisk()' onMouseOut='top.", anID, ".closeDisk()'", (document.all?" target='_dl'":""), "><img src='", disk_icon, "'",
                                    " border='0' id='", anID, "_disk' title='", top.title_mp3_dl, file_size, " MB'></a>" ].join("");
              
      egg_html[egg_html.length] = "</td></tr></table>";
    break;
  }
  return egg_html.join("");
}

function lib_paintIconLink(aType, aLabel, anURL, anID, aTitle, aStyle, aTarget, aSrcArray, aFrame) {
  var icon_html = [];
  var my_target = aTarget ? "target='" + aTarget + "'" : "";
  
  icon_html[icon_html.length] = "<table";
  if ( aStyle )
    icon_html[icon_html.length] = [ " style='", aStyle, "'>" ].join("");
  else
    icon_html[icon_html.length] = ">";
    
  icon_html[icon_html.length] = "<tr><td>";
  
  // if type is "custom" there must be aSrcArray
  var iconArray = ( aSrcArray ? aSrcArray : ["",""] );
 
    
  icon_html[icon_html.length] = [ "<a href='", anURL, "' ", my_target, " ",
                                  "onmouseover='top.lib_activateIcon(\"", anID, aType, "\",\"", aType, "\",\"", iconArray[1], "\",\"", aFrame, "\")' ", 
                                  "onmouseout='top.lib_deactivateIcon(\"", anID, aType, "\",\"", aType, "\",\"", iconArray[0], "\",\"", aFrame, "\")'>"
                                ].join("");
                                
  icon_html[icon_html.length] = [ "<img id='", anID, aType, "' class='iconLink' " ].join("");

  switch (aType) {
    case "real_ol":
      icon_html[icon_html.length] = [ "src='", top.icon_location, top.real_ol, "' border='0'" ].join("");
    break;  
    case "real_dl":
      icon_html[icon_html.length] = [ "src='", top.icon_location, top.real_dl, "' border='0'" ].join("");
    break;  
    case "mp3_ol":
      icon_html[icon_html.length] = [ "src='", top.icon_location, top.mp3_ol, "' border='0'" ].join("");
    break;  
    case "mp3_dl":
      icon_html[icon_html.length] = [ "src='", top.icon_location, top.mp3_dl, "' border='0'" ].join("");
    break;  
    case "news":
      icon_html[icon_html.length] = [ "src='", top.icon_location, top.news_icon, "' border='0'" ].join("");
    break;  
    case "chat":
      icon_html[icon_html.length] = [ "src='", top.icon_location, top.chat_icon, "' border='0'" ].join("");
    break;  
    case "video":
      icon_html[icon_html.length] = [ "src='", top.icon_location, top.video_dl, "' border='0'" ].join("");
    break;
    case "donate":
        icon_html[icon_html.length] = [ "src='", top.icon_location, top.spenden_icon, "' border='0'" ].join("");
    break;
    default:
      // Any other type handled here.
      // FIXME: "mp3_dl" is default when no array provided, a generic icon should be used here...
      if ( iconArray ) {
        icon_html[icon_html.length] = [ "src='", top.icon_location, iconArray[0], "' border='0'" ].join("");
      } else {
        icon_html[icon_html.length] = [ "src='", top.icon_location, top.mp3_dl, "' border='0'" ].join("");
      }
    break;  
  }
  
  if ( aTitle ) 
    icon_html[icon_html.length] = [ " title='", aTitle, "'>" ].join("");
  else
    icon_html[icon_html.length] = ">";

  icon_html[icon_html.length] = "</a></td>";

  if ( aLabel ) {
    icon_html[icon_html.length] = "<td class='iconLabel'>";
    icon_html[icon_html.length] = [ "<a href='", anURL, "' id='", anID, aType, "link' ", my_target, " ",
                                    "onmouseover='top.lib_activateIcon(\"", anID, aType, "\",\"", aType, "\",\"", iconArray[1], "\",\"", aFrame, "\")' ", 
                                    "onmouseout='top.lib_deactivateIcon(\"", anID, aType, "\",\"", aType, "\",\"", iconArray[0], "\",\"", aFrame, "\")'"
                                  ].join("");

    if ( aTitle ) 
      icon_html[icon_html.length] = [ " title='", aTitle, "'>" ].join("");
    else
      icon_html[icon_html.length] = ">";
      
    icon_html[icon_html.length] = aLabel;
    icon_html[icon_html.length] = "</a></td>";
  }
  
  icon_html[icon_html.length] = "</tr></table>";

  return icon_html;  
}

function lib_paintIconAppLink(aLabel, aFunc, anURL, anID, aTitle, aPadding, srcArray, anAlign, anEventArray) {
  // paints an app link with an icon and optional label
  var icon_html = [];
  var my_padding = aPadding ? aPadding:"0";
  var my_events = anEventArray ? anEventArray : [ "", "" ];
  
  icon_html[icon_html.length] = [ "<table align='", anAlign, "'><tr><td style='vertical-align:top; padding:2px 0px 0px 0px'>" ].join("");
  
  if ( !top.req_pending ) {
    // paint icon in active state
    icon_html[icon_html.length] = [ 
                                    "<a href='", anURL, "' onclick='", aFunc, "; void(0)'",
                                    " onmouseover='top.lib_activateAppIcon(\"", anID, "\",\"", srcArray[1], "\");", my_events[0], "'", 
                                    " onmouseout='top.lib_deactivateAppIcon(\"", anID, "\",\"", srcArray[0], "\");", my_events[1], "'" 
                                  ].join("");
    if ( aTitle ) {
      icon_html[icon_html.length] = [ " title='", aTitle, "'>" ].join("");
    } else {
      icon_html[icon_html.length] = ">";
    }
    
    icon_html[icon_html.length] = [
                                    "<img id='", anID, "' src='", top.icon_location + srcArray[0], "' border='0'>"
                                  ].join("");

    icon_html[icon_html.length] = "</a>";

    icon_html[icon_html.length] = [ "</td><td style='vertical-align:top; padding:", my_padding, "px 0px 0px 2px'>" ].join("");

    icon_html[icon_html.length] = [ 
                                    "<a id='", anID, "link' href='", anURL, "' onclick='", aFunc, "; void(0)' style='color:8888bb'",
                                    " onmouseover='top.lib_activateAppIcon(\"", anID, "\",\"", srcArray[1], "\");", my_events[0], "'", 
                                    " onmouseout='top.lib_deactivateAppIcon(\"", anID, "\",\"", srcArray[0], "\");", my_events[1], "'" 
                                  ].join("");
    if ( aTitle ) {
      icon_html[icon_html.length] = [ " title='", aTitle, "'>" ].join("");
    } else {
      icon_html[icon_html.length] = ">";
    }
    
    if ( aLabel ) {
      icon_html[icon_html.length] = aLabel;
    }

    icon_html[icon_html.length] = "</a>";
  
  } else {
    

    icon_html[icon_html.length] = [ "<img src='", top.icon_location + srcArray[2], "' border='0'>" ].join("");

    icon_html[icon_html.length] = [ "</td><td style='vertical-align:top; padding:", my_padding, "px 0px 0px 2px'>" ].join("");

    if ( aLabel ) {
      icon_html[icon_html.length] = [ "<span class='inactiveAppLink'>", aLabel, "</span>" ].join("");
    }
  }
  icon_html[icon_html.length] = "</td></tr></table>";
  return icon_html;
}

function lib_activateBulletEgg(anIconID) {
  top.frames["contentFrame"].document.getElementById(anIconID).src = icon_location + bullet_egg;
}

function lib_deactivateBulletEgg(anIconID) {
  top.frames["contentFrame"].document.getElementById(anIconID).src = icon_location + bullet_egg_inactive;
}

function lib_activateAppIcon(anIconID, aSrc) {
  // shows mouse over images in icon app links
  var img_ref = top.frames["contentFrame"].document.getElementById(anIconID);
  var link_ref = top.frames["contentFrame"].document.getElementById(anIconID + "link");

  img_ref.src = icon_location + aSrc;
  if (link_ref) 
    link_ref.style.color = "ccffff";
}

function lib_deactivateAppIcon(anIconID, aSrc) {
  var img_ref = top.frames["contentFrame"].document.getElementById(anIconID);
  var link_ref = top.frames["contentFrame"].document.getElementById(anIconID + "link");

  img_ref.src = icon_location + aSrc;
  link_ref.style.color = "8888bb";
}

function lib_activateIcon(anIconID, aType, aSrc, aFrame) {
  // shows mouse over images in icon links
  if ( aFrame != 'false' ) {
    var img_ref = top.frames[aFrame].document.getElementById(anIconID);
    var link_ref = top.frames[aFrame].document.getElementById(anIconID + "link");
  } else {
    var img_ref = top.document.getElementById(anIconID);
    var link_ref = top.document.getElementById(anIconID + "link");
  }
  switch (aType) {
    case "real_ol":
      img_ref.src = icon_location + top.real_ol_active;
    break;
    case "real_dl":
      img_ref.src = icon_location + top.real_dl_active;
    break;
    case "mp3_ol":
      img_ref.src = icon_location + top.mp3_ol_active;
    break;
    case "mp3_dl":
      img_ref.src = icon_location + top.mp3_dl_active;
    break;
    case "news":
      img_ref.src = icon_location + top.news_icon_active;
    break;
    case "chat":
      img_ref.src = icon_location + top.chat_icon_active;
    break;
    case "video":
      img_ref.src = icon_location + top.video_dl_active;
    break;
    case "donate":
      img_ref.src = icon_location + top.spenden_icon_active;
    break;
    default:
      img_ref.src = icon_location + aSrc;
  }

  if (link_ref)
    link_ref.style.color = "ccffff";
}

function lib_deactivateIcon(anIconID, aType, aSrc, aFrame) {
  if ( aFrame != 'false' ) {
    var img_ref = top.frames[aFrame].document.getElementById(anIconID);
    var link_ref = top.frames[aFrame].document.getElementById(anIconID + "link");
  } else {
    var img_ref = top.document.getElementById(anIconID);
    var link_ref = top.document.getElementById(anIconID + "link");
  }
  switch (aType) {
    case "real_ol":
      img_ref.src = icon_location + top.real_ol;
    break;
    case "real_dl":
      img_ref.src = icon_location + top.real_dl;
    break;
    case "mp3_ol":
      img_ref.src = icon_location + top.mp3_ol;
    break;
    case "mp3_dl":
      img_ref.src = icon_location + top.mp3_dl;
    break;
    case "news":
      img_ref.src = icon_location + top.news_icon;
    break;
    case "chat":
      img_ref.src = icon_location + top.chat_icon;
    break;
    case "video":
      img_ref.src = icon_location + top.video_dl;
    break;
    case "donate":
      img_ref.src = icon_location + top.spenden_icon;
    break;
    default:
      img_ref.src = icon_location + aSrc;
  }

  if (link_ref)
    link_ref.style.color = "8888bb";
}

function lib_setPointerCursor(anEggID) {
  // netscape needs to set cursor explicitly
  if ( !document.all ) {
    if ( top.frames["contentFrame"] )
      var egg_ref = top.frames["contentFrame"].document.getElementById( anEggID );
    else
      var egg_ref = document.getElementById( anEggID );
    egg_ref.style.cursor = "pointer";
  }
}

function lib_buttonMouseOver(anID, aClass) {
  lib_setPointerCursor( "button" + anID ); 
  if ( top.frames["contentFrame"] )
    var the_elem = top.frames["contentFrame"].document.getElementById(anID);
  else
    var the_elem = document.getElementById(anID);
    
  the_elem.className = aClass;
}

function lib_buttonMouseOut(anID, aClass) {
  if ( top.frames["contentFrame"] )
    var the_elem = top.frames["contentFrame"].document.getElementById(anID);
  else
    var the_elem = document.getElementById(anID);

  the_elem.className = aClass;
}

function lib_paintWindowHeading(aHeading) {  
  return CropfmElements.WINDOW_HEADING_HTML.replace(/\(\$heading\)/, aHeading);
}

// adds the window frame, also see lib_adjustWindowFrame
function lib_paintWindowFrame(aDocument) {
  aDocument.body.innerHTML =  
    CropfmElements.INNER_FRAME_BEGIN_HTML + 
    aDocument.body.innerHTML +
    CropfmElements.INNER_FRAME_END_HTML;
}

// Function needed by CropfmElements for adjusting size of inner frame html.
// See renderInnerFrameBegin() in class CropfmElements
function lib_adjustWindowFrame (aDocument) {
  if ( aDocument.all) {
    var width = aDocument.body.offsetWidth - 24;
    var height = aDocument.body.offsetHeight - 24;  
  } else { 
    var width = window.innerWidth - 24;
    var height = window.innerHeight - 24;
  }
  aDocument.getElementById("frame_top").width = width;
  aDocument.getElementById("frame_bottom").width = width;
  aDocument.getElementById("frame_left").height = height;
  aDocument.getElementById("frame_right").height = height;
  aDocument.getElementById("frameContent").style.height = height + "px";
}

// retrieve the inner width of the browser window
function lib_docWidth() {
  if(!window.innerWidth)
    return document.body.clientWidth;
  else 
    return window.innerWidth;
}

function lib_docHeight() {
  if(!window.innerHeight)
    return document.body.clientHeight;
  else 
    return window.innerHeight;
}

var ad_dist = 0;
var scroll_dist = 0;
var def_dist = 70;
function lib_adFollow() {
  
  if ( document.all ) {
	scroll_dist = target_frame.document.body.scrollTop; 
    ad_dist = scroll_dist - target_frame.document.all('adsense').style.posTop + def_dist;
  } else {
	scroll_dist = target_frame.pageYOffset; 
    ad_dist = scroll_dist - parseInt(target_frame.document.getElementById("adsense").style.top) + def_dist;
  }
  
  if ( Math.abs(ad_dist) > def_dist + 20 || scroll_dist == 0 ) {	
    if ( document.all )
    	target_frame.document.all('adsense').style.top = [ scroll_dist + def_dist, "px" ].join("");
    else 
    	target_frame.document.getElementById('adsense').style.top = [ scroll_dist + def_dist, "px" ].join("");

  }  
  initAdds(top.amazon_120_600);
}

var current_subject = "";
function initAdds(amazonHtml) {
	if ( top.current_query && top.current_query.mode == 3 && top.current_query.subject != top.notset_val ) {
	   
	   if (top.current_subject == top.current_query.subject || 
		   top.subject_keywords[top.current_query.subject] == null )
		   return;
	   top.current_subject = top.current_query.subject;
	   
	   if ( document.all )
		   target_frame.document.all('adsense').innerHTML = 
			   amazonHtml.replace( "$(amazon_keywords)", top.subject_keywords[top.current_subject] );
	   else 
		   target_frame.document.getElementById('adsense').innerHTML = 
			   amazonHtml.replace( "$(amazon_keywords)", top.subject_keywords[top.current_subject] );
	}
}

function initSubjectAdds(aSubject, amazonHtml) {
	if ( top.subject_keywords[aSubject] != null ) {
		   document.getElementById('amazon').innerHTML = 
				   amazonHtml.replace( "$(amazon_keywords)", top.subject_keywords[aSubject] );
	}		
}

function lib_paintHeaderBar(aBarLabel, aButtonLabel, aFunction, aUrl) {  
  // returns the HTML of a header bar with label and optional button
  var the_html = [];

  the_html[the_html.length] = "<table class='headerBar'><tr><td class='barLeft'>";

  if ( aBarLabel )
    the_html[the_html.length] = aBarLabel;

  the_html[the_html.length] = "</td><td class='barRight'>";

  if ( aFunction || aUrl )
    the_html[the_html.length] = paintButton ( aButtonLabel, aFunction, aUrl, true, false );

  the_html[the_html.length] = "</td></tr></table>";
  
  return the_html.join("");  
}

function paintQueryData(bigHeading, doColumn) {
  if ( bigHeading )
    var span_html = "<span class='inlineHeading3'>";
  else
    var span_html = "<span class='inlineHeading5'>";
    
  if ( doColumn )
    var br = "<br>";
  else
    var br = ", ";
    
  var the_html = [];
  switch (current_query.mode) {
    case 1:
      the_html[the_html.length] = span_html + search_data_content_de + "</span>";
      the_html[the_html.length] = "<br>"+ search_data_searchterm_de + ": <i><b>" + current_query.ftquery + "</b></i>" + br; 
    break;
    case 2:
      the_html[the_html.length] = span_html + search_data_guest_de + "</span>";
      the_html[the_html.length] = "<br>" + search_data_guestname_de + ": <b>" + getDisplayName(current_query.guestid) + "</b>" + br; 
    break;
    case 3:
      var the_start = ( tmp_searchform.startdate == notset ) ? top.default_startdate : tmp_searchform.startdate;
      var the_end = ( tmp_searchform.enddate == notset ) ? top.endDateChooser.gen_date ( new Date() ) : tmp_searchform.enddate;
      the_html[the_html.length] = span_html + search_data_chronological_de + "</span>";
      the_html[the_html.length] = "<br>"+ search_data_start_de + ": <b>" + the_start + "</b>" + br;
      the_html[the_html.length] = search_data_end_de + ": <b>" + the_end + "</b>" + br;

      if ( current_query.subject != notset ) {
        the_html[the_html.length] = [ "Themengebiet: <b>", lib_getSubjectTitle(current_query.subject), "</b>", br ].join(""); 
      }       
    break;
  }
  
  if ( current_query.mode && current_query.mode != 4 )
    the_html[the_html.length] = search_data_entries_de + ": <b>" + rs_length + "</b>";
  
  if ( Math.ceil(top.rs_length/page_size) > 1 ) {
    the_html[the_html.length] = ", " + search_data_pages_de + ": <b>" + Math.ceil(rs_length/page_size) + "</b>";
  }
  
  if ( top.rs_length > 1 ) {
    the_html[the_html.length] = ", " + search_data_sortorder_de + ": <b>" + ( sort_order == "up" ? search_data_sortup_de : search_data_sortdown_de ) + "</b>";
  }
  
  return the_html.join("");
}


/****************** "loading..." anmimation ******************/

function lib_showLoadingIcon() {
  //top.loading_anim = top.setInterval("doLoadingAnim()", 500);
  lib_moveLoadingIconDown();
}

function lib_moveLoadingIconDown() {
  var y_pos = parseInt(top.frames["contentFrame"].document.getElementById("loadingIconContent").style.top);
  if ( y_pos < 120 && top.req_pending ) {
    top.frames["contentFrame"].document.getElementById("loadingIconContent").style.top = [y_pos + 15,"px"].join("");
    setTimeout("lib_moveLoadingIconDown()", 12);
  }
}   

function lib_hideLoadingIcon() {
  lib_moveLoadingIconUp();
}

function lib_moveLoadingIconUp() {
  var y_pos = parseInt(top.frames["contentFrame"].document.getElementById("loadingIconContent").style.top);
  if ( y_pos > -120) {
    top.frames["contentFrame"].document.getElementById("loadingIconContent").style.top = [y_pos - 12,"px"].join("");
    setTimeout("lib_moveLoadingIconUp()", 12);
  }  else {
      top.clearInterval(top.loading_anim);
  }
}

function doLoadingAnim() {
  var loading_text = top.frames["contentFrame"].document.getElementById("loadingText");
  if ( loading_text.innerHTML == "loading..." )
    loading_text.innerHTML = "loading";
  else
    loading_text.innerHTML += ".";
}

/****************** "loading..." END ******************/

function setSearchModeFromQuery(theQuery) {
  switch (theQuery.mode) {
    case 1: top.active_search_tab = 0; break;
    case 2: top.active_search_tab = 1; break;
    case 3: top.active_search_tab = 2; break;
    default: top.active_search_tab = 0;
  }
}

function lib_parseMediaString(text) {
  /*** parses the text supplied for audio, video and show link entries (db) ***/
  
  // exp for [%%label%%file%%size%%]
  var ra_exp = new RegExp("\\.rm");
  var mp3_exp = new RegExp("\\.mp3");
  
  var obj_array = [];
  var my_type = "";
  var my_size = "unknown";
  var remaining_text = text;
  
  var link_found = top.regexp_audio_video_show_link.exec(remaining_text);
  while ( link_found ) {
    if ( link_found[1] && link_found[2] ) {
      // audio or video link      
      my_type = notset;
      
      if ( ra_exp.exec ( link_found[2] ) )
        my_type = "real";
 
      if ( mp3_exp.exec ( link_found[2] ) )
        my_type = "mp3";
      
      if ( link_found[3] )
        my_size = link_found[3];
        
      obj_array [ obj_array.length ] = { 
                                         label:link_found[1],
                                         file:link_found[2],
                                         size:my_size,
                                         type:my_type
                                       };
    }

    if ( link_found[4] && link_found[5] ) {
      // show link 
      obj_array [ obj_array.length ] = { 
                                         label:link_found[4],
                                         url:link_found[5]
                                       };
    }

    remaining_text = remaining_text.substr ( link_found.index + link_found[0].length );
    link_found = top.regexp_audio_video_show_link.exec ( remaining_text );
  }
  return obj_array;
}

function parseHtml(text) {
  /*** parses the text supplied for inline links to shows and inserts calls to gotoShow() ***/

  var return_text = text; 
  var insert_link = "";
  
  // *** parse show links ***
  var link_found = top.regexp_inline_link.exec(return_text);
  while ( link_found ) {
    if ( link_found[1] && link_found[2] ) {
      insert_link = paintAppLink ("show", link_found[1], false, "javascript:top.gotoShow(\"" + link_found[2] + "\");void(0)", false);
      return_text = return_text.replace(link_found[0],insert_link);
    } else {
      return_text = return_text.replace(link_found[0]," [BAD_LINK] ");
    }
    link_found = top.regexp_inline_link.exec(return_text);
  }

  return return_text;  
}

function lib_replaceMods() {
  // replaces moderator entities on page in HTML...
  var exp;
  for (var mod in top.mod_object) {
    exp = new RegExp("<" + mod + ">", "gi");
    if ( document.getElementById("modspan") != null ) {
      document.getElementById("modspan").innerHTML = document.getElementById("modspan").innerHTML.replace(exp, top.mod_object[mod].name);
    }
  }
}


function lib_getContentFontSize() {
  switch ( text_size ) {
    case "0":
      return font_sizes.normal;
      break;
    case "1":
      return font_sizes.medium;
      break;
    case "2":
      return font_sizes.big;
      break;
    default:
      return font_sizes.normal;
  }
}

function lib_prepareSizeInfo(aNum) {
  var my_str = String ( aNum/1048576 );
  return my_str.substr(0,4);
}

// dec to hex utility 
var hex="0123456789ABCDEF";
function lib_toHex(aDec) {
  var out = "";
  var inp = aDec;
  while(inp != 0) {
    out=hex.charAt(inp%16)+out;
    inp=inp >> 4;
  }
  if (out.length == 1) out = "0" + out;
  if (out.length == 0) out = "00";
  return out;
}

/* Base64 decoding of string */
var keyStr = "ABCDEFGHIJKLMNOP" +
			 "QRSTUVWXYZabcdef" +
			 "ghijklmnopqrstuv" +
			 "wxyz0123456789+/" +
			 "=";
function lib_decode64(input) {
   input = input.replace(/_/g, "=");
   var output = "";
   var chr1, chr2, chr3 = "";
   var enc1, enc2, enc3, enc4 = "";
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   var base64test = /[^A-Za-z0-9\+\/\=]/g;
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }

      chr1 = chr2 = chr3 = "";
      enc1 = enc2 = enc3 = enc4 = "";

   } while (i < input.length);
   
   // utf-8 encoding must only be done, when server encodes in utf-8!
   return utf8_decode(output);
}

function utf8_decode(utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}

	}

	return string;
}

