/***************************************************************************************************************
* universal load events
****************************************************************************************************************/
//commenting out the universal version of off-site link indicator since FundFire does not want to use it now. Moved into global onloads for other pubs for now.
//addEvent(window, 'load', offsiteLinkIndicator);


/***************************************************************************************************************
* article caption functions
****************************************************************************************************************/

//find the content div, call createCaptDiv on its children
function imageCaption(){
    for(var x = 0; x < document.getElementsByTagName('div').length; x++){
        if(document.getElementsByTagName('div')[x].id == "content"){
            var captionImages = new Array();
            recurseContent(document.getElementsByTagName('div')[x], captionImages);
            for (var i=0; i < captionImages.length; i++) {
                createCaptDiv(captionImages[i]);
            }
        }
    }
}
// format currency (dollar format) e.g 1250 will return $1,250
// if decimal = true then will return $1,250.00
function formatCurrency(strValue, decimal)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	
	if(decimal)
		return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
	else
		return (((blnSign)?'':'-') + '$' + dblValue);

}

//recursively loop through each content child, return array by reference
function recurseContent(content, captionImages){
    for(var cn = content.firstChild; cn != null; cn = cn.nextSibling) {
        for(var n = cn.firstChild; n != null; n = n.nextSibling) {
            if(n.tagName != null){
                if(n.tagName.toLowerCase() == "img"){
                    captionImages[captionImages.length] = n;
                }
            }
            recurseContent(n, captionImages);
        }
    }
}

//sets the global articleDate variable, set to today (to be overwritten by the article pages)
var articleDate = new Date();
 
//if the img is a jpg, wrap it in a span, add the caption from the alt tag
function createCaptDiv(cn){
    var imgWrapper = document.createElement('span');
    imgWrapper.setAttribute('class',cn.className);
    imgWrapper.setAttribute('style','width: ' + cn.width + 'px;');
    imgWrapper.setAttribute("className",cn.className);//for IE
    if (document.all) {imgWrapper.style.setAttribute('cssText','width: ' + cn.width + 'px;');}//for IE
    var newImg = document.createElement('img');
    var newBR = document.createElement('br');
    newImg.setAttribute('src',cn.src);
    newImg.setAttribute('width',cn.width);
    newImg.setAttribute('height',cn.height);
    newImg.setAttribute('alt','');
    //the "old" versus "new" determining variable
    var lastCaption = new Date("January 11, 2006");
    //if this is an "older" article, display the caption automatically
    if(articleDate < lastCaption){
        var captionText = cn.alt;
    }
    //if this is a "newer" article, display caption only if it has the prefix "caption:" (case insensitive)
    else{
        var caption = cn.alt.toLowerCase();
        caption = caption.split("caption:");
        if(caption[1]){
            var captionText = trim(cn.alt.substring(8, cn.alt.length));
        }
    }
    if(captionText){
        var altText = document.createTextNode(captionText);
        var imgType = cn.src.substring(cn.src.length - 4);
        if(imgType == ".jpg" || imgType == "jpeg" || imgType == ".gif"){
            cn.parentNode.insertBefore(imgWrapper,cn);
            imgWrapper.appendChild(newImg);
            imgWrapper.appendChild(newBR);
            imgWrapper.appendChild(altText);
            cn.parentNode.removeChild(cn);
        }
    }
}



/***************************************************************************************************************
* hide/display functions
****************************************************************************************************************/

//show layer
function showLayer(myName) {
    var myObj = new getObj(myName);
    myObj.style.visibility="visible";
    myObj.style.display="block";
}

//hide layer
function hideLayer(myName) {
    var myObj = new getObj(myName);
    myObj.style.visibility="hidden";
    myObj.style.display="none";
}

function hideDisplay(showLayer1,hideLayer1,hideLayer2,hideLayer3,hideLayer4,hideLayer5){
    //currently hides up to five layers, add extra parameters to hide/display more layers with one event
    for(x = 0; x < hideDisplay.arguments.length; x++){
        if(hideDisplay.arguments[x] != ''){
            hideLayer(hideDisplay.arguments[x]);
        }
    }
    if(showLayer1 != ''){showLayer(showLayer1)};
}

//toggle display based on current visibilty, starting with a hidden layer
function toggleDisplay(myName){
    var myObj = new getObj(myName);
    if(myObj.style.visibility == "hidden" || myObj.style.visibility == ""){
        showLayer(myName);
    }
    else{
        hideLayer(myName);
    }
}

