/**
 * Fetches an collection of DOM elements by class name.
 * 
 * @author Robert Nyman <http://www.robertnyman.com>
 * @see Code/licensing: http://code.google.com/p/getelementsbyclassname/
 */
var getElementsByClassName = function (className, tag, elm){
  if (document.getElementsByClassName) {
    getElementsByClassName = function (className, tag, elm) {
      elm = elm || document;
      var elements = elm.getElementsByClassName(className),
        nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
        returnElements = [],
        current;
      for(var i=0, il=elements.length; i<il; i+=1){
        current = elements[i];
        if(!nodeName || nodeName.test(current.nodeName)) {
          returnElements.push(current);
        }
      }
      return returnElements;
    };
  }
  else if (document.evaluate) {
    getElementsByClassName = function (className, tag, elm) {
      tag = tag || "*";
      elm = elm || document;
      var classes = className.split(" "),
        classesToCheck = "",
        xhtmlNamespace = "http://www.w3.org/1999/xhtml",
        namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
        returnElements = [],
        elements,
        node;
      for(var j=0, jl=classes.length; j<jl; j+=1){
        classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
      }
      try {
        elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
      }
      catch (e) {
        elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
      }
      while ((node = elements.iterateNext())) {
        returnElements.push(node);
      }
      return returnElements;
    };
  }
  else {
    getElementsByClassName = function (className, tag, elm) {
      tag = tag || "*";
      elm = elm || document;
      var classes = className.split(" "),
        classesToCheck = [],
        elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
        current,
        returnElements = [],
        match;
      for(var k=0, kl=classes.length; k<kl; k+=1){
        classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
      }
      for(var l=0, ll=elements.length; l<ll; l+=1){
        current = elements[l];
        match = false;
        for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
          match = classesToCheck[m].test(current.className);
          if (!match) {
            break;
          }
        }
        if (match) {
          returnElements.push(current);
        }
      }
      return returnElements;
    };
  }
  return getElementsByClassName(className, tag, elm);
};

/* Used in making PageTracker URL's *******************************************/
function getPageTypeFromMetaTag() {
  return $('meta[name=page-type]').eq(0).attr('content');
}

function getCategoryFromMetaTag() {
  return $('meta[name=category]').eq(0).attr('content');
}

/* Used by topproducts component in product modules ***************************/
function updateHomepageTopproducts(tagId, tagSlug) {
  $(".tp_top.refresh").load("/product/topproducts .refreshwith", { tag_id: tagId });

  // Track in Google Analytics
  if (typeof(tagSlug) != 'undefined') {
    window.trackPageView('events/top-product-tab/' + getPageTypeFromMetaTag() + '/' + tagSlug);
  }
}


/* Used only in CMS modules ***************************************************/
function ClearForm(formElement,defaultMessage,defaultClass) {
  defaultClass = !defaultClass.length ? 'normal' : defaultClass ;
  formElement.className = defaultClass ;
  if(formElement.value == defaultMessage) {
    formElement.value = "" ;
  }
}

function ResetForm(formElement,defaultMessage) {
  if(formElement.value === "" || formElement.value == defaultMessage) {
    formElement.value = defaultMessage ;
  }
}

function SwapErrorDivContents(t,theErrorDiv){
  for(var x=theErrorDiv.getElementsByTagName('p').length;x>0;x--){
    theErrorDiv.removeChild(theErrorDiv.getElementsByTagName('p')[x-1]) ;
  }
  
  if(t == "error"){
    if(theErrorDiv.getElementsByTagName('a').length > 0){ theErrorDiv.getElementsByTagName('a')[0].style.display = "none" ; }
  } else {
    if(theErrorDiv.getElementsByTagName('a').length > 0){ theErrorDiv.getElementsByTagName('a')[0].style.display = "inline" ; }
  }
}

function DisplayError(formID,ErrorMessage,ErrorClass,errNodeName) {
    if(!document.theForm) {
      theForm = document.getElementById(formID);
    }
    
    //isolate the div we'll be sending the error to
    errNodeName = !errNodeName.length ? 'formdetail' : errNodeName;
    var errNodes = getElementsByClassName(errNodeName,theForm);
    
    if (!errNodes) {
      alert('Please report this; getElementsByClassName() failed.');
    }
    
    var errNode = errNodes[0];
    
    /*if (errNode != null && errNode.childNodes && errNode.childNodes.length > 0) {
        while (errNode.firstChild) {
            errNode.removeChild(errNode.firstChild) ;
        }
    }*/
    //rather than clear it, hide the contents so it can be un-hidden after
    SwapErrorDivContents("error",errNode);
    
    //append the error message
    var errText = document.createElement('p');
    errText.className = ErrorClass;
    errText.appendChild(document.createTextNode(ErrorMessage));
    errNode.appendChild(errText);
}

function ReplaceDivContents(divName, replacementContent) {
  var theDiv  = document.getElementById(divName);
  // clear out the original contents of the div
  while (theDiv.firstChild) {
    theDiv.removeChild(theDiv.firstChild) ;
  }
  // put the replacement content in instead
  theDiv.innerHTML = replacementContent ;
}

/* Used by edit templates in the article module *******************/
function stripHTML(oldString) {
  return oldString.replace(/<(?:.|\s)*?>/g, ""); 
}

/* Used by informarates component in the widgets module ***********************/
function createInformaModule(lastUpdated){
  $("#provided_note").before('<div id="med_overlay_module"><div id="med_overlay_top"></div><div id="med_overlay_mid"><p>The rate information on this page is powered by Informa Research Services, Inc. &copy; 2009. This information has been obtained from various financial institutions, and Informa Research Services cannot guarantee its accuracy. The information includes financial product data that was in the Informa Research Services database at the time of publication, and may not reflect all of the products available in your region. Before acting on the information shown on this page, contact the financial institution to verify the accuracy of the data. When contacting financial institutions, always mention FiLife to ensure you receive the preferred Internet rate. Contact <a href="mailto:links@informars.com">links@informars.com</a> to have your rates included in this chart.');
}

function removeInformaModule(){
  $("#med_overlay_module").remove();
}

/* Used by templates in the informarates module *******************************/
function openFooter() {
  document.getElementById("med_overlay_footer").className = "";
}

function closeFooter() {
  document.getElementById("med_overlay_footer").className = "hideit";
}

function openInforma() {
  document.getElementById("med_overlay").className="";
}

function closeInforma() {
  document.getElementById("med_overlay").className="hideit";
}

function openNumber(x) {
  document.getElementById(x).className="call_hover_container";
}

function closeNumber(x) {
  document.getElementById(x).className="call_hover_container hideit";
}