var AdTaily = {};
AdTaily.Author="@author AdTaily.com, 2009, @author Pawel Rzymkowski for AdTaily.com, 2009";
AdTaily.REV = "1.2009-09-19,9.30";
AdTaily.WIDGET_CONTAINER_ID = "AdTaily_Widget_Container";
AdTaily.WIDGET_SCRIPT_ID = "AdTaily_Widget";
AdTaily.Exceptions = {};
AdTaily.Exceptions.WIDGET_CANNOT_BE_SHOWN = "One of widget rendering methods failed!";
AdTaily.Exceptions.WIDGET_RENDERING_ERROR = "There was a problem when tried to render widget!";
AdTaily.Exceptions.WIDGET_INITIALIZING_ERROR = "There was a problem when initializing widget settings";
AdTaily.Exceptions.WIDGET_BUY_FORM_CANNOT_BE_SHOWN = "Buy form cannot be shown!";
AdTaily.Timers = {};
AdTaily.Timers.REFLOW_TIME_MILISECONDS = 15;
AdTaily.Timers.LOAD_TIME_MILISECONDS = 40;
AdTaily.Timers.RESIZE_DELAY_MILISECONDS = 200;
AdTaily.isCenterImages = false; //false = do lewej, true = centruje w maksymalnej dostepnej szerokosci.
AdTaily.debug =  true;
AdTaily.Console = function(msg){
	if (AdTaily.debug === true) {
		if (typeof window.console !== 'object') {
			var console = {};
			console.log = function(){
				return;
			};
		}
		else {
			window.console.log(msg);
		}
	}
};

AdTaily.getCSSRule = function(ruleName, deleteFlag){
	ruleName = ruleName.toLowerCase();
	if (document.styleSheets) {
		for (var i = 0; i < document.styleSheets.length; i++) {
			var styleSheet = document.styleSheets[i];
			if (styleSheet.title == "AdtailyWidgetCSS") {
				var ii = 0;
				var cssRule = false;
				do {
					if (styleSheet.cssRules) {
						cssRule = styleSheet.cssRules[ii];
					}
					else {
						cssRule = styleSheet.rules[ii];
					}
					if (cssRule) {
						if (cssRule.selectorText.toLowerCase() == ruleName) {
							if (deleteFlag == 'delete') {
								if (styleSheet.cssRules) {
									styleSheet.deleteRule(ii);
								}
								else {
									styleSheet.removeRule(ii);
								}
								return true;
							}
							else {
								return cssRule;
							}
						}
					}
					ii++;
				}
				while (cssRule);
			}
		}
	}
	return false;
};

AdTaily.killCSSRule = function (ruleName){   
	return AdTaily.getCSSRule(ruleName, 'delete'); 
};                                                     

AdTaily.addCSSRuleWidget = function(ruleName) {                           
	if (document.styleSheets) {
	  if (!AdTaily.getCSSRule(ruleName)) {
	     if (document.styleSheets[0].addRule) {
		 	var c = AdTaily.returnWidgetCSS();         
	        c.addRule(ruleName, null,0); 
	     } else { 
		 	var c = AdTaily.returnWidgetCSS();
	        c.insertRule(ruleName+' { }', 0);
	     }
	  }
	}
	return AdTaily.getCSSRule(ruleName);
};
		
AdTaily.returnWidgetCSS = function(){
	if (document.styleSheets) {
		for (var i = 0; i < document.styleSheets.length; i++) {
			if (document.styleSheets[i].title == "AdtailyWidgetCSS") {
				return document.styleSheets[i];
			}
		}
	}
};	

AdTaily.addEvent = function(a, c, b){
    if (a.attachEvent) {
        a.attachEvent("on" + c, b);
    }
    else {
        if (a.addEventListener) {
            a.addEventListener(c, b, false);
        }
    }
};

AdTaily.addLoadEvent = function(func){
	var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function(){
            if (oldonload) {
                oldonload();
            }
            func();
        };
    }
};

