/**
 * Inject code into function
 * USAGE:
 * 	1)	$.functionInject(
			[jQuery.fn,'markItUp'],
			'console.log("markItUp resulting settings:",settings);'
		);
 *	2)	$.functionInject(
			[jQuery.fn,'markItUp'],
			function(settings){
				console.log("markItUp resulting settings:",settings);
			}
		);
 * @author Sergey S Yaglov
 * @license	MIT+GPL
 * @version 0.0.1
 */
(function($) {
	
	$.functionClone = function(func,as_text,no_def) {
		var f;
		if(typeof func=='string'){
			eval('f = '+func+';');
		}else if(typeof func=='object'){
			f = func[0][func[1]];
		}else{
			f = func;
		}
		if(typeof f=='function'){
			var fbody = f.toString().replace(/^(function)([^\(]*)\(/gi, '$1 (');
			if(typeof as_text!='undefined' && as_text){
				if(typeof no_def!='undefined' && no_def){
					return fbody.replace(/^[^\{]*\{/gi, '').replace(/\}$/gi, '');
				}else{
					return fbody;
				}
			}
			return eval('('+fbody+')');
		}
		return function(){};
	};
	
	/**
	 * @param func functionName|object[parentObject,functionName] Name of function that will be modified
	 * @param funcInj function|string Function or code to be injected
	 */
	$.functionInject = function(func,funcInj) {
		var funcBody = $.functionClone(func, 1);
		var funcDefinition = (typeof func=='string'?func:(typeof func=='object'?'func[0][func[1]]':'func'))+' = ';
		if(typeof funcInj=='function'){
			var funcInjName = 'funcInj'+Math.floor(Math.random()*1000000);
			eval('window["'+funcInjName+'"] = funcInj;');
			eval(funcDefinition + funcBody.replace(/\{/,'{ '+funcInjName+'.apply(this, arguments); '));
		}else{
			eval(funcDefinition  + funcBody.replace(/\{/,'{ '+funcInj+'; '));
		}
	};
	
})(jQuery);