//toggle display based on current visibilty, starting with a visible layer
function toggleDisplayStartVis(myName){
    var myObj = new getObj(myName);
    if(myObj.style.visibility == "visible" || myObj.style.visibility == ""){
        hideLayer(myName);
    }
    else{
        showLayer(myName);
    }
}

//toggle back issue display
function toggleBackIssue(visibility){
    if(visibility == 'hide'){hideLayer('backIssue');}
    else{showLayer('backIssue');}
}



/***************************************************************************************************************
* form validation functions
****************************************************************************************************************/

//sets a maxlength to textarea boxes
function textareaMaxLength(fieldName,maxLength){
	if(fieldName.value.length > maxLength){
	    fieldName.value = fieldName.value.substring(0, maxLength);
	    alert("This field is restricted to " + maxLength + " characters.");
	}
}

//checks that all required fields are not empty
function checkForm(f1,f2,f3,f4,f5,f6,f7){
    for(x = 0; x < checkForm.arguments.length; x++){
        if(checkForm.arguments[x] != null){
            if(checkForm.arguments[x].value == ''){
                alert('Please enter the proper information in all required fields and submit again.');
                return false;
            }
        }
    }
    return true;
}

//validates an email address field and also checks that all other required fields are not empty
function checkFormWithEmail(eAddress,f2,f3,f4,f5,f6,f7){//the email field MUST be the first parameter passed
    for(x = 0; x < checkFormWithEmail.arguments.length; x++){
        if(checkFormWithEmail.arguments[x].value == ''){
            alert('Please enter the proper information in all required fields and submit again.');
            return false;
        }
    }
    if(validateMultiEmail(eAddress.value,1,0) == false){
        return false;
    }
    return true;
}

//returns true if two email addresses are equal
function confirmEmail(eAddress,eAddressConf){
    if(eAddress == eAddressConf){
        return true;
    }
    else{
        return false;
    }
}

function checkFormConfirmEmail(eAddress,eAddressConf,f2,f3,f4,f5,f6,f7){//the email field MUST be the first parameter passed, confirming email field MUST be the second parameter passed
    for(x = 0; x < checkFormConfirmEmail.arguments.length; x++){
        if(checkFormConfirmEmail.arguments[x].value == ''){
            alert('Please enter the proper information in all required fields and submit again.');
            return false;
        }
    }
    if(validateMultiEmail(eAddress.value,1,0) == false){
        return false;
    }
    if(confirmEmail(eAddress.value,eAddressConf.value) == false){
        alert('Your email addresses do not match.');
        return false;
    }
    return true;
}

//loop through all comma seperated email addresses checking for validity
function validateMultiEmail(addr,man,db){
    var emailValidity = true;
    var email_parts = addr.split(",");
    for(var x = 0; x < email_parts.length; x++){
        email_parts[x] = trim(email_parts[x]);
        if(validateEmail(email_parts[x],man,db) == false){
            emailValidity = false;
        }
    }
    if(emailValidity == false){
        alert("Please enter valid email addresses and submit again.");
        return false;
    }
    else{
        return true;
    }
}

// Email Validation Javascript: addr = email address value | man = mandatory, 1 = yes, 0 = no | db = error messages, 1 = supress individual message, 0 = show
function validateEmail(addr,man,db) {
    // copyright 23rd March 2003, by Stephen Chapman, Felgall Pty Ltd
    if (addr == '' && man) {
        if (db) alert('email address is mandatory');
        return false;
    }
    var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
    for (i=0; i<invalidChars.length; i++) {
        if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
            if (db) alert('email address contains invalid characters');
            return false;
        }
    }
    for (i=0; i<addr.length; i++) {
        if (addr.charCodeAt(i)>127) {
            if (db) alert("email address contains non ascii characters.");
            return false;
        }
    }
    var atPos = addr.indexOf('@',0);
    if (atPos == -1) {
        if (db) alert('email address must contain an @');
        return false;
    }
    if (atPos == 0) {
        if (db) alert('email address must not start with @');
        return false;
    }
    if (addr.indexOf('@', atPos + 1) > - 1) {
        if (db) alert('email address must contain only one @');
        return false;
    }
    if (addr.indexOf('.', atPos) == -1) {
        if (db) alert('email address must contain a period in the domain name');
        return false;
    }
    if (addr.indexOf('@.',0) != -1) {
        if (db) alert('period must not immediately follow @ in email address');
        return false;
    }
    if (addr.indexOf('.@',0) != -1){
        if (db) alert('period must not immediately precede @ in email address');
        return false;
    }
    if (addr.indexOf('..',0) != -1) {
        if (db) alert('two periods must not be adjacent in email address');
        return false;
    }
    var suffix = addr.substring(addr.lastIndexOf('.')+1);
    if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
        if (db) alert('invalid primary domain in email address');
        return false;
    }
    return true;
}