AdTaily.showDuplicateWidgetError = function(){
    return '<div style="font-size:13px;font-family:Lucida Grande,verdana,arial,helvetica,sans-serif;color: #EC1200;margin:0;padding: 10px;display:block;position:relative;width:auto;height:auto;overflow:visible;background-color:#FFD3CF;border:1px dashed #FF1400">Masz wklejone dwa skrypty widgetu AdTaily na tej stronie. Skasuj jeden z nich...</div>';
};

AdTaily.Position = function(top, left){
    this.top = top;
    this.left = left;
};

AdTaily.getHostname = function (str) {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	return str.match(re)[1].toString();
};

AdTaily.getUrlParameter = function(name){
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results === null) {
		return "";
	}
	else {
		return results[1];
	}
};

AdTaily.attachScript = function(string){
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.innerHTML = string;
    document.body.appendChild(script);
};

AdTaily.loadAndAttachScript = function(url){
    AdTaily.Console('loadAndAttach');
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    var head = document.getElementsByTagName("head")[0];
    if (head) {
        head.appendChild(script);
    }
    else {
        document.body.appendChild(script);
    }
};

AdTaily.getCurrentPosition = function(obj){
    var curleft = 0;
    var curtop = 0;
    
    for (o = obj; o !== null; o = o.offsetParent) {
        curleft += o.offsetLeft;
        curtop += o.offsetTop;
    }
    return new AdTaily.Position(curtop, curleft);
};

AdTaily.getUrlHash = function(){
    return unescape(window.location.hash.substring(1));
};

AdTaily.setUrlHash = function(string){
    window.location.hash = string;
};

AdTaily.createElement = function(type){
    var element = document.createElement(type);
    element.style.cssText = "position: relative; display: block; font-weight: normal; text-align: left; width: auto; height: auto; background: none; padding: 0; margin: 0;";
    return element;
};

AdTaily.renderErrorMessage = function(error){
	if (typeof window.console === 'object') {
        AdTaily.Console(error);
    }
    else {
        var errorMessage = AdTaily.createElement("span");
        errorMessage.style.display = 'none';
        errorMessage.innerHTML = error;
        errorMessage.id = "AdTaily_Silent_Error_Message";
        if (document.body) {
            document.body.appendChild(errorMessage);
        }
        else {
            throw error;
        }
    }
};

AdTaily.Widget = function(){
    AdTaily.Console('widgetConstruct');
    this.titleText = 'Sponsorzy strony';
    this.buyButtonText = "Reklama na tej stronie";
    this.homeLinkTitle = "Pobierz taki widget z AdTaily.com";
    this.closeButtonText = "Zamknij";
    this.cancelButtonText = "Anuluj";
    this.backgroundColor = "#F3FAE6";
    this.borderColor = "#42BE31";
    this.borderSize = 1;
    this.openWidgetMinWidth = 300;
    this.openWidgetMinHeight = 500;
    this.imageWidth = 125;
	this.imageHeight = 125;
    this.imageMargin = 10;
    this.closedWidgetMinWidth = this.imageWidth + 2 * this.imageMargin;
    this.version = "0.3";
    
    this.data = null;
    this.resizeTimer = new Date();
    this.recentWidth = 0;
    this.imageCount = 99;
    this.body = AdTaily.createElement('div');
	this.reflowRemoved = false;
	this.isShowThankYouMessage = false;
	
	this.title = null;
	this.buyButton = null;
	this.footerLink = null;
    
    this.url = window.location;
    this.protocol = "http://";
    this.new_campaign_path = "/widget/campaigns/new";
    this.json_links_path = "/links/";
    
    if (AdTaily.KEY !== null && AdTaily.KEY !== undefined) {
        this.key = AdTaily.KEY;
    }
    else {
        throw "Script or widget key is corrupted!";
    }
    
    this.hostname = AdTaily.HOST;
	this.container = document.getElementById(AdTaily.WIDGET_CONTAINER_ID);
};

AdTaily.removeReflow = function(){
	AdTaily.Console('removeReflow');
	try {
		clearInterval(AdTaily.reflowInterval);
		AdTaily.reflowRemoved = true;
	}
	catch (error){AdTaily.renderErrorMessage(error);}
};

