var NokautPP = {
	unique_id  : 0,

	ad_format  : "468x60",
	ad_type    : "popular",
	ad_content : 0,
	ad_partner : 0,
	ad_channel : 0,
	ad_photo   : 1,
	ad_mode	   : '',

	color_border  : "#adabab",
	color_product : "#5272AC",
	color_price   : "#CF1E24",
	color_offers  : "#666666",
	date_start: 0,
    tmp_div_id : "",

	init: function() {

		this.date_start = new Date().getTime();

		if (this.isDefinedVariable("nokaut_ad_format")) {
			switch (nokaut_ad_format) {
				case "750x150":
				case "600x150":
				case "468x60":
				case "300x250":
				case "160x600":
				case "160x320":
				case "120x600":
					this.ad_format = nokaut_ad_format;
					break;
			}
		}
	    if (this.isDefinedVariable("nokaut_ad_type")) {
			switch (nokaut_ad_type) {
				case "context":
				case "category":
				case "product":
				case "popular":
					this.ad_type = nokaut_ad_type;
					break;
			}
		}
		if (this.isDefinedVariable("nokaut_ad_content")) {
			this.ad_content = nokaut_ad_content;
		}
		if (this.isDefinedVariable("nokaut_ad_mode")) {
			this.ad_mode = nokaut_ad_mode;
		}
		if (this.isDefinedVariable("nokaut_ad_partner")) {
			this.ad_partner = nokaut_ad_partner;
		}
		if (this.isDefinedVariable("nokaut_ad_channel")) {
			this.ad_channel = nokaut_ad_channel;
		}
		if (this.isDefinedVariable("nokaut_ad_photo")) {
			switch (nokaut_ad_photo) {
				case "1":
				case "true":
				case "yes":
				case "tak":
					this.ad_photo = 1;
					break;
				case "0":
				case "false":
				case "no":
				case "nie":
					this.ad_photo = 0;
					break;
			}
		}
		if (this.isDefinedVariable("nokaut_color_border")) {
			//this.color_border = nokaut_color_border;
		}
		if (this.isDefinedVariable("nokaut_color_product")) {
			//this.color_product = nokaut_color_product;
		}
		if (this.isDefinedVariable("nokaut_color_price")) {
			//this.color_price = nokaut_color_price;
		}
		if (this.isDefinedVariable("nokaut_color_offers")) {
			//this.color_offers = nokaut_color_offers;
		}

        this.tmp_div_id = "NokautAdsResultContainer";

		// xgenerate unique id for container
        this.generateUniqueId();

		// render content
        if (this.unique_id > 0) {
           this.render();
        }
	},

	clickTracker: function() {
		if(typeof(NokautPageTracker) ==  "object") {
			var time_to_click = (new Date().getTime() - this.date_start) / 1000;
			var ad_id = 'widget_'+this.ad_format+'_'+this.ad_type;
			NokautPageTracker._trackEvent('Formy reklamowe PP', ad_id, String(this.ad_partner), parseInt(time_to_click, 10));
		}
	},

	generateUniqueId: function() {
	    var MAX_ROTATED_ADS = 20;
	    this.unique_id = parseInt(Math.random() * MAX_ROTATED_ADS + 1);
        if (MAX_ROTATED_ADS == NokautGeneratedFormsCounter) {
            this.unique_id = 0;

            var div = document.getElementById(this.tmp_div_id);
            if ('undefined' != typeof div) {
                div.parentNode.removeChild(div);
            }
            return;
        } else if (NokautGeneratedForms[String(this.ad_type)+"|"+this.ad_format+"|"+this.unique_id]) {
	        this.generateUniqueId();
	        return;
	    }

	    NokautGeneratedForms[String(this.ad_type)+"|"+this.ad_format+"|"+this.unique_id] = this;
        NokautGeneratedFormsCounter++;
	},

	renderGaScripts: function() {

		var script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", "http://www.google-analytics.com/ga.js");
        script.setAttribute("charset", "utf-8");
        script.setAttribute('onload', 'NokautPageTracker = _gat._getTracker("UA-15841605-1"); NokautPageTracker._trackPageview("/partner/"+NokautPP.ad_partner+"/"+window.location.hostname+window.location.pathname+"/widget_"+NokautPP.ad_format+"_"+NokautPP.ad_type);');
		var head = document.getElementsByTagName('head')[0];
		head.appendChild(script);
	},

	render: function() {
        var id = "nokaut_ads_" + this.ad_type + "_"+ this.ad_format + "_" + this.unique_id + "_result";

        //var divs = document.getElementsByClassName(this.tmp_div_id);
        var div = document.getElementById(this.tmp_div_id);
		//alert(div);

        // stara wersja
        if (null == div || 0 == div) {
            // render widget box; was changed cause of conflict with Facebook Connect codes
            document.write("<div class=\"NokautWidget"+this.ad_format+"\" id=\""+id+"_container\" style=\"border-color: "+this.color_border+"\"></div>");
            div = document.getElementById(id+'_container');

            // render widget ci
            var ci = document.createElement("div");
            ci.className = "NokautWidgetCI";

            div.appendChild(ci);

            var a = document.createElement("a");
            a.setAttribute("href", "http://www.nokaut.pl#pid=" + this.ad_partner + "&cid=" + this.ad_channel);
            a.setAttribute("title", "nokaut.pl porownywarka cen");
            a.setAttribute("onclick", "NokautPP.clickTracker();");

            ci.appendChild(a);

            var span1 = document.createElement("span");
            var span2 = document.createElement("span");
            var span3 = document.createElement("span");

            span1.className = "NokautWidgetCILogo1";
            span2.className = "NokautWidgetCILogo2";
            span3.className = "NokautWidgetCISlogan";

            a.appendChild(span1);
            a.appendChild(span2);
            a.appendChild(span3);

            span1.innerHTML = "nokaut";
            span2.innerHTML = ".pl";
            span3.innerHTML = "&nbsp;por&#243;wnywarka cen";
        }

		var time_to_click = this.date_start - new Date().getTime();
		// render js for google analitics
		this.renderGaScripts();
		// render linked styles
		this.renderLinkedStyles();
		// render inline styles
		this.renderInlineStyles(id);

		// render widget content
		var ul = document.createElement("ul");
		ul.setAttribute("id", id);
		ul.className = "NokautWidgetProductsList";

		div.appendChild(ul);

		var url = "http://"+ this.getCurrentDomain() +"/pp/nokaut.php";
		url += "?partner=" + this.ad_partner;
		url += "&channel=" + this.ad_channel;
		url += "&unique="  + this.unique_id;
		url += "&photo="   + this.ad_photo;
		url += "&type="    + this.ad_type;
		url += "&format="  + this.ad_format;
		url += "&mode="    + this.ad_mode;
        

		if (this.ad_type == "context") {
			url += "&content=" + this.encode(this.getContext());
		} else {
			url += "&content=" + this.ad_content;
		}

		var script = document.createElement("script");
		script.setAttribute("language", "javascript");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", url);
        script.setAttribute("charset", "utf-8");

        ul.appendChild(script);
		div.className = 'NokautWidget'+this.ad_format;
		div.id = id+'_container';
	},

	getPageEncoding: function() {

	},

	renderLinkedStyles: function() {
		var href = "http://css.nokaut.pl/pp/NokautWidget" + this.ad_format + ".css?ver=1.2";
        
		try { //IE
			var link = document.createStyleSheet(href);
		} catch (e) { //W3C
			var link = document.createElement("LINK");
			link.setAttribute("href", href);
			link.setAttribute("rel", "stylesheet");
			link.setAttribute("type", "text/css");
			link.setAttribute("charset", "utf-8");

			var head = document.getElementsByTagName('head')[0];
			head.appendChild(link);
		}
	},

	getCurrentDomain: function() {
		try {
			if (document.location.host.indexOf('widget.') != -1) {
				return document.location.host;
			} else {
				return 'widget.nokaut.pl';
			}
		} catch (e) {
			return 'widget.nokaut.pl';
		}
	},

	renderInlineStyles: function(id) {
		var styles = "<!--\n";
		styles += ".NokautWidget" + this.ad_format + " #" + id + " li a.NokautProductName {\n";
		styles += "color: " + this.color_product + ";\n";
		styles += "}\n";
		styles += ".NokautWidget" + this.ad_format + " #" + id + " li a.NokautProductPrice {\n";
		styles += "color: " + this.color_price + ";\n";
		styles += "}\n";
		styles += ".NokautWidget" + this.ad_format + " #" + id + " li a.NokautProductOffers {\n";
		styles += "color: " + this.color_offers + ";\n";
		styles += "}\n";
		styles += "-->\n";

		try { //IE
			var style = window.document.createStyleSheet();
			style.cssText = styles;
		} catch (e) { //w3c
			var style = document.createElement("style");
			style.setAttribute("type", "text/css");
			style.appendChild(document.createTextNode(styles));

			var head = document.getElementsByTagName('head')[0];
			head.appendChild(style);
		}
	},

	isDefinedVariable: function(variable) {
        return (typeof(window[variable]) == "undefined") ? false : true;
    },

    getContext: function() {
        var content = '';

    	var titles = document.getElementsByTagName('title');
        var title  = titles[0].innerHTML;

        content += title;

        var metas = document.getElementsByTagName('meta');

        for (var i = 0; i < metas.length; i++) {
        	switch (metas[i].getAttribute('name')) {
        		case 'description':
        			content += ' ' + metas[i].getAttribute('content');
        			break;
        		case 'nokaut_ad_keywords':
        			return metas[i].getAttribute('content');
        			break;
        	}
        }

        return content;
    },

    encode: function (string) {
    	string = string.replace(/\r\n/g, " ");

    	var utftext = "";

    	for (var n = 0; n < string.length; n++) {
    		var c = string.charCodeAt(n);

    		if (c < 128) {
    			utftext += String.fromCharCode(c);
    		} else if((c > 127) && (c < 2048)) {
    			utftext += String.fromCharCode((c >> 6) | 192);
    			utftext += String.fromCharCode((c & 63) | 128);
    		} else {
    			utftext += String.fromCharCode((c >> 12) | 224);
    			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
    			utftext += String.fromCharCode((c & 63) | 128);
    		}
    	}

    	return utftext;
    }
}

var NokautGeneratedForms = NokautGeneratedForms || {};
var NokautGeneratedFormsCounter = NokautGeneratedFormsCounter || 0;

NokautPP.init();