/***************************************************************************************************************
* altering column height and width functions
****************************************************************************************************************/

//initialize the height of the three columns by finding the longest column on load
var maxHeight = 0;
function initHeights(){
    //initialize the heights of the three columns
    if(document.getElementById('nav')){
        if(document.getElementById('nav').offsetHeight > maxHeight){maxHeight = document.getElementById('nav').offsetHeight;}
    }
    if(document.getElementById('rightCol')){
        if(document.getElementById('rightCol').offsetHeight > maxHeight){maxHeight = document.getElementById('rightCol').offsetHeight;}
    }
    if(document.getElementById('content')){
        if(document.getElementById('content').offsetHeight > maxHeight){maxHeight = document.getElementById('content').offsetHeight;}
    }
    if(document.getElementById('main')){
        if(document.getElementById('main').offsetHeight > maxHeight){maxHeight = document.getElementById('main').offsetHeight;}
    }

    if(document.getElementById('nav')){
        //set to auto height, to force size of column to maximum height
        document.getElementById('nav').style.height = (maxHeight) + "px";
    }
    if(document.getElementById('rightCol')){
        //set to auto height, to force size of column to maximum height
        document.getElementById('rightCol').style.height = (maxHeight) + "px";
    }
    if(document.getElementById('content')){
        //set to auto height, to force size of column to maximum height
        document.getElementById('content').style.height = (maxHeight) + "px";
    }
    if(document.getElementById('main')){
        //set to auto height, to force size of column to maximum height
        document.getElementById('main').style.height = (maxHeight) + "px";
    }
    /* 
            * Test if initHeight() was executed, if so, print a period "." at the end of "An Information Service of Money-Media" on the bottom of the page
            */
    if(document.getElementById('copy')){
        document.getElementById('copy').innerHTML = document.getElementById('copy').innerHTML + ".";
    }
    if(document.getElementById('footerLinks')){
        document.getElementById('footerLinks').innerHTML = document.getElementById('footerLinks').innerHTML + "-";
    }
}

//reinitialize the height of the three columns after some event changes the height of one or more column
function changeHeight(newColumn){
    //set new column to auto height, to force size of column to maximum height
    document.getElementById(newColumn).style.height = 'auto';
    //then check if that height is less than the global maxHeight set on the page load, if so, set to maxHeight
    if(document.getElementById(newColumn).offsetHeight < maxHeight){
        document.getElementById(newColumn).style.height = maxHeight + "px";
    }
}

function changeDivHeight(newColumn, myName, firstHeight, secHeight){
    //set new column to auto height, to force size of column to maximum height
    document.getElementById(newColumn).style.height = 'auto';
    
    if(myName == '') {
    	document.getElementById(newColumn).style.height = firstHeight + "px";
    	return;
	}
    
    var myObj = new getObj(myName);
    
    if(myObj.style.visibility == "hidden" || myObj.style.visibility == ""){ 
    	document.getElementById(newColumn).style.height = firstHeight + "px";
    } else {
    	document.getElementById(newColumn).style.height = secHeight + "px";
    }
    
}