AdTaily.start = function(){
    AdTaily.Console('start');
    try {
        AdTaily.widget = new AdTaily.Widget();
    } 
    catch (error) {
        AdTaily.renderErrorMessage(error);
		return;
    }
    AdTaily.widget.loadingData = true;
    try {
        AdTaily.widget.loadData();
    } 
    catch (error2) {
        AdTaily.renderErrorMessage(error2);
		return;
    }
    try {
        var load = function(){
            if (AdTaily.widget.loadingData === false) {
                try {
                    AdTaily.widget.drawWidget();
					if (AdTaily.reflowRemoved === false) {
						AdTaily.reflowInterval = setInterval(AdTaily.widget.reflow, AdTaily.Timers.REFLOW_TIME_MILISECONDS);
					}
                } 
                catch (e) {
                    AdTaily.renderErrorMessage(e);
                }
                finally {
                    clearInterval(AdTaily.startInterval);
                }
            }
        };
		AdTaily.startInterval = setInterval(load, AdTaily.Timers.LOAD_TIME_MILISECONDS);
		AdTaily.addEvent(window,'load',AdTaily.removeReflow);
    } 
    catch (error3) {
        AdTaily.renderErrorMessage(error3);
		return;
    }
	AdTaily.Console('start End');
};

AdTaily.Widget.prototype.reflow = function(){
    
    try {
        if (AdTaily.widget.recentWidth != document.getElementById(AdTaily.WIDGET_CONTAINER_ID).parentNode.offsetWidth) {
            AdTaily.widget.solveDimensions();
        }
    } 
    catch (error) {
        AdTaily.renderErrorMessage(error);
    }
	AdTaily.Console('reflow');
};

AdTaily.Widget.prototype.drawWidget = function(){
	if (this.error === true) {return;}
	AdTaily.Console('drawWidget');
    var widget = AdTaily.createElement('div');
    widget.style.cssText = "text-align: left; position: relative; display: block; border-style: solid;"; //width: 100%;
    widget.style.backgroundColor = this.backgroundColor;
	widget.style.borderColor = this.borderColor;
	widget.style.borderWidth = this.borderSize + "px";
	this.body = widget;
    
	this.solveDimensions();
    this.showTitle();
	if (this.data.links.length>0) {
		this.body.appendChild(this.createImgStructure(this.data));
    }
    this.showBuyButton();
    this.showFooter();
	document.getElementById(AdTaily.WIDGET_CONTAINER_ID).appendChild(this.body);
	
	if (this.isShowThankYouMessage === true){
		this.showThankYouMessage();
	}
	
    var me = this;
    var resizeHandler = function(){
		AdTaily.Console('resize');
		if (new Date().getTime() - me.resizeTimer.getTime() > AdTaily.Timers.RESIZE_DELAY_MILISECONDS) {
            me.resizeTimer = new Date();
            me.solveDimensions();
        }
    };
	AdTaily.addEvent(window,'resize',resizeHandler);
	AdTaily.Console('drawWidget end');
};

AdTaily.Widget.prototype.createImgStructure = function(data){
	var f = document.createDocumentFragment();
	
	var d1 = document.createElement("div");
	d1.id = "ADTAILY_WIDGET_D1";
	d1.className = "ADTAILY_WIDGET_D1";
	d1.style.clear = "both";
	d1.style.overflow = "hidden";
	
	var d2 = document.createElement("div");
	d2.id = "ADTAILY_WIDGET_D2";
	d2.className = "ADTAILY_WIDGET_D2";
	d2.style.width = "100%";
	
	this.buildImages(this.constructImageLinks(data),d2);

	var br = document.createElement("div");
	br.className = "ADTAILY_WIDGET_BR";
	var br2 = document.createElement("div");
	br2.className = "ADTAILY_WIDGET_BR";
	d2.appendChild(br2);
	d1.appendChild(d2);
	d1.appendChild(br);
	f.appendChild(d1);
	
	return f;
};

AdTaily.Widget.prototype.buildImages = function(imgArray, parentDiv){
	AdTaily.Console('buildImages');
	for (var i = 0; i < imgArray.length; i++) {
		var center = document.createElement('center');
		center.style.cssText = "float: left;padding-top: 5px; padding-bottom:5px;";
		center.appendChild(imgArray[i]);
		parentDiv.appendChild(center);
	}
};

