<!--- Only load when doc is fully ready --->
$(document).ready(function() {
	
	//For each img on the page
	$("img").each(function() {
		
		//Get our alt tag, alignment and setup pattern to find caption
		var CurrImgAlt = $(this).attr("alt");
		var CurrImgAlign = $(this).attr("align");
		var CurrImgWidth = $(this).attr("width");
		var CurrImgVSpace = $(this).attr("vspace");
		var CurrImgHSpace = $(this).attr("hspace");
		var sPattern = "\[Caption\]";
		
		if (CurrImgAlt.length > 0) {		
		
			//Try to check if this alt tag starts with our special starting string
			if (CurrImgAlt.search(sPattern) != -1) {
				//Get our caption text (trimming any spaces/etc
				var sCaptionText = TrimString(CurrImgAlt.substring(9,CurrImgAlt.length));
				
				//Based on alignment, determine what class to apply to the wrapping span
				if(CurrImgAlign.toLowerCase() == 'right') {
					var ImgAlign = 'imagebox_right';
				} else if (CurrImgAlign.toLowerCase() == 'left') {
					var ImgAlign = 'imagebox_left';
				} else {
					var ImgAlign = 'imagebox';
				}
				
				//Build style for caption span
				sCaptionStyle = "width: "+CurrImgWidth+"px;";
				
				/* For now, don't apply top/bottom padding to caption
				if(CurrImgVSpace > 0) {				
					sCaptionStyle += " padding-top: "+CurrImgVSpace+"px; padding-bottom: "+CurrImgVSpace+"px;";				
				}
				*/
				
				//Apply any left/right padding to the caption to keep it aligned w/image
				if(CurrImgHSpace > 0) {				
					sCaptionStyle += " padding-left: "+CurrImgHSpace+"px; padding-right: "+CurrImgHSpace+"px;";				
				}
				
				//Wrap our span w/alignment class
				$(this).wrap("<span class='"+ImgAlign+"'></span>");		
				
				//Now insert our caption in a span after the img tag, set width of span to match
				//the image width so that it can wrap properly/etc
				//Must do it here to ensure it remains within the span we added around it
				$(this).after("<span style='"+sCaptionStyle+"'>"+sCaptionText+"</span>");
				
				/* Clean Up attributes */				
				//Add a title attribute for other browsers and update alt to remove "[Caption]"
				$(this).attr("title",sCaptionText);
				$(this).attr("alt",sCaptionText);
				
				//Remove the alignment attribute
				$(this).attr("align","");				
				
			}
			
		}
   	});

});