//expands the width of a containing element to equal the width of its childen
function widthExpander(thisLayer){
    var selectedID = new Array();
    var styleType = new Array();
    var thisStyleValue;
    var totalWidth = 0;
    var i = 0;
    for(var cn = document.getElementById(thisLayer).firstChild; cn != null; cn = cn.nextSibling) {
        if(cn.id != null){
            selectedID[i] = cn.id;
            i++;
        }
    }
    //selectedID array length must have at least 2 children to increase the totalWidth in IE
    if(selectedID.length < 2){return;}

    styleType[0] = ["marginLeft","margin-left"];
    styleType[1] = ["marginRight","margin-right"];
    styleType[2] = ["paddingLeft","padding-left"];
    styleType[3] = ["paddingRight","padding-right"];
    for(var x = 0; x < selectedID.length; x++){

        if(document.getElementById(selectedID[x]) != null){
            for(var i = 0; i < styleType.length; i++){
                styleType[i] = styleType[i] + '';
                styleType_parts = styleType[i].split(",");
                thisStyleValue = cascadedstyle(document.getElementById(selectedID[x]), styleType_parts[0], styleType_parts[1]);
                thisStyleValue_parts = thisStyleValue.split("p");

                if(thisStyleValue_parts[0] != 'auto'){
                    totalWidth += parseInt(thisStyleValue_parts[0]);
                }
            }
            thisStyleValue = cascadedstyle(document.getElementById(selectedID[x]), 'width', 'width');
            thisStyleValue_parts = thisStyleValue.split("p");
            for(var cn = document.getElementById(selectedID[x]).firstChild; cn != null; cn = cn.nextSibling) {
                var childW = childOffset(cn);
            }
            if(parseInt(childW) > parseInt(thisStyleValue_parts[0])){
                totalWidth += parseInt(childW);
            }
            else{
                totalWidth += parseInt(thisStyleValue_parts[0]);
            }
        }
    }
    if(totalWidth > 0){
        document.getElementById(thisLayer).style.width = totalWidth + "px";
    }
}

//finds the maximum offsetwidth of a node's children
var childOffsetWidth = 0;
function childOffset(cn){
    if(cn.offsetWidth > childOffsetWidth){childOffsetWidth = cn.offsetWidth;}
    if(cn.hasChildNodes() == true){
        for(var n = cn.firstChild; n != null; n = n.nextSibling) {
            childOffset(n);
        }
    }
    return childOffsetWidth;
}



/***************************************************************************************************************
* cookie functions
****************************************************************************************************************/

//create a cookie
function createCookie(name,value,days){
    if (days){
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else{
        var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

//read a cookie
function readCookie(name){
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++){
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

//erase a cookie
function eraseCookie(name){
    createCookie(name,"",-1);
}



/***************************************************************************************************************
* misc functions
****************************************************************************************************************/

//add an event handler, from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
function addEvent(obj, type, fn) {
    if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
    }
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
    }
}

//remove an event handler, from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
function removeEvent(obj, type, fn) {
    if (obj.removeEventListener) {
        obj.removeEventListener( type, fn, false );
    }
    else if (obj.detachEvent) {
        if (fn!=undefined){
            obj.detachEvent( "on"+type, obj[type+fn] );
            obj[type+fn] = null;
            obj["e"+type+fn] = null;
        }
    }
}

//returns the cursor's position
function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY){
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    }
    else{
        cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
        cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
    }
    return cursor;
}

//returns today's date (client side) in yyyy-mm-dd format
function todayStr() {
    var now = new Date();
    if((now.getMonth() + 1) > 10){var fullMonth = now.getMonth() + 1;}
    else{var fullMonth = "0" + (now.getMonth() + 1);}
    if(now.getDate() > 10){var fullDay = now.getDate();}
    else{var fullDay = "0" + now.getDate();}
    return now.getFullYear() + "-" + fullMonth + "-" + fullDay;
}

//display back to top link if page length requires scrolling
function backToTop(){
    var headlineWrappperCount = 0;
    
    //TODO: remove the content ID version of this once all pages have been doov'ed with the main ID instead.
    if(document.getElementById('content')){var content = document.getElementById('content');}
    else if(document.getElementById('main')){var content = document.getElementById('main');}

    // Count the items in a listing page, and refuse to display "Back to Top" Link if less then 3 items
    for(i=0; i<document.getElementsByTagName('div').length; i++){
        if(document.getElementsByTagName('div')[i].className=="headlineWrapper"){
            headlineWrappperCount++;
        }
    }
    
    if(content){
        if((content.offsetHeight > document.documentElement.clientHeight) && (headlineWrappperCount > 3)){
            var topLink = document.createElement('a');
            var topLinkText = document.createTextNode('Back to Top');
            topLink.href= 'javascript:void(0)';
            topLink.onclick = function (){window.location = '#';}
            topLink.className = 'backToTop';
            topLink.appendChild(topLinkText);
            content.appendChild(topLink);
        }
    }
}