AdTaily.Widget.prototype.constructImageLinks = function(data) {
	AdTaily.Console('constructImageLinks');
	var imgArray = new Array();
	for (var i=0; i<data.links.length; i++) {
		var tmpLink = document.createElement("a");
		if (data.links[i].title !== undefined) {
			tmpLink.title = data.links[i].title;
		}
		if (data.links[i].link !== undefined) {
			tmpLink.href = data.links[i].link;
		}
		tmpLink.rel = "nofollow";
		tmpLink.target = "_blank";
		if (data.links[i].click && data.links[i].click !== undefined)
		{
			var clickURL = data.links[i].click;
			tmpLink.onmousedown = (function(click){
				return (function(){this.href = click; return true;});
			})(clickURL);
		}
		var img = document.createElement('img');
		img.height = this.imageHeight;
		img.width = this.imageWidth; 
		img.style.cssText = "float: right; border: none; padding: 0 !important; margin: 0 !important;";
		if (data.links[i].title !== undefined) {
			img.alt = data.links[i].title;
		}
		img.src = data.links[i].image;
        img.onmouseover = function(){
            this.style.filter = 'alpha(opacity=80)';
            this.style.MozOpacity = '0.8';
            this.style.opacity = '0.8';
        };
        img.onmouseout = function(){
            this.style.filter = 'alpha(opacity=100)';
            this.style.MozOpacity = '1.0';
            this.style.opacity = '1.0';
        };
		tmpLink.appendChild(img);
		imgArray[i] = tmpLink;
		if (data.links[i].external_js_tracker) {
			try {
				eval(data.links[i].external_js_tracker);
			} catch (e) {AdTaily.renderErrorMessage(e);}
		}
	}
	return imgArray;
};

AdTaily.Widget.prototype.solveDimensions = function() {
	AdTaily.Console('solveDimensions');
	var w = document.getElementById(AdTaily.WIDGET_CONTAINER_ID).parentNode.offsetWidth; 
	var IMGWIDTH = this.imageWidth; 
	var MINMARGIN = this.imageMargin; 
	//var N = Math.floor((w - (2*MINMARGIN))/IMGWIDTH);
	var N = Math.floor((w - MINMARGIN)/(IMGWIDTH+MINMARGIN));
	if (AdTaily.isCenterImages === true) {
		if (this.imageCount < N) {
			N = this.imageCount;
		} // fragment robiacy centrowanie przy mniejszej liczbie reklam niz wyliczone kolumny
	}
	var actualMargin = (w - (N*IMGWIDTH))/(N+1);
	
	var t = null;
	t = AdTaily.addCSSRuleWidget('.ADTAILY_WIDGET_D1');
	t.style.paddingRight = actualMargin+"px";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow1 center');
	t.style.width = "100%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow2 center');
	t.style.width = "50%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow3 center');
	t.style.width = "33%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow4 center');
	t.style.width = "25%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow5 center');
	t.style.width = "20%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow6 center');
	t.style.width = "16.6%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow7 center');
	t.style.width = "14.25%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow8 center');
	t.style.width = "12.5%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow9 center');
	t.style.width = "11.1%";
	t = AdTaily.addCSSRuleWidget('.AdTailyWIDGETrow10 center');
	t.style.width = "10%";
	t = AdTaily.addCSSRuleWidget('.ADTAILY_WIDGET_BR');
	t.style.cssText = "clear: both; font-size: 0; height: 0; line-height: 0; float: left;";

	t = AdTaily.addCSSRuleWidget("#AdTailyBuyButton");
	if (w < 200) {
		t.style.cssText = "margin-bottom:29px !important; width: auto !important;";
	} else {
		t.style.cssText = "margin-bottom:5px !important;";
		t.style.width = w - 75 +"px";
	}
	t=null;
	document.getElementById(AdTaily.WIDGET_CONTAINER_ID).className = 'AdTailyWIDGETrow'+N;
	this.recentWidth = w;
	this.width = w;
	if (this.width > this.openWidgetMinWidth) {
        this.openWidgetWidth = this.width;
    }
    else {
        this.openWidgetWidth = this.openWidgetMinWidth;
    }
    
    if (this.width < this.closedWidgetMinWidth) {
        this.width = this.closedWidgetMinWidth;
    }
	AdTaily.Console('solveDimensions end');
};

