( function() {
	
	// Creating a unique name
	var trueName = '';
	var demotape_webRoot = 'http://www.demotape.no/';
	
	for (var i = 0; i < 16; i++) {
		trueName += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
	}
	window[trueName] = {};
	var $ = window[trueName];
	
	$.f = function() {
		return {
			init : function(target) {
			var theScripts = document.getElementsByTagName('SCRIPT');
			
			for (var i = 0; i < theScripts.length; i++) {
				if (theScripts[i].src.match(target)) {
						
					$.a = {};
					var songId = '';
					var songName = '';
					var artistName = '';
					
					if (theScripts[i].innerHTML) {
						$.a = $.f.parseJson(theScripts[i].innerHTML);
						if ($.a.songId) {
							songId = $.a.songId;
						}
					}
					if ($.a.err) {
						//alert('bad json!');
					}
					
					//JSON SONG OBJECT
					//callData();
					if (!$.f.runFunction) {
						$.f.runFunction = [];
					}
					var n = $.f.runFunction.length;
					var id = trueName + '.f.runFunction[' + n + ']';
					
					$.f.runFunction[n] = function(r) {
						delete($.f.runFunction[n]);
						$.f.removeScript(id);
						$.f.renderResult(r, trueName);
					}
					
					//Creating the outer DIV
					$.container = document.createElement('DIV');
					$.container.id = "demotapeBadgeContainer_" + trueName;
					$.container.className = trueName;
					$.container.innerHTML = '<iframe src="' + demotape_webRoot + 'embed/song/' + songId + '" scrolling="no" frameborder="0" style="border:none;overflow:hidden;width:400px;height:89px;" allowTransparency="true"></iframe>';
					
					theScripts[i].parentNode.insertBefore($.container, theScripts[i]);
					theScripts[i].parentNode.removeChild(theScripts[i]);

					break;
				}
			}
			},
			parseJson : function(json) {
				this.parseJson.data = json;
				if ( typeof json !== 'string') {
					return {"err":"trying to parse a non-string JSON object"};
				}
				try {
					var f = Function(['var document,top,self,window,parent,Number,Date,Object,Function,',
					                  'Array,String,Math,RegExp,Image,ActiveXObject;',
					                  'return (' , json.replace(/<\!--.+-->/gim,'').replace(/\bfunction\b/g,'function­') , ');'].join(''));
					return f();
				} catch (e) {
					return {"err":"trouble parsing JSON object"};
				}
			}
		};
	}();
	//var thisScript = /^https?:\/\/[^\/]*localhost\/demotape\/js\/badge\/demotape.player.js$/;
	var thisScript = /^https?:\/\/[^\/]*www.demotape.no\/js\/badge\/demotape.player.js$/;
	if (typeof window.addEventListener !== 'undefined') {
		window.addEventListener('load', function() { $.f.init(thisScript); }, false);
	} else if (typeof window.attachEvent !== 'undefined') {
		window.attachEvent('onload', function() { $.f.init(thisScript); });
	}
})();

