/*

  AdSense class

  Copyright (C) 2009 by DevWorx, Hungary


*/

var adsense_handler_unit;
var adsense_ads_to_skip = 0;
var adsense_units = new Array();
var adsense_ad_client = '';
var adsense_language = '';
var adsense_encoding = '';
var adsense_hook_installed = false;

function google_ad_request_done_instance(adsense_handler_id, google_ads)
{
  var adsense_handler_unit = false;
  for(var i=0;i<adsense_units.length;i++)
    if (adsense_units[i].divid==adsense_handler_id)
      adsense_handler_unit = adsense_units[i];

  if (adsense_handler_unit)
    adsense_handler_unit.processResponse(google_ads);
  else
    throw "No AdSense handler found with id '"+adsense_handler_id+"'!";

  // keep count of ads to skip
  if (google_ads)
  if (google_ads[0].bidtype == "CPC") 
    adsense_ads_to_skip = adsense_ads_to_skip + google_ads.length;

  adsense_handler_unit = null;
}

var AdSenseUnit = Class.create(); 
AdSenseUnit.prototype = {   

  initialize: function(divid, google_ad_type, google_image_size, google_max_num_ads, google_ad_channel) {   

    this.divid = divid;
    this.google_ad_client = adsense_ad_client;
    this.google_ad_channel = google_ad_channel;
    this.google_ad_type = google_ad_type;
    this.google_image_size = google_image_size;
    this.google_max_num_ads = google_max_num_ads;
    this.google_feedback = 'on';

    adsense_units[adsense_units.length] = this;

//    var obj = this;
//    setTimeout(function () { obj.sendRequest();} , 2000);
    this.sendRequest();
  },

  isDebug: function() {
    return false;
  },

  decodeURL: function(url) {
//    return decodeURI(url);
    if (url==undefined) return '';

    return url.replace( 
      /&(amp|[lg]t|quot);/g, 
      function(m, p1) 
      { 
        var map = { 
          amp:  "&", 
          lt:   "<", 
          gt:   ">", 
          quot: '"' 
        }; 


        return map[p1]; 
      }); 

  },

  getDiv: function() {
    var div = document.getElementById(this.divid);
    if (!div)
      throw "AdSense unit host '"+this.divid+"' not found";
    return div;
  },

  createElement: function(tagName, attrs, subElements) {

    if (attrs)
    {
      var attrNames = new Array(attrs.length);
      var attrValues = new Array(attrs.length);
      for (var i=0;i<attrs.length;i++)
      {
  	var s = attrs[i];
          var p = s.indexOf('='); if (p==0) p = s.length;
          var attrName = s.substr(0,p); var attrValue = s.substr(p+1);

          if (attrName=='class')
            if (document.all)
              attrName = 'className'; // IE needs 'className' instead of 'class'
               
  	attrNames[i] = attrName;
          attrValues[i] = attrValue;
      }
    }

    var element = document.createElement(tagName); 

    if (attrs)
    for (var i=0;i<attrs.length;i++)
    {
        if (attrNames[i].substr(0,2)=='on')
          eval('element.'+attrNames[i]+' = new Function(\''+attrValues[i].replace(/\'/g,'\\\'')+'\')'); 
        else
          element.setAttribute(attrNames[i],attrValues[i]);
    }

    if (subElements)
    for (var i=0;i<subElements.length;i++)
      element.appendChild(subElements[i]);

    return element;
  },

  createText: function(s) {
//    var node = document.createTextNode(s); - not good, won't decode named entities
    var node = document.createElement("span");
    node.innerHTML = String(s);
    return node;
  },

  addElement: function(element) {
    this.getDiv().appendChild(element);
  },

  getOuterHTML: function(element) {
    if (element.outerHTML)
	return element.outerHTML;
    else
	{
    	  var e = document.createElement('span'); 
	  e.appendChild(element.cloneNode(true));
          return e.innerHTML;
	}
  },

  sendRequest: function() {

    var crlf = String.fromCharCode(13)+String.fromCharCode(10);
    var scripttext =
    	'google_ad_client = \''+this.google_ad_client+'\';'+crlf+
    	'google_ad_output = \'js\';'+crlf+
    	'google_ad_type = \''+this.google_ad_type+'\';'+crlf+
    	'google_image_size = \''+this.google_image_size+'\';'+crlf+
    	'google_max_num_ads = '+this.google_max_num_ads+';'+crlf+
	'google_skip = '+adsense_ads_to_skip+';'+crlf+
//    	'google_feedback = this.google_feedback;'+crlf+
	crlf+
	'function google_ad_request_done(google_ads)'+crlf+
	'{'+crlf+
	'	google_ad_request_done_instance(\''+this.divid+'\', google_ads);'+crlf+
	'}'+crlf+
	'';

    if (this.google_ad_channel)
	scripttext = scripttext + 
    	'google_ad_channel = \''+this.google_ad_channel+'\';';

    if (adsense_language) 
	scripttext = scripttext + 
	'google_language = \''+adsense_language+'\';';

    if (adsense_encoding) 
	scripttext = scripttext + 
	'google_encoding = \''+adsense_encoding+'\';';

    if (this.isDebug())
	scripttext = scripttext + 
      	'google_adtest = \'on\';';

    var js1 = document.createElement('script');
    js1.setAttribute("language","JavaScript");
    js1.setAttribute("type","text/javascript");
    if (js1.canHaveChildren)
	js1.appendChild(document.createTextNode(scripttext));
    else
	js1.text = scripttext;

    var js = document.createElement('script');
    js.setAttribute("id",this.divid+'_script');
    js.setAttribute("language","JavaScript");
    js.setAttribute("type","text/javascript");
    js.setAttribute("src", "http://pagead2.googlesyndication.com/pagead/show_ads.js");
    adsense_handler_unit = this;

    var node = this.getDiv();
    node = document.getElementsByTagName('head')[0];

//    node.appendChild(js1); node.appendChild(js); - this makes Firefox miss multiple instances, and Chrome to clear document
    document.write(this.getOuterHTML(js1)); document.write(this.getOuterHTML(js));
  },

  scriptLoadCallback: function(callback) {
    var target = window.event.srcElement;
    if(target.readyState == "loaded")
      callback();
  },

  processResponse: function(google_ads) {

    if (google_ads.length==0) return false;  

    var ad = google_ads[0];

/*
    // test flash ad
    ad = {
	type: 'flash',
	image_width: 336,
	image_height: 280,
	image_url: 'http://192.168.2.100:12345/proghu/common/adsense.swf',
	dummy: 0
    };

    // test html ad
    ad = {
	type: 'html',
	snippet: '<a href="#">Hello world!</a>'
    };
*/

    switch(ad.type)
    {
      case 'text':
        this.renderTextUnit(google_ads);
        break;
      case 'image':
        this.renderImageUnit(ad);
        break;
      case 'html':
        this.renderHtmlUnit(ad);
        break;
      case 'flash':
        this.renderFlashUnit(ad);
        break;
      default:
        throw "Don't know how to handle ad type '"+ad.type+"'";
    }
  },

  renderTextUnit: function(ads) {

     var divs = new Array();
     for (var i=0;i<ads.length;i++) {
       var ad = ads[i];
       divs[divs.length] =
         this.createElement('li',[],
           [
             this.createElement('div',['class=title'],
		[
                  this.createElement('a',
     		    [
     		      'href='+this.decodeURL(ad.url),
     		      'onmouseover=window.status=\'ugrás a következőre: '+ad.visible_url+'\'; return true;',
     		      'onmouseout=window.status=\'\''
     		    ]
     		    ,
     		    [
     		      this.createText(ad.line1)
     		    ]
		  )
                ]
     	     ),
             this.createElement('div',['class=content'],
		[
		  this.createElement('div',[],[this.createText(ad.line2)]),
		  this.createElement('div',[],[this.createText(ad.line3)])
		]
	     ),
             this.createElement('div',['class=link'],
		[
                  this.createElement('a',
     		    [
     		      'href='+this.decodeURL(ad.url),
     		      'onmouseover=window.status=\'ugrás a következőre: '+ad.visible_url+'\'; return true;',
     		      'onmouseout=window.status=\'\''
     		    ]
     		    ,
     		    [
     		      this.createText(ad.visible_url)
     		    ]
		  )
                ]
     	     )
           ]
         );
	if (i<ads.length-1)
	  divs[divs.length] = this.createElement('li',['class=sep']);
     }

     this.addElement(
       this.createElement('div',['class=adunit text'+((ads.length==1) ? ' single' : '')+' groupof'+ads.length],
	[
	  this.createElement('a',['class=feedback','href='+this.decodeURL(google_info.feedback_url)],[this.createText('Google Hirdetések')]),
	  this.createElement('ul',['class=items'],divs)
	]
       )
     );
  },

  renderImageUnit: function(ad) {
     this.addElement(
       this.createElement('div',['class=adunit image'],
         [
           this.createElement('a',['class=feedback','href='+this.decodeURL(google_info.feedback_url)],[this.createText('Google Hirdetések')]),
           this.createElement('a',
              [
                'href='+this.decodeURL(ad.url),
                'target=_top',
                'title=ugrás a következőre: '+ad.visible_url,
                'onmouseout=window.status=\'\'',
                'onmouseover=window.status=\'ugrás a következőre: '+ad.visible_url+'\';return true;'
              ]
              ,
              [
                this.createElement('img',
                  [
                    'border=0',
                    'src='+this.decodeURL(ad.image_url),
                    'width='+ad.image_width,
                    'height='+ad.image_height
                  ]
                )
              ]
           )
         ]
       )
     );
  },

  renderHtmlUnit: function(ad) {

     var html = this.createElement('span');
     html.innerHTML = ad.snippet;

     this.addElement(
       this.createElement('div',['class=adunit html'],[html])
     );
  },
 
  renderFlashUnit: function(ad) {

     var embedElement =
                this.createElement('embed',
		   [
		     'src='+this.decodeURL(ad.image_url),
		     'width='+ad.image_width,
		     'height='+ad.image_height,
		     'type=application/x-shockwave-flash',
               	     'AllowScriptAccess=never',
               	     'pluginspage=http://www.macromedia.com/go/getflashplayer'
		   ]
		);

     this.addElement(embedElement); return;

/*
     if (document.all) 
	embedElement = this.createElement('param',['name=dummy','value=dummy']); 
*/

     this.addElement(
       this.createElement('div',['class=adunit flash'],
         [
           this.createElement('a',['class=feedback','href='+this.decodeURL(google_info.feedback_url)],[this.createText('Google Hirdetések')]),
	   embedElement
/*
           this.createElement('object',
              [
		'width='+ad.image_width,
		'height='+ad.image_height,
                'classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
                'codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0'
              ]
              ,
              [
                this.createElement('param',['name=width','value='+ad.image_width]),
                this.createElement('param',['name=height','value='+ad.image_height]),
                this.createElement('param',['name=quality','value=high']),
                this.createElement('param',['name=allowscriptaccess','value=never']),
                this.createElement('param',['name=movie','value='+this.decodeURL(ad.image_url)]),
		embedElement
              ]
           )
*/
         ]
       )
     );
  },
  
  dummy: function() {
  }

};  


function initAdSense(google_ad_client, google_language, google_encoding)
{
  adsense_ad_client = google_ad_client;
  adsense_language = google_language;
  adsense_encoding = google_encoding;
  adsense_handler_unit = null;
  adsense_ads_to_skip = 0;
}