AdTaily.Widget.prototype.setTitle = function(new_title_text){
    AdTaily.Console("setTitle");
    try {
        if (this.title) {
            if (new_title_text !== undefined && new_title_text.length > 0) {
                this.title.innerHTML = new_title_text;
            }
            else {
                this.body.removeChild(this.title);
            }
        }
    } 
    catch (error) {
        AdTaily.renderErrorMessage("Problem when setting new title  \n" + e);
    }
};

AdTaily.Widget.prototype.showTitle = function(){
    AdTaily.Console("showTitle");
    if (this.title === null && this.titleText && this.titleText.length > 0) {
        this.title = AdTaily.createElement("span");
        this.title.style.cssText = "text-align: left;font-size: 13px; font-weight: normal;font-family: 'Lucida Grande',verdana,arial,helvetica,sans-serif; color: #2f2f2b;position: relative; display: block; height: 18px; overflow: hidden; color: #2f2f2b; margin-top: 10px; margin-left: 10px; margin-bottom: 0;";//float: left;
        var titleTextNode = document.createTextNode(this.titleText);
		this.title.innerHTML = this.titleText;
        this.body.appendChild(this.title);
    }
};

AdTaily.Widget.prototype.init = function(data){
    AdTaily.Console('init');
    try {
        this.data = data;
        if (data.settings && data.settings.backgroundColor !== undefined && data.settings.backgroundColor !== "") {
            this.backgroundColor = data.settings.backgroundColor;
        }
        if (data.settings && data.settings.borderColor !== undefined && data.settings.borderColor !== "") {
            this.borderColor = data.settings.borderColor;
        }
        if (data.texts && data.texts.title) {
            this.setTitle(data.texts.title);
            this.titleText = data.texts.title;
        }
        if (data.settings && data.settings.position && data.settings.position.toUpperCase() == "TOP") {
            this.setTopPosition();
        }
        if (data.texts && data.texts.link_text) {
            this.buyButtonText = data.texts.link_text;
        }
        if (data.texts && data.texts.home_link_title) {
            this.homeTitleLink = data.texts.home_link_title;
        }
        if (data.status !== undefined && data.status.toUpperCase() == "ERROR") {
			AdTaily.Console('error handler');
            this.showErrorMessage();
        }
        if (AdTaily.getUrlHash().toUpperCase() == "ADTAILY_PAID" || AdTaily.getUrlParameter("thankyou").toUpperCase() == "ADTAILY" ) {
            AdTaily.Console('thx');
			this.isShowThankYouMessage = true;
        }
        this.imageCount = data.links.length;
        this.loadingData = false;
    } 
    catch (error) {
        AdTaily.renderErrorMessage(AdTaily.Exceptions.WIDGET_INITIALIZING_ERROR + "\n" + error);
    }
    AdTaily.EmbedTrackingCode(data.tracking_code, data.ua);
    AdTaily.Console('init end');
};

AdTaily.Widget.prototype.loadData = function(url){
    try {
        AdTaily.loadAndAttachScript(this.protocol + this.hostname + this.json_links_path + this.key + ".js");
    } 
    catch (e) {AdTaily.renderErrorMessage(e);}
};

