/* 
  Copyright 2004 - Certifica.com 
  Version 07-2009
  $Id$
*/

DEFAULT_PIVOT_NAME = 'cert_Pivot';
DEFAULT_REDIRECT_TIME = 3000;
DEFAULT_PERIODIC_REDIRECT_TIME = 60000;
DEFAULT_ORIGIN_COOKIE_NAME = 'cert_Origin';

var cert_CustomCounters = null;
var cert_CustomAttributes = null;


function cert_normalizePath(sPath, sPrefix)
{
    var sProtocol = cert_getProtocol();
    var sRet = 'home/default';
    var regexSlashes = /\/\/+/g;
    var regexInvalid = /[^A-Z0-9_.\/]/gi;
    var aDefaultPages = [
		'index.htm', 'index.html', 'index.asp', 'index.php', 
		'index.cfm', 'index.shtml', 'index.jsp', 'default.asp', 
		'default.html', 'default.htm', 'default.jsp', 'default.php'
    ];

    sPath = unescape(sPath);
    if (sPath && sPath.length > 0 &&
        (sProtocol == 'http:' || sProtocol == 'https:')) { 
        sPath = sPath.replace(regexInvalid, '');
        // Si es un directorio, se agrega una pagina por defecto
        if (sPath.charAt(sPath.length - 1) == '/') {
            sPath += aDefaultPages[0];
        }
        sPath = sPath.replace(regexSlashes, '/');

        var aParts = sPath.split('/');
        var aElems = new Array();
        for (var i = 0; i < aParts.length; i++) {
            if (aParts[i] && aParts[i] != '') {
                aElems.push(aParts[i]);
            }
        }

        if (aElems.length == 0) {
            aElems.push('home');
            aElems.push('default');
        }

        if (aElems.length == 1) {
            aElems.unshift('home');
        }
        
        for (var i = 0; i < aDefaultPages.length; i++) {
            if (aElems[aElems.length - 1] == aDefaultPages[i]) {
                aElems[aElems.length - 1] = 'default';
                break;
            }
        }
        
        // Si viene el prefijo, lo uso.
        if (sPrefix) {
            sRet = sPrefix + '/' + aElems[aElems.length -1];
        } else {
            sRet = aElems.join('/');
        }
        
    }
    return sRet;
}

function cert_qVal(sValue) 
{
    var pos = String(document.location).indexOf('?');
    if (pos != -1) {
       var query = String(document.location).substring(pos+1);
       var vars = query.split("&");
       for (var i=0; i < vars.length; i++) {
          var pair = vars[i].split("=");
          if (pair[0] == sValue)
             return pair[1];
       }       
    }
    return null;  
}

