// Changes the visibility of any object (@ ID) between 'block' and 'none'
function toggle_visibility(id) {
  var e = document.getElementById(id);
  if(e.style.display == 'none')
    e.style.display = 'block';
  else
    e.style.display = 'none';
  }
//USAGE EXAMPLE: <a href="#" onclick="toggle_visibility('div1')">hide/show</a> <!--where 'div1' is the ID of the object-->

// ==============================================================

// For all <a rel="External"> to be target="_blank"
function externalLinks() {
  if (!document.getElementsByTagName) return;
  var anchors = document.getElementsByTagName("a");
  for (var i=0; i<anchors.length; i++) {
    var anchor = anchors[i];
    if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
      anchor.target = "_blank";
    }
  }
}
window.onload = externalLinks;
// SOURCE: http://www.sitepoint.com/article/standards-compliant-world/3

// ==============================================================

// Pop-Up Embedder Script by David Battino, www.batmosphere.com; Object tag implementation by Mark Levitt, http://digitalmedia.oreilly.com
var UniqueID = 314 // Make each link open in a new window.
var newWinOffset = 0 // Position of first pop-up
function PlayerOpen(soundfiledesc,soundfilepath) {
PlayWin = window.open('',UniqueID,'width=320,height=250,top=' + newWinOffset +',left=0,resizable=0,scrollbars=0,titlebar=0,toolbar=0,menubar=0,status=1,directories=0,personalbar=0');
PlayWin.focus(); 
var winContent = "<html xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'><head><title>" + soundfiledesc + "</title></head><body style='background-color:blue;color:white;'>";
winContent += "<h1 style='font-size:18px;font-family:Verdana,sans-serif;line-height:1.5;font-weight:bold;'>" + soundfiledesc + "</h1>";
winContent += "<object width='300' height='42'>";
winContent += "<param name='SRC' value='" +  soundfilepath + "' />";
winContent += "<param name='autoplay' value='true' />";
winContent += "<param name='controller' value='true' />";
winContent += "<param name='bgcolor' VALUE='#FF9900' />";
winContent += "<embed src='" + soundfilepath + "' autostart='true' loop='false' style='width:300px;height:42px;background-color:#FF9900;' controller='true'></embed>";
winContent += "</object>";
winContent += "<p style='font-size:12px;font-family:Verdana,sans-serif;text-align:center'><a href='"+soundfilepath+"' style='color:white;'>Download this file</a> <span style='font-size:10px'>(right-click or Option-click)</span></p>";
winContent += "<form><div style='text-align:center;'><input type='button' value='Close this window' onClick='javascript:window.close();' /></div></form>";
winContent += "</body></html>";
PlayWin.document.write(winContent);
PlayWin.document.close(); // "Finalizes" new window
UniqueID = UniqueID + 1
// newWinOffset = newWinOffset + 20 // subsequent pop-ups will be this many pixels lower.
}
//USAGE EXAMPLE: 

// ==============================================================

// Get the browser brand
function SjGetBrowser()
{
   var agt=navigator.userAgent.toLowerCase();
   if( ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1)) )
       return "IE";
   else if( ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
         && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
         && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)) )
       return "Netscape";
   else
       return "unknown";
}

// ==============================================================

// Embed WMV/MP3 InerBrowser (ISSUE: no good in FF2)
function playMedia(mediaURL,rpt,height,width) {
  var mediaURL,rpt,height,width
  if (SjGetBrowser() == "Netscape") 
	embedMPlayer(mediaURL,rpt,height,width);  
  if (SjGetBrowser() == "IE") 
	embedIEobject(mediaURL,rpt,height,width);
  if (navigator.appName.substring(0,5) == "WebTV")
	embedSource(mediaURL,rpt,height,width)
}
function embedSource(mediaURL,rpt,height,width) {
  var CodeGen = ""
  var mediaURL,rpt,height,width
  CodeGen = '<embed src="' + mediaURL + '"' + '\n' ;
  CodeGen += ' height=' + height + ' width=' + width + ' autostart="true"' + '\n'
  CodeGen += ' loop=' + rpt + ' />'
  document.write(CodeGen)
}
function embedMPlayer(mediaURL,rpt,height,width) {
  CodeGen = "" 
  var mediaURL,rpt,height,width
  CodeGen = '<embed type="application/x-mplayer2" ' + '\n' ;
  CodeGen = CodeGen + ' pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" ' + '\n' ;
  CodeGen = CodeGen + 'Name="MediaPlayer" ' + 'src="' + mediaURL + '" ' + '\n' ;
  CodeGen = CodeGen + 'autoStart=1 ' ;
  if ((height == 24) && (width == 299)) 
    CodeGen = CodeGen + 'ShowStatusBar=1 '; 
  if ((height >= 50) && (width >= 200)) 
    CodeGen = CodeGen + 'ShowStatusBar=1 '; 
  if ((height <= 49) && (width != 299))
    CodeGen = CodeGen + 'ShowStatusBar=0 '; 
  CodeGen = CodeGen + 'playCount=' + rpt + ' ' ;
  CodeGen = CodeGen + 'volume=-1 ' ;
  CodeGen = CodeGen + 'HEIGHT=' + height + ' WIDTH=' + width + ' />'
  document.write(CodeGen)
}
function embedIEobject(mediaURL,rpt,height,width){
  CodeGen = "" 
  var mediaURL,rpt,height,width
  CodeGen = '<object id=Player' + '\n' ;
  CodeGen += 'codeBase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,0,02,902' + '\n' ;
  CodeGen += 'type=application/x-oleobject height=' + height + ' width=' + width + '\n' ;
  CodeGen += ' standby="Loading Microsoft® Windows® Media Player components..." ' + '\n' ;
  CodeGen += 'classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"> ' + '\n' ;
  CodeGen += '<param name="Filename" value="' + mediaURL + '" />' + '\n' ;
  if ((height == 24) && (width == 299)) 
    CodeGen += '<param name="ShowStatusBar" value="true" />';
  if ((height >= 50) && (width >= 200)) 
    CodeGen += '<param name="ShowStatusBar" value="true" />'; 
  if ((height <= 49) && (width != 299))
    CodeGen += '<param name="ShowStatusBar" value="false" /> ';
  CodeGen += '<param name="autoStart" value="true" /><param name="Volume" value="-1" />' + '\n' ;
  CodeGen += '<param name="playCount" value=' + rpt + ' /></object>'
  document.write(CodeGen)
}
// USAGE EXAMPLE:
// <script type="text/javascript">playMedia("media/S_Club_7-NeverHad.wmv",1,250,250)</script>
// <script type="text/javascript">playMedia("media/TimeAfterTime.mp3",1,50,300)</script>

