/**
 * Clase para manejo de ADSENSE
 * 2008/11/6 17:01:05 [Pablo Dominguez]
 */
Adsense = function(){
	this.query 		= '';
	this.client 	= 'pub-0159970609929852';
	this.channel 	= '9413860958';
	this.testMode 	= 'off';
	this.inEncode	= 'utf8';
	this.outEncode	= 'utf8';
	this.langAds	= 'it';
	this.country	= 'it';
	this.totalAds	= '';
	this.numAdsShow	= 0;
	this.locations	= [];
	this.data		= [];
	this.modeSearch = 'url'; //Crea el query segun la URL o el DIV de ANUNCIO
}

/**
 * Setea las variables como un string que luego se imprimen porque google en la llamada
 * a la funcion google_afs_request_done las necesita evaluadas..
 */
Adsense.prototype.addBanner = function( numAds, location ){
	this.totalAds += numAds;
	this.numAdsShow = numAds;
	this.locations.push( location );
}

/**
 * Arma el query de busqueda segun la etiqueta html que se le indique
 * @param id [opcional] Si se setea un ID, se realiza la busqueda por el INNERHTML del ID.
 */
Adsense.prototype.buildQuery = function( id ){
	var id = id || 'anuncio';
	var st = '';
	if( this.modeSearch == 'url' ){
		var	re = new RegExp((("https:" == location.protocol) ? "https://" : "http://") + location.host + '/');
		var st = location.href.replace(re, '');
			st = st.replace(new RegExp("[0-9\.]","g"),"");
			st = st.replace(new RegExp("-html","g"),"");
			st = st.replace(new RegExp("[/]","g"),"+");
			st = st.replace(new RegExp("[-]","g")," ");
	}

	if (st==null || st==''){
		st = document.getElementById( id ).innerHTML;
		st = st.replace(new RegExp("<a.*[^>]+>.*</a>"),"");
		st = st.replace(new RegExp("[0-9\.]","g"),"");
		st = st.replace(new RegExp("<\/?[^>]+>","g"),"");
		st = st.replace(/^\s+/, "").replace(/\s+$/, "");
	}
	return st.toLowerCase();
}

/**
 * Divide el this.data en partes segun la cantidad
 */
Adsense.prototype.chunk = function( size ){
	for(var x, i = 0, c = -1, l = this.data.length, n = []; i < l; i++){
    	(x = i % size) ? n[c][x] = this.data[i] : n[++c] = [this.data[i]];
    }
    this.data = n;
}

/**
 * Asigna el innerHTML de los objetos que lo llaman
 */
Adsense.prototype.render = function(){
	// Verifica que existan Ads para mostrar
	var dataLength = this.data.length;
	var locationLength = this.locations.length;
	// Solo si existen impresiones y valores para el ad
	if(dataLength > 0 && locationLength > 0) {
		// Separa los datos segun la cantidad de ads por banner
		this.chunk( this.numAdsShow );
		//Para cada lugar donde se imprimen los datos
		for(i in this.locations){
			if(typeof this.data[i] != 'undefined'){
				// Inicio de la tabla contenedora con el encabezado
				wideAds = '<table align="left" class="sponsoredTable" cellpadding="0" cellspacing="0" width="735px">' +
				'<tr class="sponsored">' +
				'<td class="sponsored" style="border-bottom: 1px solid #336699;border-top: 1px solid #336699;">' +
				'<a href="http://services.google.com/feedback/online_hws_feedback">Ads by Google</a>' +
				'</td>' +
				'</tr>' +
				// Contenido de anuncios
				this.data[i].join("\n") +
				// Cierre de la tabla contenedora
				'</table>';

				//Imprime y asigna el add al objeto guardado
				document.getElementById(this.locations[i]).innerHTML = wideAds;
			}
		}
	}
	return;
}

/**
 * Se inicializa el objeto para tenerlo como global y disponible en todo el contexto
 */
if(!AdsGoogle){
	var AdsGoogle = new Adsense();
}

/**
 * Esta función es obligatoria: procesa el google_ads objeto JavaScript,
 * que contiene anuncios de AFS relevantes para la consulta de búsqueda del usuario. El nombre de
 * esta función <i>debe</i> ser <b>google_afs_request_done</b>. Si no se nombra correctamente
 * esta función, no mostrarán anuncios de AFS.
 */
function google_afs_request_done(google_ads){
	// Verifica que existan Ads para mostrar
	var google_num_ads = google_ads.length;
	if(google_num_ads <= 0) {
		return;
	}
	// Offset de datos válidos
	var a = 0;
	// Recorre los resultados para guardar los datos en la clase
	for(i = 0; i < google_num_ads; i++)	{
		if(google_ads[i].type=="text/wide") {
			// Contenedor START {
			wideAds = '<tr class=\'sponsored\'>';
			wideAds+= '<td class=\'sponsored\' style="border-bottom: 1px solid #336699;">';
			wideAds+= '<p>';
			// Titulo
			wideAds+= '<a style="text-decoration:underline" ';
			wideAds+= 'onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ';
			wideAds+= 'onmouseout="javascript:window.status=\'\';return true;" ';
			wideAds+= 'href="' + google_ads[i].url + '">';
			wideAds+= '<span class="title">' + google_ads[i].line1 + '</span>';
			wideAds+= '</a><br><span class=\'negro\'>';
			// Descripcion
			wideAds+= google_ads[i].line2 + ' - ';
			// Url
			wideAds+= '</span><a style="text-decoration:none" ';
			wideAds+= 'onmouseover="javascript:window.status=\'';
			wideAds+= google_ads[i].url + '\';return true;" ';
			wideAds+= 'onmouseout="javascript:window.status=\'\';return true;" ';
			wideAds+= 'href="' + google_ads[i].url + '">';
			wideAds+= '<span class="url">' + google_ads[i].visible_url + '</span></a>';
			// } Contenedor FIN
			wideAds+= '</p>';
			wideAds+= '</td>';
			wideAds+= '</tr>';

			//Guarda los datos en el obj AdsGoogle
			AdsGoogle.data.push(wideAds);
		}
	}
	// Imprime los resultados en los objetos guardados
	AdsGoogle.render();
}