AdTaily.Widget.prototype.showButtons = function(){
    AdTaily.Console("showbuttons");
    if (arguments.length > 0) {
        for (var i = 0; i < arguments.length; i++) {
            if (arguments[i].toUpperCase() == "CANCEL" && !this.cancelButton) {
                this.cancelButton = AdTaily.createElement("a");
                this.cancelButton.appendChild(document.createTextNode("Anuluj"));
                this.cancelButton.href = window.parent.location;
                this.cancelButton.style.cssText = "position: absolute; bottom: 10px; left: 156px; color: #19b000; font-size: 11px; font-family: verdana,arial,helvetica,sans-serif; z-index: 1;";
                var me2 = this;
                this.cancelButton.onclick = function(){
                    me2.closeWidget();
                    return false;
                };
                this.layer.appendChild(this.cancelButton);
            }
            
            if (arguments[i].toUpperCase() == "CLOSE" && !this.closeButton) {
                try {
                    this.closeButton = AdTaily.createElement("span");
                    this.closeButton.type = "button";
                    this.closeButton.title = this.closeButtonText;
                    
                    this.closeButton.style.cssText = "background-attachment: scroll; background-color: transparent; overflow: hidden; padding: 6px; z-index: 1;position: absolute; top: 0; right: 0; border: 0; display: block; cursor: pointer; height: 30px; width: 30px;";
                    this.closeButton.style.background = 'url(' + this.protocol + this.hostname + '/images/close.gif) no-repeat center';
                    var me = this;
                    this.closeButton.onclick = function(){
                        me.closeWidget();
                        if (AdTaily.getUrlHash().toUpperCase() == "ADTAILY_PAID") {
                            AdTaily.setUrlHash("#");
                        }
                    };
                    this.layer.appendChild(this.closeButton);
                } 
                catch (error) {
                    AdTaily.renderErrorMessage("Error when rendering close button"+error);
                }
			}
        }
    }
    else {
        AdTaily.renderErrorMessage("No buttons to render");
    }
};

AdTaily.Widget.prototype.closeWidget = function()
{	AdTaily.Console('closeWidget');
	try
	{
		if (this.closeButton)
		{
			this.layer.removeChild(this.closeButton);
			this.closeButton = null;
		}
		
		if (this.cancelButton)
		{
			this.layer.removeChild(this.cancelButton);
			this.cancelButton = null;
		}
		
		if (this.iframe) 
		{
			this.layer.removeChild(this.iframe);
			this.iframe = null;
		}
		
		if (this.layer) 
		{
			document.body.removeChild(this.layer);
			this.layer = null;
		}
		
		if (this.body)
		{
			this.body.style.visibility = 'visible';
		}
	}
	catch(error)
	{
		AdTaily.renderErrorMessage("Error when closing widget  \n" + e);
	}
};	

AdTaily.Widget.prototype.showErrorMessage = function()
{
	this.error = true;
	var a = document.getElementById(AdTaily.WIDGET_CONTAINER_ID);
	a.innerHTML = "Sorry, Server Side Error Occured! &nbsp;&nbsp;&nbsp;&nbsp; AdTaily.com";
	a.style.cssText = "border: 1px solid black";
	a.style.borderColor = this.borderColor;
	a.style.padding = 5+"px";
	a.style.backgroundColor = this.backgroundColor;
};

AdTaily.Widget.prototype.showThankYouMessage = function()
{	AdTaily.Console('showThankYouMessage');
	if (this.key !== undefined)
	{
		AdTaily.Console('wnetrze');
		var url = this.protocol + this.hostname + "/widget/campaigns/" +  this.key + "/thanks";
		if (this.layer && this.loadingLabel)
		{
			this.layer.removeChild(this.loadingLabel);
		}
		this.loadUrl(url);
	}
	else
	{
		AdTaily.renderErrorMessage("Key is empty!");
	}
};

AdTaily.Widget.prototype.getPosition = function()
{
	AdTaily.Console('getPosition');
	return AdTaily.getCurrentPosition(this.body);
};

