/* JS Document */

//version:   1.0
//author:    Valentina Cartei
//email:     val.cartei@gmail.com


//Get Element by Class Name from: http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/

function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}


/*********************************************************************/
/* addCaption FUNCTION : @aclass, els with that class are retrieved  */
/* create a caption for all the imgs with class use_caption_as_title */
/* first, a div wrapper is created, then a par whose text node is 	 */
/* the caption and the image, are appended to the wrapper div node.	 */
/* The class use_caption_as_title is assigned to the div.			 */							
/* the width of the image is retrieved and assigned to the width	 */
/* of the div.														 */
/*********************************************************************/

function addCaption(aClass) {
//get all images with class specified by aClass parameter
	var captionImages = getElementsByClassName(document, "img", aClass);
	for ( var i=0; i<captionImages.length; i++) {
		//create the div wrapper of the image and caption
		var imageWrapper= document.createElement("div");
		//the caption (it is a paragraph node)
		var imageCaptionPar = document.createElement("p");
		//create a text node for the caption and append it to it
		var imageCaption = document.createTextNode(captionImages[i].title);
		imageCaptionPar.appendChild(imageCaption);
		if (captionImages[i].parentNode.getAttribute("href")!=null){
			captionImages[i].parentNode.parentNode.insertBefore(imageWrapper,captionImages[i].parentNode);
			imageWrapper.appendChild(captionImages[i].parentNode);
		}
		else{
			captionImages[i].parentNode.insertBefore(imageWrapper,captionImages[i]);
			imageWrapper.appendChild(captionImages[i]);}
		//img must have a title attrib, which is its caption
		if ( captionImages[i].title != "" ) {
		imageWrapper.appendChild(imageCaptionPar); 
		}
		imageWrapper.className=captionImages[i].className;
		//imageWrapper.className =aClass;
		captionImages[i].className = "";
		var imageWidth = captionImages[i].getAttribute("width");
		imageWrapper.style.width = imageWidth + "px";
		
    }
}




// Runs all the listed functions on the loading of the window

window.onload=function(){
addCaption("use-title-as-caption");
}