//disable any link that is not in a pop-up window, used on print pages
function disableInlineHrefs(){
    for(x = 0; x < document.getElementsByTagName('a').length; x++){
        if(document.getElementsByTagName('a')[x].target != "_blank" && document.getElementsByTagName('a')[x].href != "javascript:void(0)"){
            document.getElementsByTagName('a')[x].href = "javascript:void(0)";
            document.getElementsByTagName('a')[x].style.color = "#000000";
            document.getElementsByTagName('a')[x].style.textDecoration = "none";
            document.getElementsByTagName('a')[x].style.cursor = "text";
        }
    }
}

//find external CSS property value, script found at: http://javascriptkit.com/dhtmltutors/dhtmlcascade4.shtml
function cascadedstyle(el, cssproperty, csspropertyNS){
    if (el.currentStyle){ //if IE5+
        return el.currentStyle[cssproperty]
    }
    else if (window.getComputedStyle){ //if NS6+
        var elstyle=window.getComputedStyle(el, "")
        return elstyle.getPropertyValue(csspropertyNS)
    }
}

//trim a string
function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}

//get an object
function getObj(name) {
    if (name) {
        if (document.getElementById) {if (document.getElementById(name)) {this.obj = document.getElementById(name);this.style = document.getElementById(name).style;}else {return false;}}
        else if (document.all) {this.obj = document.all[name];this.style = document.all[name].style;}
        else if (document.layers) {this.obj = document.layers[name];this.style = document.layers[name];}
        else {return false;}
        return this;
    }
}

//opens new window
function openWin( windowURL, windowName, windowFeatures ) {
	return window.open( windowURL, windowName, windowFeatures ) ;
}

// Open Links in a new window, from http://www.456bereastreet.com/archive/200605/using_javascript_instead_of_target_to_open_new_windows/
function openInNewWindow() {
    // Change "_blank" to something like "newWindow" to load all links in the same new window
    var new_w = cascadedstyle(this, 'width', 'width'); //width
    var new_h = cascadedstyle(this, 'height', 'height'); //height
    var new_scroll = cascadedstyle(this, 'overflow', 'overflow'); //scrollbars & resizable

    //new window defaults if none have been passed in by the css
    if(new_w == "auto"){new_w = screen.width * .85;}
    if(new_h == "auto"){new_h = screen.height * .65;}
    if(new_scroll == "hidden"){new_scroll = 0;}else{new_scroll = 1;}

    var newWindow = window.open(this.getAttribute('href'), '_blank','location=1,width='+new_w+',height='+new_h+',resizable='+new_scroll+',scrollbars='+new_scroll);
    newWindow.focus();
    return false;
}

//Add the openInNewWindow function to the onclick event of links with a class name of "newwin", adapted from http://www.456bereastreet.com/archive/200605/using_javascript_instead_of_target_to_open_new_windows/
function getNewWindowLinks() {
    // Check that the browser is DOM compliant
    if (document.getElementById && document.createElement && document.appendChild) {
        // Find all links
        var link;
        var new_w;
        var new_h;
        var links = document.getElementsByTagName('a');
        for (var i = 0; i < links.length; i++) {
            link = links[i];
            // Find all links with a class name of "newwin" and a _blank target
            if (/\bnewwin\b/.exec(link.className) && link.target == "_blank") {
                var img   = document.createElement('img');
                img.setAttribute('src', '/_images/icon_newwin.gif');
                img.style.marginLeft = "2px";
                link.appendChild(img);
                link.onclick = openInNewWindow;
            }
        }
    }
}

//opens the various windows on Industry Tools
function docOpen(f,t){
    if (t == 'wholesale'){
        var chart = f;
        var url = "wholesale/" ;
        url += chart;
    }
    if (t == 'direct'){
        var chart = f;
        var url = "direct/" ;
        url += chart;
    }
    if (t == 'captive'){
        var chart = f;
        var url = "captive/" ;
        url += chart;
    }
    if (t == 'bank'){
        var chart = f;
        var url = "bank/" ;
        url += chart;
    }
    var w = window.open(url, "Top25", "menubar,toolbar,scrollbars,resizable,status,width=650,height=500");
    w.location.href = url;
    w.focus();
    return;
}