AdTaily.Widget.prototype.openWidget = function()
{	
	AdTaily.Console('openWidget');
	try
	{
		if (!this.layer && this.width)
		{
			this.layer = AdTaily.createElement("div");
			this.layer.id = "AdTaily_Widget_Layer";
			this.layer.style.height = this.openWidgetMinHeight + "px";
			this.layer.style.width = this.openWidgetWidth + "px";
			this.layer.style.backgroundColor = this.backgroundColor;
			this.layer.style.borderStyle = 'solid';
			this.layer.style.borderWidth = this.borderSize + "px";
			this.layer.style.borderColor = this.borderColor;
			this.layer.style.overflow = 'hidden';
			this.layer.style.display = 'block';
			this.layer.style.position = 'absolute';
			this.layer.style.zIndex = 99999;
			
			this.loadingLabel = AdTaily.createElement("span");
			this.loadingLabel.style.position = 'absolute';
			
			this.loadingLabel.style.top = this.openWidgetMinHeight/2 + "px";
			this.loadingLabel.style.textAlign = 'center';
			this.loadingLabel.style.width = '100%';
			this.loadingLabel.style.fontFamily = '"Lucida Grande",verdana,arial,helvetica,sans-serif';
			this.loadingLabel.style.fontSize = '12px';
			this.loadingLabel.appendChild(document.createTextNode(this.data.texts.downloading));
			this.layer.appendChild(this.loadingLabel);
			
			this.layer.style.top = this.getPosition().top + "px";
			this.layer.style.left = this.getPosition().left + "px";

			this.body.style.visibility = 'hidden';
			
			this.showButtons("close");
			document.body.appendChild(this.layer);
		}
	}
	catch(error)
	{
		AdTaily.renderErrorMessage("Cannot open widget  \n" + e);
	}
};

AdTaily.Widget.prototype.loadUrl = function(url)
{
	AdTaily.Console("loadUrl");
	try
	{
		if (!this.iframe && !this.cancelButton && !this.closeButton && this.width) 
		{
			this.openWidget();
			this.iframe = AdTaily.createElement("iframe");
			this.iframe.style.height = this.openWidgetMinHeight+"px";
			this.iframe.style.width = this.openWidgetMinWidth +"px";
			this.iframe.frameBorder = '0';
		 	this.iframe.scrolling = "no";
			this.iframe.src = url;
			this.iframe.allowTransparency = "false";
			this.iframe.style.height = '100%';
			this.iframe.style.width = this.openWidgetWidth + "px";
			this.layer.appendChild(this.iframe) ;
			return false;
		}
		else
		{ 
			AdTaily.renderErrorMessage("Iframe still exist!");
		}
	}
	catch(error)
	{
		AdTaily.renderErrorMessage(AdTaily.Exceptions.WIDGET_BUY_FORM_CANNOT_BE_SHOWN+"  \n" + error);
	}
};

AdTaily.Widget.prototype.showFooter = function(){
    AdTaily.Console('showFooter');
    if (this.footerLink === null) {
        this.footerLink = AdTaily.createElement("a");
        var linkText = document.createTextNode("AdTaily.com");
        this.footerLink.href = "http://" + AdTaily.HOST;
        this.footerLink.rel = "nofollow";
        this.footerLink.title = this.homeTitleLink;
		this.footerLink.appendChild(linkText);
        this.footerLink.style.cssText = "display: inline;font-size: 11px; font-family: arial, sans-serif; color: black; text-decoration: none; padding: 4px; opacity: 0.4; position: absolute; right: 10px; bottom: 6px;";
		this.footerLink.style.filter = 'alpha(opacity=40)';
		this.footerLink.onmouseover = function(){
            this.style.textDecoration = 'underline';
        };
        this.footerLink.onmouseout = function(){
            this.style.textDecoration = 'none';
        };
        this.body.appendChild(this.footerLink);
        if (this.width < this.openWidgetMinWidth - this.footerLink.offsetWidth) {
            this.buyButton.style.marginBottom = '29px';
            this.buyButton.style.width = this.width - 8 - 2 * this.imageMargin + "px";
        }
    }
};

AdTaily.Widget.prototype.showBuyButton = function()
{ 	AdTaily.Console('showbuybutton');
  	if (this.buyButton === null && this.buyButtonText && this.buyButtonText.length > 0 && this.key !== undefined)
	{
		this.buyButton = AdTaily.createElement("a");
		this.buyButton.id = "AdTailyBuyButton";
		this.buyButton.style.cssText = "text-align: left;display: block;  padding: 8px 6px 6px 3px; font-size: 13px; font-weight: normal; overflow: hidden; font-family:'Lucida Grande',verdana,arial,helvetica,sans-serif";
		this.buyButton.style.marginTop = 0;
		this.buyButton.style.marginLeft = 8+"px";
		this.buyButton.style.marginRight = 8+"px";
		this.buyButton.style.marginBottom = 5+"px";
		this.buyButton.style.width = this.width - 8 - 2*this.imageMargin - 75 + "px";
		var me = this;
		var url = this.protocol + this.hostname + this.new_campaign_path + "?key=" + this.key + "&url=" + this.url;
        this.buyButton.onclick = function(){
            me.loadUrl(url);
            return false;
        };
		this.buyButton.href = url;
		this.buyButton.innerHTML = this.buyButtonText;
		this.body.appendChild(this.buyButton);
	}
	else
	{
		AdTaily.renderErrorMessage("Cannot render buy button");
	}
};

