var base = 'http://api.adstargeting.com/advtarget/'
var Ym = {
    URLEncode: function(url) {
               var SAFECHARS = "0123456789" +                  // Numeric
                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +  // Alphabetic
                   "abcdefghijklmnopqrstuvwxyz" +
                   "-_.!~*'()";                    // RFC2396 Mark characters
               var HEX = "0123456789ABCDEF";

               var plaintext = url.toString();
               var encoded = "";
               for (var i = 0; i < plaintext.length; i++ ) {
                   var ch = plaintext.charAt(i);
                   if (ch == " ") {
                       encoded += "+";             // x-www-urlencoded, rather than %20
                   } else if (SAFECHARS.indexOf(ch) != -1) {
                       encoded += ch;
                   } else {
                       var charCode = ch.charCodeAt(0);
                       if (charCode > 255) {
                           encoded += "+";
                       } else {
                           encoded += "%";
                           encoded += HEX.charAt((charCode >> 4) & 0xF);
                           encoded += HEX.charAt(charCode & 0xF);
                       }
                   }
               } // for

               return encoded;
    },

    gethex: function(decimal) {
            var hexchars = "0123456789ABCDEFabcdef";
            return "%" + hexchars.charAt(decimal >> 4) + hexchars.charAt(decimal & 0xF);
    },


    Utf8UrlEncode: function(url) {
                   var unreserved = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~";
                   var reserved = "!*'();:@&=+$,/?%#[]";
                   var allowed = unreserved + reserved;
                   // Some variables:
                   var decoded = url;
                   var encoded = "";

                   for (var i = 0; i < decoded.length; i++ ) {
                       var ch = decoded.charAt(i);
                       if (unreserved.indexOf(ch) != -1) {
                           encoded = encoded + ch;
                       } else {
                           var charcode = decoded.charCodeAt(i);
                           if (charcode < 128) {
                               encoded = encoded + this.gethex(charcode);
                           }
                           if (charcode > 127 && charcode < 2048) {
                               encoded = encoded + this.gethex((charcode >> 6) | 0xC0);
                               encoded = encoded + this.gethex((charcode & 0x3F) | 0x80);
                           }

                           if (charcode > 2047 && charcode < 65536) {
                               encoded = encoded + this.gethex((charcode >> 12) | 0xE0);
                               encoded = encoded + this.gethex(((charcode >> 6) & 0x3F) | 0x80);
                               encoded = encoded + this.gethex((charcode & 0x3F) | 0x80);
                           }

                           if (charcode > 65535) {
                               encoded = encoded + this.gethex((charcode >> 18) | 0xF0);
                               encoded = encoded + this.gethex(((charcode >> 12) & 0x3F) | 0x80);
                               encoded = encoded + this.gethex(((charcode >> 6) & 0x3F) | 0x80);
                               encoded = encoded + this.gethex((charcode & 0x3F) | 0x80);
                           }
                       }
                   }  // end of for ...
                   return encoded;
    },

    http_build_query: function(params, path) {
                      var first = 1;
                      var query = "";
                      for(paramName in params) {
                          paramValue = params[paramName];
                          query += (first == 1) ? '' : '&';
                          first = 0;
                          if(typeof path == 'undefined') {
                              var paramPath = this.Utf8UrlEncode(paramName);
                          } else {
                              var paramPath = path+'['+this.Utf8UrlEncode(paramName)+']';
                          }
                          if (typeof paramValue == 'undefined' || paramValue == null) {
                              query += paramPath + '=';     
                          } else if(typeof paramValue == 'object') {
                              query += this.http_build_query(paramValue, paramPath);
                          } else {
                              paramValue = new String(paramValue);
                              query += paramPath+'='+this.Utf8UrlEncode(paramValue);
                          }
                      }
                      return query;
                  },

    queryString: function() {
        hu = window.location.search.substring(1);
        gy = hu.split("&");
        var query = {};
        for (i=0; i<gy.length; i++) {
            ft = gy[i].split("=");
            query[ decodeURIComponent(ft[0]) ] = decodeURIComponent(ft[1]);
        }
        return query;
    },


	init: function() {
			// Begin Overture
        // Ex.: http://www.google.com/search?client=opera&rls=en&q=bush+iraq&sourceid=opera&ie=utf-8&oe=utf-8
        RE_GOOGLE = new RegExp(/google\.\w+\/.*[\?&]q=([^&]+)/i);

        // Ex.: http://it.search.yahoo.com/search?p=bush+iraq+petrolio&fr=yfp-t-501&ei=UTF-8&meta=vl%3D
        RE_YAHOO = new RegExp(/yahoo\.\w+\/.*[\&\?]p=([^&]+)/i);

        // Ex.: http://search.msn.it/results.aspx?q=bush+petrolio+iraq+petrolio.blogosfere.it&FORM=MSNH
        RE_MSN = new RegExp(/search\.(?:msn|live)\.\w+\/.*q=([^&]+)/i);

        // Ex.: http://www.wikio.it/search/petrolio+bush+iraq
        RE_WIKIO = new RegExp(/wikio\.\w+\/search\/([^&]+)/i);

        // var RE_VIRGILIO = new RegExp(/\.alice\.it\/.*qs=([^&]+)/i);
        RE_VIRGILIO = new RegExp(/\.virgilio\.it\/.*qs=([^&]+)/i);

        // Ex: http://arianna.libero.it/search/abin/integrata.cgi?regione=9&query=petrolio%20bush%20iraq
        RE_LIBERO = new RegExp(/arianna\.libero\.it\/.*query=([^&]+)/i);

        // Ex: http://it.ask.com/blogsearch?q=petrolio+bush+iraq&qsrc=2102&o=0&l=dir&bql=any&t=a&s=r
        RE_ASK = new RegExp(/ask\.com\/.*q=([^&]+)/i);

        // Ex: http://oknotizie.alice.it/search.php?s=blogosfere&x=0&y=0
        RE_OKNOTIZIE = new RegExp(/oknotizie\.alice\.it\/.*s=([^&]+)/i);

        // Ex: http://www.liquida.it/metropolitana/
        // var RE_LIQUIDA = new RegExp(/liquida\.it\/([^\/]+)/i);
        RE_LIQUIDA = new RegExp(/liquida\.it\/search\/([^\/]+)/i);

        // Ex: http://www.bing.com/search?q=petrolio+guerra+blogosfere&go=&form=QBRE3&scope=web
        RE_BING = new RegExp(/bing\.com\/.*q=([^&]+)/i);
		
			this.RE_REFERRERS = [
            ['Google', RE_GOOGLE],
            ['Yahoo', RE_YAHOO],
            ['MSN', RE_MSN],
            ['Wikio', RE_WIKIO],
            ['Virgilio', RE_VIRGILIO],
            ['Libero', RE_LIBERO],
            ['Ask', RE_ASK],
            ['OKNOtizie', RE_OKNOTIZIE],
            ['Liquida', RE_LIQUIDA],
            ['Bing', RE_BING]
                ];
	},

	get_referrer_info: function(referrer) {
        //  Disable the referrer welcome message
        //  return null;

        var ref_match = null, cur_ref_re = null;
        var referrers_to_check = this.RE_REFERRERS.slice();

        while (cur_ref_re = referrers_to_check.pop()) {
            ref_match = cur_ref_re[1].exec(referrer);

            // Returns the referrer's name (title) and the searched terms
            if (ref_match) return [cur_ref_re[0], unescape(ref_match[1]).replace('-', ' ')];
        }

        return null;
    },


    start: function() {
			this.init();
            var setup = ym_setup;
            setup.ts = '1327729431';
            setup.kw = typeof this.queryString().kw != 'undefined' ? this.queryString().kw : '';
			setup.title = typeof document.title != 'undefined' ? document.title : '';
			setup.keywords = '';
			setup.description = '';
			var metas = document.getElementsByTagName('meta');


			var referrer_info = this.get_referrer_info(document.referrer);
			if (referrer_info) {
				setup.kwSearched = referrer_info[1];
			}
			else {
				setup.kwSearched = '';
			}


			for(i=0; i < metas.length; i++) {
				if(typeof metas[i].name != 'undefined' && metas[i].name.toLowerCase() == "keywords") {
					setup.keywords = metas[i].content;
				}
				if(typeof metas[i].name != 'undefined' && metas[i].name.toLowerCase() == "description") {
					setup.description = metas[i].content;
				}
				
			}
			setup.rnd = Math.random();

            var html = unescape("%3Ciframe src='"+base+"res_slot.js?") +this.http_build_query(setup)+ unescape("' width='"+setup.ym_slot_width+"' height='"+setup.ym_slot_height+"' frameborder='0' allowtransparency='true' scrolling='no'%3E%3C/iframe%3E");
            var prev;
            if(prev = document.getElementById('ym_preview')) {
                prev.innerHTML = html;
            }
            else {

                var img_path = 'images/loader/';
                if(setup.ym_slot_id == 138 || setup.ym_slot_id == 140 || setup.ym_slot_id == 142 || setup.ym_slot_id == 41) {
                    var img_path = 'images/loader/it/';
                }

                if(setup.ym_slot_market != undefined) {
                    var img_path = 'images/loader/' + setup.ym_slot_market + '/';
                }
                
            var b = document.getElementsByTagName('script');
            var b = b[b.length - 1];
            var a = document.createElement('ins');
            a.id = 'ym_anchor_' + setup.ym_slot_id;
            a.setAttribute('style',  'background:url(\''+base+ img_path +setup.ym_slot_width+'x'+setup.ym_slot_height+'.gif\');display:inline-table;border:none;margin:0;padding:0;position:relative;visibility:visible;height:'+setup.ym_slot_height+'px;margin:0;padding:0;width:'+setup.ym_slot_width+'px');
            b.parentNode.insertBefore(a,b);

         var el = document.createElement("script");
         el.type = 'text/javascript';
         el.async = true;
		 el.setAttribute('src', base + 'res_slot.js?checkStatus=' + setup.ym_slot_id + '&' + Ym.http_build_query(setup) + '&location=' + escape(document.location));
		 /*el.setAttribute('width', setup.ym_slot_width);
		 el.setAttribute('height', setup.ym_slot_height);
		 el.setAttribute('frameborder', '0');
		 el.setAttribute('allowtransparency', 'true');
		 el.setAttribute('scrolling', 'no');*/
         var b = document.getElementById("ym_anchor_"+setup.ym_slot_id);
         b.parentNode.insertBefore(el,b);
            }
    }
}

Ym.start();

