(function ($) {
	
	/* 
	umoznuje zobrazovat reklamni bannery systemu openx asynchronne
	
	spolupracuje se skriptem openx-advert.php
	cestu ke skriptu je mozne definovat pomoci 
	$.fn.nmopenx.defaults.url = 'inc/openx-advert.php';
	
	parametry banneru je mozne zadat do elementu, ktery ho spousti
	napr:
	<span class="openxadvert-titul {zoneid:20, user: 'karel', lang: 'cs'}" />
	
	v souboru openx-advert je ale potreba definovat nazvy povolenych parametru ($allowedParams)
	*/
	var _loopIterations = 20;

	function _documentWriteSafeAppend(markup, $this) {
	    var cnt = 0; // prevent infinite loops
	    (function (markup) {
	        if (markup.match(/document\.write|<script/)) {
	            var oldDocumentWrite = document.write;
	            var buffer = '';
	            document.write = function (markup) {
	                buffer += markup;
	            };
	            $this.append(markup);
	            document.write = oldDocumentWrite;
	
	            cnt++;
	            if (cnt > _loopIterations) {
	                $.error('nmopenx: document.write loop stopped after ' + _loopIterations + ' iterations');
	            }
	            arguments.callee(buffer);
	        }
	        else {
	            $this.append(markup);
	            if (typeof success == 'function') {
	                setTimeout(success, 0);
	            }
	        }
	    })(markup);
	}

	function _buildRequestParameters(settings) {
		var data = settings;
		var notallowedKeys = new Array('url');
		
		for (var key in notallowedKeys) {
			delete (data[notallowedKeys[key]]);
		}
		
		return data;
	}

  var init = function (options) {
		// nacteni parametru
		var opts = $.extend({}, $.fn.nmopenx.defaults, options);
		// iterace pro kazdy element
		
		return this.each(function() {
			$this = $(this);
			// parametry elementu
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;
			debug(o);
	
			var data = _buildRequestParameters(o);
			$.ajax({
				url: opts['url'],
				data: data,
				cache: false,
				success: function(data) {
					_documentWriteSafeAppend('<script type="text/javascript">' + data + '</script>', $this);
				}
			});
		});
	
	};

	function debug($obj) {
		if (window.console && window.console.log)
			window.console.log('nmopenx elements count: ' + $obj);
	}

  var methods = {
		init: init
  };

	$.fn.nmopenx = function(method) {
		debug (this);
 		if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        return methods.init.apply(this, arguments);
    } else {
        $.error('Method ' +  method + ' does not exist on jQuery.nmopenx');
    }
  };

	$.fn.nmopenx.defaults = {
		'url' : 'inc/openx-advert.php'
	};
}) (jQuery);