function cert_getCookie(sName) {
  var dc = document.cookie;
  var prefix = sName + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function cert_setCookie(sName, sValue, dtExpires, sPath, sDomain, bSecure) {
  document.cookie = sName + "=" + escape(sValue) +
      ((dtExpires) ? "; expires=" + dtExpires.toGMTString() : "") +
      ((sPath) ? "; path=" + sPath : "") +
      ((sDomain) ? "; domain=" + sDomain : "") +
      ((bSecure) ? "; secure" : "");
}

function cert_getReferrer()
{
   var referrer = document.referrer;
   if (self.cert_getReferrer14)
      return cert_getReferrer14();
/*@cc_on
  @if(@_jscript_version >= 5 )
   try { 
      if ( self != top ) referrer = top.document.referrer;
   } catch(e) {};
  @end
  @*/
  return referrer;
}

/* Obtiene el tipo de protocolo del documento actual. */
function cert_getProtocol()
{
    if (window && window.location && window.location.protocol)
        return window.location.protocol;
    return null;
}
 
/* Crea una cookie con el contenido del referrer para evaluarlo
  en el paso final, si es necesario. */
function cert_setOrigin()
{
	var c = cert_getCookie(DEFAULT_ORIGIN_COOKIE_NAME);
	if (!c) {
		var l = cert_getReferrer();
		if (l) {
			var re = new RegExp('https?:\/\/([^\/]+)');
			var m = re.exec(l);
			if (m) {
				var m2 = re.exec(document.location);
				if (m2) {
					if (m[1] != m2[1]) {
						c = m[1];
					}
				}
			}
		}
		if (!c) {
			c = 'directo';
		}
		cert_setCookie(DEFAULT_ORIGIN_COOKIE_NAME, c);
	} 
}

function cert_getFlashVersion()
{
	var flashVersion = -1;
	if (navigator.plugins && navigator.plugins.length) {
		var objFlash = navigator.plugins["Shockwave Flash"];
		if (objFlash) {
			if (objFlash.description) {
				flashDesc = objFlash.description;
				flashVersion = flashDesc.charAt(flashDesc.indexOf('.')-1);
			}
		}

		if (navigator.plugins["Shockwave Flash 2.0"]) {
			flashVersion = 2;
		}
	} else if (navigator.mimeTypes && navigator.mimeTypes.length) {
		x = navigator.mimeTypes['application/x-shockwave-flash'];
		if (x && x.enabledPlugin) {
			flashVersion = 0; // no detectada!
		}
	}

	/*@cc_on
	for(var i = 10; i > 0; i--) {
		try {
			var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
			flashVersion = i;
			break;
		} catch(e){}
	}	
	@*/
	return flashVersion;
}

/* Crea la URL para obtener un pageview de Certifica. */
/* Sólo necesita los parámetros iSiteId y sPath       */
function cert_getURL(iSiteId, sPath, sAppend) 
{
    var size, colors, referrer, url;
    size = colors = referrer = 'otro';
    var o = cert_qVal('url_origen');
    var proto = cert_getProtocol();
    if (proto != 'https:')
        proto = 'http:';
    
    if (o != null && o != '')
       referrer = o;
    else 
       referrer = escape(cert_getReferrer());
    if ( window.screen.width ) size = window.screen.width;
    if ( window.screen.colorDepth ) colors = window.screen.colorDepth;
    else if ( window.screen.pixelDepth ) colors = window.screen.pixelDepth;
    url = 
       proto + '//hits.e.cl/cert/hit.dll?sitio_id=' + iSiteId + '&path=' + sPath +
       '&referer=' + referrer + '&size=' + size + '&colors=' + colors;
    url += '&java=' + navigator.javaEnabled() + '&flash=' + cert_getFlashVersion();
    if (sAppend)
        url += sAppend;
    return url;    
}

function cert_addCustomAttribute(sType, sValue)
{
	if (!cert_CustomAttributes) {
		cert_CustomAttributes = new Object();
	}

	cert_CustomAttributes[sType] = sValue;
}

function cert_addCustomCounter(sType, iValue)
{
	if (iValue && iValue > 0) {
		if (!cert_CustomCounters) {
			cert_CustomCounters = new Object();
		}

		if (cert_CustomCounters[sType]) {
			cert_CustomCounters[sType] += iValue;
		} else {
			cert_CustomCounters[sType] = iValue;
		}
	}
}


function cert_getCustomTags()
{
	var sRet = '';
	var ct_atrib = '', ct_acum = '';
	if (cert_CustomAttributes) {
		ct_atrib = 'ct_atrib=';
		for (var i in cert_CustomAttributes) {
			ct_atrib += i + ':' + cert_CustomAttributes[i] + ';';
		}
	}

	if (cert_CustomCounters) {
		ct_acum = 'ct_acum=';
		for (var i in cert_CustomCounters) {
			ct_acum += i + ':' + cert_CustomCounters[i] + ';';
		}
	}

	if (ct_atrib || ct_acum) {
		if (ct_atrib) {
			sRet += '&' + ct_atrib;
		}
		if (ct_acum) {
			sRet += '&' + ct_acum;
		}
	}
	return sRet;
}


/* Crea la URL para un sitio con e-Commerce. */
function cert_getURL_eCommerce(iSiteId, sPath, sAmount)
{
	var sOrigin = null;

	if ((sOrigin = cert_getCookie(DEFAULT_ORIGIN_COOKIE_NAME))) {
		cert_addCustomAttribute('origin', sOrigin);
	}

	if (sAmount) {
		cert_addCustomCounter('money', sAmount);
	}

	var sAppend = cert_getCustomTags();

	return cert_getURL(iSiteId, sPath, sAppend);
}
	
		
/* Efectua un hit en certifica usando una imagen pivote. */
function cert_registerHit(iSiteId, sPath, sPivotName) 
{
   var sAppend = '&cert_cachebuster=' + (1 + Math.floor (Math.random() * 10000));
   if ( !sPivotName )
      sPivotName = DEFAULT_PIVOT_NAME;
   if ( document.images )
      if ( document.images[sPivotName] )
         document.images[sPivotName].src = cert_getURL(iSiteId, sPath, sAppend);
}

/* Efectúa una redirección marcando la ruta de salida */
function cert_registerHitAndRedirect( sURL, iSiteId, sPath, sPivotName ) 
{
   cert_registerHit( iSiteId, sPath, sPivotName );
   setTimeout( "location.href = '" + sURL + "'", DEFAULT_REDIRECT_TIME );
}

/* Abre una nueva ventana, marcando el hit */
function cert_registerHitAndOpenWindow( sURL, iSiteId, sPath, sPivotName, sName, sFeatures, bReplace )
{
   cert_registerHit( iSiteId, sPath, sPivotName );
   if (!sName)
      sName = 'Downloads';
   if (!sFeatures)
      sFeatures = 'toolbar=no,location=no,directories=no,status=yes,menubar=no, scrollbars=no,resizable=no,width=425,height=510,screenX=20,screenY=20';
   window.open( sURL, 
      sName, 
      sFeatures, 
      bReplace 
   );
   return false;
}

/* Marca el hit y reemplaza/abre una URL en el frame 'sName' */
function cert_registerHitAndReplaceOtherFrame( sURL, sName, iSiteId, sPath, sPivotName ) 
{
   cert_registerHitAndOpenWindow( sURL, iSiteId, sPath, sPivotName, sName, 0, true );
}

/* Marca el hit y reemplaza/abre una URL en el frame 'sName' */
function cert_registerHitAndReplaceThisFrame( sURL, iSiteId, sPath, sPivotName ) 
{
   cert_registerHitAndRedirect( sURL, iSiteId, sPath, sPivotName );
}

/* Marca el hit y baja un archivo */
function cert_registerHitAndDownloadFile( sURL, iSiteId, sPath, sPivotName ) 
{
   cert_registerHitAndRedirect( sURL, iSiteId, sPath, sPivotName );
}

function cert_getAnchor(sUrl)
{
    return '<img src="' + sUrl + '" width="1" height="1" border="0" alt="Certifica.com">';
}

/* Marca un hit en la página actual */
function tagCertifica(iSiteId, sPath, sDesc) 
{
    sPrefix = null;
    sAppend = null;
    if (sPath.toLowerCase() == 'url') { 
        sPath = location.pathname;
    } 
    if (!sDesc) {
        sDesc = document.title;
    }
   if (sDesc) {
        sAppend = '&descr=' + escape(sDesc.substr(0, 50));
    }
    
 /*   sPath = cert_normalizePath(sPath, sPrefix);*/
	  var fragmento = sPath.split("/");

switch (fragmento[1]){
	
	case "":
	sPath= '/home/portada';
	break;

	case "articulos":
			sPath = 	fragmento[1] + '/portada';
	    if (fragmento.length > 3) 
				{
					sPath = fragmento[1] + "/" + fragmento[2] ;
	  		}
	break;
	case "forums":
		sPath = 	fragmento[1] + '/Portada';
	  if (fragmento.length > 2) 
				{
					switch (fragmento[2]){
						case '':
							sPath = fragmento[1] + '/Portada';
						break;				
						case "mi-primer-tema.324":
						case "preguntas-y-sugerencias-sobre-psicofxp-com.78":
						case "anuncios.450":
						case "tips.521":
						case "noticias.60":
						case "donde-estabas.586":
							sPath = fragmento[1] + '/General';
						break;

						case "tribus-urbanas.593":
						case "avatares-y-firmas.216":
						case "discuciones-generales.13":
						case "dedicatorias-y-cumpleanos.145":
						case "el-recreo.536":
								sPath = fragmento[1] + '/Comunidad';
						break;

						case "recursos.504":
						case "rigtones.505":
						case "imagenes-videos-y-skins.506":
						case "telefonos-moviles.276":
						case "general-telefonos-moviles.502":
						case "apple-iphone.595":
						case "blackberry.599":
						case "motorola.497":
						case "nokia.498":
						case "sony-ericsson.499":
						case "lg-pantech.515":
						case "samsung.500":
						case "alcatel.501":
						case "recomendaciones-y-reviews.387":
						case "operadoras-moviles.508":
						case "general-operadoras-moviles.513":
						case "movistar.509":
						case "personal.510":
						case "claro.511":
						case "nextel.512":
						case "desbloqueos.514":
							sPath = fragmento[1] + '/telefonia_movil';
						break;	

						case "bellas-artes.135":
						case "diseno.36":
						case "arquitectura-indumentaria-industrial-3d.541":
						case "grafica.543":
						case "recursos-tipografias-teoria-tutoriales.544":
						case "musica.41":
						case "musicos.195":
						case "recitales-and-eventos.347":
						case "literatura.62":
						case "taller-de-escritura-textos-de-usuarios.380":
						case "la-libreria.569":
						case "taller-de-escritura-juegos-y-consignas.585":
						case "fotografia-e-iluminacion-profesional.211":
						case "presupuestos-y-eleccion-de-equipos.447":
						case "cine-tv-radio-y-espectaculos.67":
								sPath = fragmento[1] + '/arte_y_cultura';
						break;	


						case "juegos-de-pc.206":
						case "consola-de-juegos.157":
						case "abandonware.120":
						case "juegos-de-mesa-rol-y-estrategia.152":
								sPath = fragmento[1] + '/juegos';
						break;	

						case "comics-y-animacion.35":
						case "proyecto-cartas.375":
						case "el-foro-de-comiqueando.492":
						case "manga-y-anime.335":
						case "historieta-argentina-y-europea.414":
						case "la-comiqueria.416":
								sPath = fragmento[1] + '/historieta_y_animacion';
						break;

						case "humor.95":
						case "vida-nocturna.124":
						case "sitios-web-varios.38":
						case "salidas.420":
								sPath = fragmento[1] + '/ocio';
						break;

						case "polideportivo.79":
						case "deportes-de-aventura.587":
						case "futbol.426":
						case "gimnasio.236":
						case "artes-marciales.280":
						case "deportes-de-contacto.533":
						case "rugby.568":
								sPath = fragmento[1] + '/deportes';
						break;
						
						case "amor-y-pareja.178":
						case "sexualidad.118":
								sPath = fragmento[1] + '/amor_y_sexualidad';
						break;		

					  case "amateur.423":
						case "mostra-lo-tuyo.532":
						case "el-reservado.588":
						case "xxx.51":
						case "hentai.191":
								sPath = fragmento[1] + '/adultos';
						break;

						case "familia.425":
						case "animales-y-mascotas.192":
						case "clasificados.265":
						case "acuarismo.584":
						case "adopciones.596":
						case "como-hago.197":
						case "manualidades.198":
								sPath = fragmento[1] + '/hogar-y-familia';
						break;

						case "autos.87":
						case "en-dos-ruedas.529":
						case "todo-por-2-ruedas.576":
						case "aeronautica.601":
								sPath = fragmento[1] + '/motores';
						break;

						case "gastronomia.172":
						case "imagen-y-cuidado-personal.334":
						case "viajes-y-turismo.193":
								sPath = fragmento[1] + '/estilo_de_vida';
						break;

						case "ciencia.176":
						case "historia.488":
						case "politica-economia-sociologia.146":
						case "filosofia.494":
						case "estudios.142":
						case "idiomas.452":
						case "esoterico.139":
						case "religion-y-espiritualidad.239":
								sPath = fragmento[1] + '/humanidades';
					  break;

						case "empleos.126":
						case "orientacion-legal.424":
						case "servicios.343":
						case "temas-laborales.128":
								sPath = fragmento[1] + '/laboral_legal';
						break;	


						case "general.546":
						case "bienes-raices.547":
						case "mercado-bursatil.548":
						case "seminarios-y-eventos.549":
								sPath = fragmento[1] + '/negocios_inversiones';
						break;

						case "software.11":
						case "hardware.58":
						case "recomendaciones-de-compra-venta-de-hard.271":
						case "programacion.313":
						case "desarrollo-web.264":
						case "recursos-y-mas.224":
						case "webmasters.319":
						case "administracion-web.275":
						case "diseno-web.210":
						case "sistemas-operativos.430":
						case "gnu-linux.50":
						case "windows.70":
						case "otros-s-o.456":
						case "it-pro-servidores.243":
						case "redes-informaticas.113":
						case "manuales-y-tutoriales.225":
						case "seguridad-informatica.47":
						case "chat-e-mail-y-mensajeros.132":
								sPath = fragmento[1] + '/informatica';
						break;

						case "television-hd.598":
						case "gadgets.432":
						case "audio-y-video.68":
						case "consultas-sobre-equipos.539":
						case "electronica.149":
								sPath = fragmento[1] + '/tecnologia';
						break;

						case "alejo-and-valentina.528":
						case "dominio-digital.287":
						case "tecnologia.406":
						case "informatica.49":
								sPath = fragmento[1] + '/foros_especiales';
						break;

						case "compra.19":
						case "venta.20":
								sPath = fragmento[1] + '/clasificados';
						break;
					
						default:
							sPath = "forums/otros/" + fragmento[1] ;
	  			}
     }
  break;
	
	case  "videos":
		sPath = 	fragmento[1] + '/portada';
	break ;	
		
	case  "fotos":
		sPath = 	fragmento[1] + '/portada';
	break ;	
	
	case  "amigos":
		sPath = 	fragmento[1] + '/portada';
	break ;	
	
	case  "empleos":
		sPath = 	fragmento[1] + '/portada';
	break ;	


	case  "contacto":
		sPath = 	fragmento[1] + '/portada';
	break ;	
	
	case  "legales":
		sPath = 	fragmento[1] + '/portada';
	break ;	

	case  "ayuda":
		sPath = 	fragmento[1] + '/portada';
	break ;	

	case  "trabaja-con-nosotros.html":
		sPath = 	fragmento[1] + '/portada';
	break ;	

	case  "do":
		sPath = 	fragmento[1] + '/portada';
	break ;	
	case  "blog":
		sPath = 	fragmento[1] + '/portada';
	break ;	

	default:
		sPath = 'canales_nuevos/' +  fragmento[1];
		
}

	/*alert(sPath); */

	  sURL = cert_getURL(iSiteId, sPath, sAppend); 
  
    document.writeln('<img src="' + sURL
        + '" width="1" height="1" border="0" alt="Certifica.com">' );
}

/* Marca un hit en la página actual, usando eCommerce */
function tagCertifica_eCommerce(iSiteId, sPath, iAmount) 
{
    document.writeln(cert_getAnchor(cert_getURL_eCommerce(iSiteId, sPath, iAmount)));
}

/* Marca un registro cada iTime milisegundos.  */
function cert_registerPeriodicHit( iSiteId, sPath, sPivotName, iTime ) 
{
   if ( !sPivotName )
      sPivotName = DEFAULT_PIVOT_NAME;
   if ( !iTime )
      iTime = DEFAULT_PERIODIC_REDIRECT_TIME;

   cert_registerHit( iSiteId, sPath, sPivotName );
   setTimeout( 'cert_registerPeriodicHit( ' + iSiteId + ', "' + sPath + '", "' + sPivotName + '", ' + iTime + ')', iTime );
}

cert_setOrigin();
