/* Javascript originally written by: Brett Chang of evercloud.com */
/* Javascript altered to create one Div with a class of "caption" containing the image and the images alt-text displayed within a span for flexible styling abilities*/

function st_getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function addImgCaption(myImgElem){
  var myParent = myImgElem.parentNode;
  var newParentNode;
  var eDiv = document.createElement("div");
  var eBr = document.createElement("br");
  var eSpan = document.createElement("span");
  var eCaption =  document.createTextNode (myImgElem.getAttribute('alt'));
  var anchorNode;
  var anchorNodeParent;
  
    // Create a container <div> for the <img> and <span>

  eDiv.className = "caption";
  eDiv.style.width=myImgElem.getAttribute("width")+"px";
  eDiv.style.cssFloat=myImgElem.getAttribute("align");
  eDiv.style.styleFloat=myImgElem.getAttribute("align");
	
    // If the <img> parent is an <a> we need to insert the <a> and then
    // insert the <img>
    
  if( myImgElem.parentNode.nodeName == 'A' ){
    anchorNode = myImgElem.parentNode;
    anchorNodeParent = myImgElem.parentNode.parentNode;
    // Tell the anchor node's parent to replace the anchor node with the new div node
    anchorNodeParent.replaceChild(eDiv, anchorNode);
    // Apend the anchor node (with img child node) to the new div node
    eDiv.appendChild( anchorNode );
   } else {
    // Tell the img node's parent to replace the img node with the new div node
    myImgElem.parentNode.replaceChild(eDiv, myImgElem);
    // And add the img to the new div node
    eDiv.appendChild(myImgElem);
  }
  eDiv.appendChild(eBr);
  
  var imgAlt = myImgElem.getAttribute("alt");
  var imgSrc = myImgElem.getAttribute("src");  
  var imgSplit = imgSrc.split("/");
  var imgCount = (imgSplit.length-1);
  var imgName = imgSplit[imgCount];

  if(imgAlt != null && imgName != imgAlt && imgAlt != ""){
    eDiv.appendChild(eSpan);
    eSpan.appendChild(eCaption);
  }
  
  myImgElem.setAttribute("alt", "");
  myImgElem.removeAttribute("title");
  myImgElem.removeAttribute("align");
}

function st_image_captions(){
	var myImages = st_getElementsByClass("captionimg", document, 'img');
	for(var i=0;i<myImages.length;i++){	
		addImgCaption(myImages[i]);
	}
}

window.onload = st_image_captions;