//builds a list of URIs from any tags within a specified container, original script found at: http://www.easy-designs.net/code/footnoteLinks/
function footnoteLinks(containerID,targetID) {
  if (!document.getElementById ||
      !document.getElementsByTagName ||
      !document.createElement) return false;
  if (!document.getElementById(containerID) ||
      !document.getElementById(targetID)) return false;
  var container = document.getElementById(containerID);
  var target    = document.getElementById(targetID);
  var h2        = document.createElement('h2');
  addClass.apply(h2,['printOnly']);
  var h2_txt    = document.createTextNode('Links');
  h2.appendChild(h2_txt);
  var coll = container.getElementsByTagName('a');
  var ol   = document.createElement('ol');
  addClass.apply(ol,['printOnly']);
  var myArr = [];
  var thisLink;
  var num = 1;
  var arrLen = false;
  //split the current URL into parts to find the domain name
  var domain_parts = window.location.toString().split('/');
  for (var i=0; i<coll.length; i++) {
      //split the link URL into parts to find its domain name
      var link_parts = coll[i].href.toString().split('/');
      //only change into a footnote if the anchor tag is not equal to a JS void and is not on this domain
      if(coll[i].getAttribute('href') != 'javascript:void(0)' && link_parts[2] != domain_parts[2]){
        var thisClass = coll[i].className;
        if ( (coll[i].getAttribute('href') ||
              coll[i].getAttribute('cite')) &&
              (thisClass == '' ||
               thisClass.indexOf('ignore') == -1)) {
          thisLink = coll[i].getAttribute('href') ? coll[i].href : coll[i].cite;
          var note = document.createElement('sup');
          addClass.apply(note,['printOnly']);
          var note_txt;
          var j = inArray.apply(myArr,[thisLink]);
          if ( j || j===0 ) {
            note_txt = document.createTextNode(j+1);
          } else {
            var li     = document.createElement('li');
            var li_txt = document.createTextNode(thisLink);
            li.appendChild(li_txt);
            ol.appendChild(li);
            myArr.push(thisLink);
            note_txt = document.createTextNode(num);
            num++;
          }
          note.appendChild(note_txt);
          if (coll[i].tagName.toLowerCase() == 'blockquote') {
            var lastChild = lastChildContainingText.apply(coll[i]);
            lastChild.appendChild(note);
          } else {
            coll[i].parentNode.insertBefore(note, coll[i].nextSibling);
          }
          arrLen = true;
        }
    }
  }
  if(arrLen == true){target.appendChild(h2);}
  target.appendChild(ol);
  addClass.apply(document.getElementsByTagName('html')[0],['noted']);
  return true;
}

//functions for browsers which do not inherently support the entire JavaScript Core, scripts found at: http://www.easy-designs.net/code/jsUtilities/
    //array.push (if unsupported)
    if(Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }; };
    //array.shift (if unsupported)
    if (Array.prototype.shift == null) { Array.prototype.shift = function() { var response = this[0]; for (var i=0; i < this.length-1; i++) { this[i] = this[i + 1]; }; this.length--; return response; }; };
    //function.apply (if unsupported), script found at: http://youngpup.net
    if (!Function.prototype.apply) { Function.prototype.apply = function(oScope, args) { var sarg = []; var rtrn, call; if (!oScope) oScope = window; if (!args) args = []; for (var i = 0; i < args.length; i++) { sarg[i] = "args["+i+"]";}; call = "oScope.__applyTemp__(" + sarg.join(",") + ");"; oScope.__applyTemp__ = this; rtrn = eval(call); oScope.__applyTemp__ = null; return rtrn;};};
    //Hunts for a value in the specified array
    function inArray(needle) { for (var i=0; i < this.length; i++) { if (this[i] === needle) { return i; } } return false; } Array.prototype.inArray = inArray;
    //verifies if something is an array
    function isArray() { return (typeof(this.length)=="undefined") ? false : true; }; Array.prototype.isArray = isArray;
    //sorts an array by key names
    function ksort() { var sArr = []; var tArr = []; var n = 0; for (i in this) tArr[n++] = i+"|"+this[i]; tArr = tArr.sort(); for (var i=0; i<tArr.length; i++) { var x = tArr[i].split("|"); sArr[x[0]] = x[1]; } return sArr; } Array.prototype.ksort = ksort;
    //appends the specified class to the object
    function addClass(theClass) { if (this.className != '') { this.className += ' ' + theClass; } else { this.className = theClass; } } Object.prototype.addClass = addClass;
    //removes the specified class to the object
    function removeClass(theClass) { var oldClass = this.className; var regExp = new RegExp('\\s?'+theClass+'\\b'); if (oldClass.indexOf(theClass) != -1) { this.className = oldClass.replace(regExp,''); } } Object.prototype.removeClass = removeClass;
    //finds the last block-level text-containing element within an object
    function lastChildContainingText() { var testChild = this.lastChild; var contentCntnr = ['p','li','dd']; while (testChild.nodeType != 1) { testChild = testChild.previousSibling; }  var tag = testChild.tagName.toLowerCase(); var tagInArr = inArray.apply(contentCntnr, [tag]); if (!tagInArr && tagInArr!==0) { testChild = lastChildContainingText.apply(testChild); } return testChild; } Object.prototype.lastChildContainingText = lastChildContainingText;