// ==============================================================

// Search within page
// This is the function that actually highlights a text string by adding HTML tags
// before and after all occurrences of the search term. You can pass your own tags
// if you'd like, or if the highlightStartTag or highlightEndTag parameters are
// omitted or are empty strings then the default <span> tags will be used.
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<em class='highlight'>";
    highlightEndTag = "</em>";
  }
  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  return newText;
}
// This is sort of a wrapper function to the doHighlight function.
// It takes the searchText that you pass, optionally splits it into
// separate words, and transforms the text on the current web page.
// Only the "searchText" parameter is required; all other parameters
// are optional and can be omitted.
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
  // if the treatAsPhrase parameter is true, then we should search for 
  // the entire phrase that was entered; otherwise, we will split the
  // search string so that each word is searched for and highlighted
  // individually
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(" ");
  }
  if (!document.body || typeof(document.body.innerHTML) == "undefined") {
    if (warnOnFailure) {
      alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
    }
    return false;
  }
  var bodyText = document.body.innerHTML;
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }
  document.body.innerHTML = bodyText;
  return true;
}
// This displays a dialog box that allows a user to enter their own search terms
// to highlight on the page, and then passes the search text or phrase to the
// highlightSearchTerms function. All parameters are optional.
function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)
{
  // This function prompts the user for any words that should be highlighted on this web page.
  if (!defaultText) {
    defaultText = "";
  }
  // we can optionally use our own highlight tag values
  if ((!textColor) || (!bgColor)) {
    highlightStartTag = "";
    highlightEndTag = "";
  } else {
    highlightStartTag = "<span style='color:" + textColor + "; background-color:" + bgColor + ";'>";
    highlightEndTag = "</span>";
  }
  if (treatAsPhrase) {
    promptText = "Please enter the phrase you'd like to search for:";
  } else {
    promptText = "Please enter the words you'd like to search for, separated by spaces:";
  }
  searchText = prompt(promptText, defaultText);
  if (!searchText)  {
    alert("No search terms were entered. Exiting function.");
    return false;
  }
  return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
}
// This function takes a referer/referrer string and parses it to determine if it contains any
// search terms. If it does, the search terms are passed to the highlightSearchTerms function
// so they can be highlighted on the current page.
function highlightGoogleSearchTerms(referrer)
{
  // This function has only been very lightly tested against typical Google search URLs. If
  // you wanted the Google search terms to be automatically highlighted on a page, you could
  // call the function in the onload event of your <body> tag, like this:
  //       <body onload='highlightGoogleSearchTerms(document.referrer);'>
  //var referrer = document.referrer;
  if (!referrer) {
    return false;
  }
  var queryPrefix = "q=";
  var startPos = referrer.toLowerCase().indexOf(queryPrefix);
  if ((startPos < 0) || (startPos + queryPrefix.length == referrer.length)) {
    return false;
  }
  var endPos = referrer.indexOf("&", startPos);
  if (endPos < 0) {
    endPos = referrer.length;
  }
  var queryString = referrer.substring(startPos + queryPrefix.length, endPos);
  // fix the space characters
  queryString = queryString.replace(/%20/gi, " ");
  queryString = queryString.replace(/\+/gi, " ");
  // remove the quotes (if you're really creative, you could search for the
  // terms within the quotes as phrases, and everything else as single terms)
  queryString = queryString.replace(/%22/gi, "");
  queryString = queryString.replace(/\"/gi, "");
  return highlightSearchTerms(queryString, false);
}
// This function is just an easy way to test the highlightGoogleSearchTerms function.
function testHighlightGoogleSearchTerms()
{
  var referrerString = "http://www.google.com/search?q=javascript%20highlight&start=0";
  referrerString = prompt("Test the following referrer string:", referrerString);
  return highlightGoogleSearchTerms(referrerString);
}

// USAGE EXAMPLE:
// <input type="button" value="Highlight multiple search terms" onClick="searchPrompt('this and that', false);" />
// <input type="button" value="Highlight a search phrase" onClick="searchPrompt('the page', true, 'green', 'pink');" />
// <input type="button" value="Test highlightGoogleSearchTerms function" onClick="testHighlightGoogleSearchTerms();" />

// ==============================================================
