/**
 * Sourcelink jQuery plugin
 * 
 * A not-very-generic class for recognizing ZendFramework-style classnames
 * in the source and automagically creating links to them in the source browser
 * 
 * Usage: $('pre.source-block').sourcelink({'LibraryName':'/path/to/lib/root'},'/path/to/filebrowser'); // initializes all source blocks
 * 
 * @author Mikko Hämäläinen <mkoh@mkoh.net>
 */

(function($){

	$.fn.sourcelink = function(paths, browserRoot){
		
		return this.each(function(){
			// loop through every library
			for(className in paths) {
				var currentElement = this;
				// matches ZendFramework style classnames
				var reg = new RegExp("("+className+"(_([A-Za-z0-9_]*))+)", "g");
				var matches = currentElement.innerHTML.match(reg);
				// get distinct classnames by making the array unique
				var uniqClassNames = [];
				for(i in matches) {
				    // if unique and last char is not "_" (that's a hack, todo: fix regexp)
					if(uniqClassNames.indexOf(matches[i]) < 0 && matches[i].charAt(matches[i].length -1) != '_') {
						uniqClassNames.push(matches[i]);
					}
				}
				// for each found class..
				$(uniqClassNames).each(function(){
                    // console.debug(this.toString());
					// .. parse the url (replace "_" with "/")
					var library = this.toString().split("_").shift();
					var linkPath = this.replace(/_/g,"/");
					// .. and get the full filesystem path
					linkPath = browserRoot+paths[library]+"/"+linkPath+'.php';
					// now find each instance of the classname and make it a link
					var classMatch = new RegExp("("+this.toString()+")([^a-zA-Z0-9_])", "g");
					// finally update the html of the element
					currentElement.innerHTML = currentElement.innerHTML.replace(classMatch,"<a class=\"sh_function linked-class\" href=\""+linkPath+"\">$1</a>$2");
				});
			}			
		});
	};
})(jQuery);