//sets an offsite indicator class to each content link that points to a domain other than the current domain
function offsiteLinkIndicator(){
    if(document.getElementById("main")){
        //split the current URL into parts to find the domain name
        var domain_parts = window.location.toString().split('/');

        $(document.getElementById("main")).find('a').each(
            function(i){
                //split the link URL into parts to find its domain name
                var link_parts = this.href.split('/');
               	if(
                    (link_parts[2] != domain_parts[2]) &&
                    (this.href != 'javascript:void(0)') &&
                    (link_parts[2] != undefined) && 
                    (link_parts[2] != 'ads.money-media.com')
                ){
                    if(this.className){
                        this.className = 'newwin ' + this.className;
                    } else {
                        this.className = 'newwin';
                    }
                }
            }
        );
        //once the classes are set, call the function that styles each class with that name
        getNewWindowLinks();
    }
}


// MOVO POLLING
var polling = {
	response: function(frm) {
		var resp = function(r) {
			if (parseInt(r.responseText)>0) {
				polling.refresh(frm.poll_id.value, frm.user_id.value);
			}
		};
		var option_value=0;
		if (frm.option_id.length != undefined) {
			for (var o=0; o<frm.option_id.length; o++) {
				if (frm.option_id[o].checked) {
					option_value=frm.option_id[o].value;
				}
			}
		} else {
			option_value = frm.option_id.value; // single option, should never reach this, here for error prevention
		}
		if (option_value!=0 && frm.user_id.value.length>0 && frm.poll_id.value.length>0) {
			var params = "action=response&user_id=" + frm.user_id.value + "&poll_id=" + frm.poll_id.value + "&option_id=" + option_value + "&";
			$.xml("POST", "/poll/action.html", params, resp); // jquery ajax
		}
	},

	refresh: function(poll_id, user_id, list){
		var resp=function(r){
			var poll = eval("(" + r.responseText + ")");
			var option_row = document.createElement("DIV");
			option_row.setAttribute('class', 'pollresponse');
			option_row.setAttribute('className', 'pollresponse');
			var wrap = document.getElementById("poll_" + poll_id);
			wrap.innerHTML = '';
			for (var o in poll) {
				if (!isNaN(parseInt(o))) {
					var opt=poll[o];
					var clone_row = option_row.cloneNode(true);
					clone_row.appendChild( document.createTextNode(opt['result'] + '%, ' + opt['option']) );
					clone_row.appendChild( document.createElement("BR") );
					var option_bar = document.createElement("IMG");
					option_bar.style.width = (opt['result'] == 0 ? '1px' : opt['result'] + '%');
					option_bar.style.height = '10px';
					option_bar.setAttribute('src', '/_images/logo_bar.gif');
					clone_row.appendChild(option_bar);
					wrap.appendChild(clone_row);
					wrap.innerHTML = wrap.innerHTML.replace(/&amp;/g, '&');
				}
			}
			var a_refresh = document.createElement("A");
			a_refresh.setAttribute("name", "refresh");
			a_refresh.onclick=function(){polling.refresh(poll_id, user_id, list)};
			a_refresh.innerHTML = "Refresh this poll";
			wrap.appendChild(a_refresh);
			if (list == undefined) {
				wrap.appendChild( document.createTextNode(' | ') );
				var a_list = document.createElement("A");
				a_list.setAttribute("href", "/poll/");
				a_list.innerHTML = "View a list of previous polls";
				wrap.appendChild(a_list);
			}
			document.body.style.cursor='auto';
		};
		if (parseInt(poll_id) > 0) {
			document.body.style.cursor='wait';
			var params = "action=request&poll_id=" + poll_id + "&user_id=" + user_id;
			try {
				$.xml("POST", "/poll/action.html", params, resp); // jquery ajax
			} catch (er) {
				window.refresh();
			}
		}
	}
}