AdTaily.Widget.prototype.getVersion = function(){
    return this.version;
};

AdTaily.Widget.prototype.setTopPosition = function()
{	AdTaily.Console('settopposition');
	AdTaily.Console(this.container.id);
	if (this.container && this.container.parentNode)
	{
		var parent = this.container.parentNode;
		if (parent.childNodes[0] && parent.childNodes[0] != this.container)
		{
			parent.insertBefore(this.container, parent.childNodes[0]);
		}
	}
};

AdTaily.EmbedTrackingCode = function(tracking_code, ua){
    try {
        var locationUrl = window.location.toString().replace(/#.*$/, '').replace(/\/$/, "");
        var connector = (locationUrl.indexOf("?") >= 0 ? "&" : "?");
        var trackUrl = locationUrl + connector + tracking_code;
        AdTaily.genCookie("__adtaily_ui");
        var url = 'http://tracker.adtaily.com/stats?' +
        'key=' +
        AdTaily.KEY +
        '&ui=' +
        (AdTaily.getCookie('ui') || AdTaily.getCookie("__adtaily_ui")) +
        '&track_url=' +
        encodeURIComponent(trackUrl) +
        '&ua=' +
        ua;
        var frame = document.createElement("iframe");
        frame.src = url;
        frame.style.display = "none";
		var append = function(){
			document.body.appendChild(frame);
		};
		setTimeout(append,1);
    } 
    catch (e) {
        AdTaily.renderErrorMessage("Error embeding tracking code\n" + e);
    }
};

AdTaily.setCookie = function(c_name,value,expiredays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+
  ((expiredays===null) ? "" : ";expires="+exdate.toGMTString());
};

AdTaily.getCookie = function(c_name)
{
  if (document.cookie.length>0)
    {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1)
      {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end == -1) {
	  	c_end = document.cookie.length;
	  }
      return unescape(document.cookie.substring(c_start,c_end));
      }
    }
  return "";
};

AdTaily.genCookie = function(name) {
  if (AdTaily.getCookie(name) === "" || !AdTaily.getCookie(name).match(/\w{10}/)) {
    var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    var v = "";
    for (var i = 0; i < 10; i++) {
      v += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    AdTaily.setCookie(name, v, 365 + Math.floor(Math.random() * 365));
  }
};

//START
AdTaily.script = document.getElementById(AdTaily.WIDGET_SCRIPT_ID);

if (AdTaily.script)
{	
	AdTaily.KEY = AdTaily.script.getAttribute("key");
	AdTaily.HOST = AdTaily.getHostname(AdTaily.script.getAttribute("src"));

	if (AdTaily.HOST.match(/^static\.adtaily\.\w+/)) {
		AdTaily.HOST = AdTaily.HOST.replace(/^static/, "www");
	} else if (AdTaily.HOST.match(/^static\./)) {
		AdTaily.HOST = AdTaily.HOST.replace(/^static\./, "");
	}
}

if (document.getElementById(AdTaily.WIDGET_CONTAINER_ID) === null)
{
	document.write('<div id="'+AdTaily.WIDGET_CONTAINER_ID +'"></div>');
	AdTaily.css = document.createElement('style');
	AdTaily.css.type = 'text/css';
	AdTaily.css.rel = 'stylesheet';
	AdTaily.css.media = 'screen';
	AdTaily.css.title = 'AdtailyWidgetCSS';
	document.getElementsByTagName("head")[0].appendChild(AdTaily.css);
	AdTaily.start();
}
else
{
	document.write(AdTaily.showDuplicateWidgetError());
}
//end