/*
Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
of Simon Willison (see comments by Simon below).

License:
Behaviour is entirely BSD licensed.

More information:
http://ripcord.co.nz/behaviour/
*/

var Behaviour = {
	list : new Array,
	
	register : function(sheet){
		Behaviour.list.push(sheet);
	},
	
	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},
	
	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				try{
            list = document.getElementsBySelector(selector);
          }catch(err){
          
          }
				
				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},
	
	addLoadEvent : function(func){
		var oldonload = window.onload;
		
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

Behaviour.start();

/*
The following code is Copyright (C) Simon Willison 2004.
*/

function getAllChildren(e) {
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  if (!document.getElementsByTagName) {
    return new Array();
  }
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if ((element==null) || (tagName && element.nodeName.toLowerCase() != tagName)) {
        return new Array();
      }
      currentContext = new Array(element);
      continue;
    }
    if (token.indexOf('.') > -1) {
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue;
    }
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction;
      switch (attrOperator) {
        case '=': 
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~':
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|':
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^':
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$':
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*':
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue;
    }
    
    if (!currentContext[0]){
    	return;
    }
    
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

//AJAX
function cacheCapas() {
        this.cache={};   
    }
    cacheCapas.prototype = {
        getCache : function(id)
        {
            return this.cache[id];
        },
        setCache : function(id,texto)
        {
            this.cache[id]=texto;
        }
    }
    cacheCapas.instance=new cacheCapas();


    /*
     * Metodo que recoge los scripts de una cadena de texto, busca su src, y los
     * inserta en la cabecera via appendChild. Lo usamos por que asignar un texto
     * a un elemento via innerHTML no hace que se parseen lso scripts.
     * @param texto Cadena en la que  se encuentra la etiqueta <script src="...
     * @access private
     */ 
    String.prototype.parseSrcScripts = function () {
        texto=this.valueOf();
        scriptsSrcREGEXP = /(?:<script.*src=[\"|\']([^\"|\']*)[\"|\'][^>]*>)/gi;
        resultados = texto.match(scriptsSrcREGEXP);
        if (resultados != null)
        {
            for(var i=0; i<resultados.length; i++) 
            {
                archivo_js = resultados[i].replace(scriptsSrcREGEXP,"$1");
                if (archivo_js.indexOf("http") === 0 && archivo_js.indexOf("http://ads.prisacom.com")!=0)
                    throw "El archivo es externo"; 
                scrpt = document.createElement("script");
                scrpt.src=archivo_js;
                document.getElementsByTagName("head")[0].appendChild(scrpt);
            }

        }
    }

    function Ajax()
	{
		this.estadoAnterior = -1;
		//AJAX Prisacom Interactive Navigation Object
	}
	Ajax.prototype = {
			
			peticion:function (url,args,method,callback)
			{
				xmlHttp=this.getXmlHttpObject()
				if (xmlHttp==null)
				{
					return
				}
				var eventos = ["onAbort","onLoading","onLoaded","onInteractive","onComplete"];
				this.callback=callback;
				xmlHttp.onreadystatechange = function()
				{
					try {
						if (!this.estadoAnterior) this.estadoAnterior = -1;
						if (typeof(callback[eventos[xmlHttp.readyState]]) == "function" && this.estadoAnterior!=xmlHttp.readyState){
              evento_actual = eventos[xmlHttp.readyState];
              try {
                callback[eventos[xmlHttp.readyState]](xmlHttp);
            	 } catch (e) {
                  errores(e);
               }
              this.estadoAnterior = xmlHttp.readyState;
						}
					}catch(e){
            errores(e)
					}
				}
				try {

					if (method=="GET") {
						xmlHttp.open("GET",url+"?"+args,true);
						xmlHttp.send(null)
					} else {
						xmlHttp.open("POST", url, true);
						xmlHttp.setRequestHeader("Method", "POST "+url+" HTTP/1.1");
						xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
						xmlHttp.send(args);
					}
				} catch(e) {
          this.errores(e)
				}
			},
			getXmlHttpObject: function ()
			{ 
				var objXMLHttp=null
				try 
				{
					objXMLHttp=new XMLHttpRequest()
				}
				catch(e)
				{
					try 
					{
						objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
					}
					catch (e)
					{
						try 
						{
					      		objXMLHttp=new ActiveXObject('Msxml2.XMLHTTP');
						} 
						catch (e)
						{
							return null;
						}
					}
				}
				return objXMLHttp
			},
			
			/*
			 * Metodo que sustituye el output por la etiqueta dentro del html
			 * @param url Url que genera la salida del contenido
			 * @param arg Argumentos que recibe el url (Formato: arg1=valor1&arg2=valor2) ¡debe
			 * estar debidamente URLEncodeado!
			 * @param textoLoading Texto a mostrar mientras se espera la respuesta
			 * @param destino Array con las etiquetas a ser reemplazadas. destino[0]="etiqueta a reemplazar si todo va bien"; destino[1]="etiqueta a reemplazar si va mal"
			 * @param destino o puede ser un string si siempre se va a reemplazar por la misma etiqueta
			 * @param method Metodo Get o Post
			 * @access public 
			 */ 
			replace: function(url,args,textoLoading,destino,method) {
				//El sexto argumento (posicion 5 del array) es una funcion que se ejecuta en caso
				//de que todo haya ido con exito
				var posicion_parametro_funcion = 5;
				if (typeof(arguments[posicion_parametro_funcion]) == "function") {
					finalizar = arguments[posicion_parametro_funcion];
				}else{
					finalizar = function () {};
				}
				getCodigoEstado= this.getCodigoEstado;
				errores = this.errores;
				var timer = null;
				//Declaramos timer para poder anularlo luego.
				//Vamos a meter el contenido actual de las capas en la cache, por si hay algun
				//problema en la carga.

				if (destino.constructor == Array)
				{
					for (var i = 0; i < destino.length; i++)
					{
						if (document.getElementById(destino[i]).innerHTML.replace(/\W/gi,"").toUpperCase() != textoLoading.replace(/\W/gi,"").toUpperCase())
						{
							cacheCapas.instance.setCache(
                                destino[i],
                                document.getElementById(destino[i]).innerHTML
                            );
						}
					}
					//Va tratado por que los saltos de linea y las comillas simples interrumpirian el literal
					command = "cache = cacheCapas.instance.getCache('"+destino[1]+"');\ndocument.getElementById('"+destino[1]+"').innerHTML=cache;\n";
				} else {
					if (document.getElementById(destino).innerHTML.replace(/\W/gi,"").toUpperCase() != textoLoading.replace(/\W/gi,"").toUpperCase())
					{
						cacheCapas.instance.setCache(destino,document.getElementById(destino).innerHTML);
					}
					//El cache para javascript da igual por que si el innerHTML es igual que el texto loading 
					//es por que esta capa ya esta en el cache 
					command = "cache = cacheCapas.instance.getCache('"+destino+"'); \ndocument.getElementById('"+destino+"').innerHTML=cache;\n";
				}
				//complicamos esto asi por que command tiene que ser una cadena de texto.
				//Al final, setTimeout lanza un eval (en el ambito global del script) de la cadena de texto
				//transcurridos x milisegundos
				//A command le añadimos para que parsee los scripts.
                command = command + ";\ncache.parseSrcScripts();\nBehaviour.apply()";
                timer = setTimeout(command,5000);
				this.peticion(
					url,args,method,
					{
						onLoading: function(peticion) {
							//Si destino es un array, colocamos el texto de cargando
							//en la capa asignada a "Todo ha ido mal".
              if (destino.constructor == Array){
                var dummy_destino = document.getElementById(destino[1]);
              } else {
                var dummy_destino = document.getElementById(destino);
              }
              var alto_destino = dummy_destino.offsetHeight || 
                     dummy_destino.style.pixelHeight || 
                     dummy_destino.style.height;
              
              dummy_destino.innerHTML = textoLoading;
          
              // calculamos el padding necesario para centrar
              // verticalmente el texto Cargando
              try {
                 var dummy_cargando = document.getElementById("cargando");
                 var alto_cargando= dummy_cargando.offsetHeight || 
                        dummy_cargando.style.pixelHeight || 
                        dummy_cargando.style.height;
                 var padding = parseInt(alto_destino-alto_cargando);
                 padding = parseInt(padding/2);

                 dummy_cargando.style.textAlign     = "center";
                 dummy_cargando.style.paddingTop    = padding+"px";
                 dummy_cargando.style.paddingBottom = padding+"px";
              } catch(e) {
                return true;
              }
              
            },
						onComplete: function(peticion) {
							//Las variables destino, timer, y otras las conservamos
							//del cuerpo de la funcion que encierra a esta gracias a las 
							//propiedades de las closures:
							//http://blog.morrisjohns.com/javascript_closures_for_dummies

							//Primero quitamos el timer para en caso de que casque
							clearTimeout(timer);
							//Si tenemos el timer a mano es, como hemos dicho, por las
							//propiedades del closure

							//Okey, si recibimos una cabecera distinta a 200 es que algo ha ido mal 
							//En ese caso cogemos el texto de las capas y eliminamos 
							if (peticion.status != 200) 
							{
								if (destino.constructor == Array)
								{
									//se han mandado varias capas: la que tiene el texto "cargando"
									//es la de "Todo ha ido mal".
									for (var i = 0; i<destino.length; i++) 
									{
										document.getElementById(destino[i]).innerHTML=cacheCapas.instance.getCache(destino[i]);
									}
								} else {
									document.getElementById(destino).innerHTML = cacheCapas.instance.getCache(destino);
								}
								return false;
							}
							//Todo lo demas ocurre solo en el caso de que la peticion haya dado 
							//un 200
							textoRetorno = peticion.responseText;
							try {
								textoRetorno.parseSrcScripts();
							} catch(e) {
                errores(e)
							}
							var codigoEstado=getCodigoEstado(textoRetorno);
							if (destino.constructor == Array) {
								if ((codigoEstado=="000") || (codigoEstado=="")){
									destino = destino[0];
								} else {
									destino = destino[1];
								}
							} 
							document.getElementById(destino).innerHTML=textoRetorno;

							//Funcion a ejecutar al final del proceso
							finalizar();
						}
					}
				)
			},
			getCodigoEstado: function (texto){
				var RegSpan=/.*<span\s?class=["|']?estado["|']?\s?id=["|']?([^"'>\s]+)["|']?><\/span>.*/gi;
				var codigoError = "";
				var strSpan = texto.match(RegSpan);							
				if (strSpan!=null)
					codigoError = strSpan[0].replace(RegSpan,"$1");
				return codigoError;
			},
			errores: function(e) {
       
				if (typeof(debugging) != "undefined")
				{
            if (typeof(e.description) != "undefined")
                 alert(e.description)
            else 
                alert(e);
				}
			}
	}


//FORM
function Form(elementId) 
{
	for (var i = 0; i < document.forms.length; i++)
	{
		if (document.forms[i].id==elementId)
		{
			this.formulario = document.forms[i];
			break;
		}
	}
   if (elementId == "envio_noticia_amigo"){
       el= document.getElementById(elementId);
       this.formulario = el;
   }
}

Form.prototype = {
	getQueryString: function() {
		var args = Array();
		for (var i = 0; i < this.formulario.elements.length; i++)
		{
			elem = this.formulario.elements[i];
			if (elem.type=="text" || elem.type =="textarea" || elem.type =="password" ||elem.type =="hidden")
			{
				args[args.length]=elem.name+"="+escape(elem.value);
			} else if (elem.type=="radio" || elem.type =="checkbox") {
				if (elem.checked)
					args[args.length]=elem.name+"="+escape(elem.value);
			} else if (typeof(elem.type)!="undefined" && elem.type.split("-")[0]=="select") {
				for (var j=0; j<elem.options.length; j++)
				{
					if (elem.options[j].selected)
					{
						args[args.length]=elem.name+"="+elem.options[j].value;
					}
				}
			} 
		}
		return args.join("&");
	},
	amp:  function(i) {
		if (i != this.formulario.elements.length-1)
		return "&amp<br>";
	}
}

//VENTANA
//var vent;        // ventana (div) modal
//var vent_locker; // ventana (div) que bloquea lo que hay debajo de ella

function Ventana() {
	vent                = document.createElement("DIV");
	vent.id             = "ventana";
	vent.style.display  = "none";
	vent.style.position = "absolute";
	vent.style.zIndex   = 200;
	this.moveTo(0,0);
    try {
        vent.onpropertychange=function() {
            if (event.propertyName=="innerHTML")
            {
                Ventana.instance.center(Ventana.instance.getVentHeight(),Ventana.instance.getVentWidth()); 
            }
            return true;
        }
    } catch(e)
    {

    }
	document.getElementsByTagName("body")[0].appendChild(vent);
	
	vent_locker                = document.createElement("DIV");
	vent_locker.id             = "ventana_locker";
	vent_locker.style.display  = "none";
	vent_locker.style.position = "absolute";
	vent_locker.style.zIndex   = 1;
	vent_locker.style.left     = "0px";
	vent_locker.style.top      = "0px";
	vent_locker.style.backgroundImage = "url(/images/0.gif)";
	vent_locker.className             = "modal_close";
	document.getElementsByTagName("body")[0].appendChild(vent_locker);
}

Ventana.prototype = {
	setStringContent: function (contenido) {
		vent.innerHTML=contenido;
	},
	setHttpContent: function(url,LOAD_STATUS_TEXT,method)
	{
		// la siguiente funcion la pasamos por parametro a ajax
		// para que sea ejecutada alli
		function accionesPersonalizadas(){
			VentH=Ventana.instance.getVentHeight();
			VentW=Ventana.instance.getVentWidth();
			vent.style.display="none";
			Ventana.instance.center(VentH,VentW);
			Behaviour.apply();
			vent.style.display="block"
		}
		a = new Ajax();
		var url = url;
		var esDeCod = url.match(/\?/g);
		if (esDeCod==null){
			url = unescape(url);
		}
		var argsDec = url.split("?")[1];		
		var aP      = argsDec.split("aP=")[1];
		aP          = unescape(aP.split("&")[0]);
		var ctn     = "ventana";
		//alert(aP);
		a.replace("/modulo/index.html",aP,LOAD_STATUS_TEXT,ctn,"GET", accionesPersonalizadas);
		return false;
},
	getVentWidth: function(){
		return vent.offsetWidth ||  vent.style.pixelWidth || vent.style.width;
	},

	getVentHeight: function(){
		return vent.offsetHeight || vent.style.pixelHeight || vent.style.height;
	},
	center: function(ventH,ventW){
		//IMPORTANTE
        //como este método se llama con el evento onpropertychange del explorer
        //ni este método ni cualquiera que se llame desde él
        //debe modificar propiedades de vent, (aunque si puede hacerlo de vent.style.loquesea)
        //--NUNCA vent.style=otroObjeto--
        
        //En otro caso, se caera en un bucle infinito (se llamará a onpropertychange cada vez
        //que una propiedad cambie, y este método cambiará una propiedad de vent, se llamará a
        //onpropertychange, y así hasta el infinito o hasta que matemos el proceso, lo que llegue antes)
        
        var docElem     = document.documentElement;
        
		// posiciones del scroll
		var scrollX = self.pageXOffset || (docElem&&docElem.scrollLeft) || document.body.scrollLeft;
		var scrollY = self.pageYOffset || (docElem&&docElem.scrollTop) || document.body.scrollTop;
		// ancho y alto de la ventana del navegador
		var width  = self.innerWidth || (docElem&&docElem.clientWidth) || document.body.clientWidth;
		var height = self.innerHeight || (docElem&&docElem.clientHeight) || document.body.clientHeight;
		// calculamos X e Y para posicionar la ventana modal
        var x = Math.round(width/2) - (ventW /2) + scrollX;
	    var y = Math.round(height/2) - (ventH /2) + scrollY;
        this.moveTo(x,y);
        //alert("ventana navegador: "+width+";\nancho_ventana:"+ventW+"\nscroll:"+scrollX+"\ncalculo_left:"+x);
	},
	resizeTo: function (alto,ancho){
		alto  = parseInt(alto);
		ancho = parseInt(ancho);
		vent.style.height=alto;
		vent.style.width=ancho;
		vent.style.clip="rect:(0,"+ancho+","+alto+",0)";
	},
	setScrollable: function (scrollable) {
		vent.style.overflow=(scrollable)?"auto":"hidden";
	},
	moveTo: function (x,y){
		vent.style.left=parseInt(x)+"px";
		vent.style.top=parseInt(y)+"px";
	},
	show: function (){
		//this.elements2hide("hidden");
		altoDocumento 		   = (document.body.scrollHeight || document.height)+"px";
		anchoDocumento    	   = (document.body.scrollWidth  || document.width)+"px";
		vent_locker.style.height   = altoDocumento;
        	vent_locker.style.width    = anchoDocumento;
		vent_locker.style.display  = "block";
		
		vent.style.display         = "block";
		this.moveTo(0,0);
		this.center(this.getVentHeight(),this.getVentWidth());
		Behaviour.apply();
	},
	hide: function (){
		//this.elements2hide("visible");
		vent_locker.style.display = "none";
		vent.style.display        = "none";
	},
	elements2hide: function (visibility){
		//Esta funcion oculta o muestra todos los elementos que lleven el class "modal_hides_me"
		var divs2hide = document.getElementsBySelector(".modal_hides_me");
		for(var i in divs2hide){
			divs2hide[i].style.visibility = visibility;
		}
	}
}

function instanciaVentana(){
	if (typeof(Ventana.instance)=="undefined")
        Ventana.instance = new Ventana();
}

Behaviour.addLoadEvent(instanciaVentana);

function loadEmbedObject(str){
        document.write(str);
}

function loadEmbedObjectInDiv(myDiv, str){
        myDiv.innerHTML = str;
}

function checkAX()
{
        try{
                if (window.ActiveXObject)
                {
                        obj = new ActiveXObject("WMPlayer.OCX");
                        return true;
                }
                else if (window.GeckoActiveXObject)
                {
                        obj = new GeckoActiveXObject("WMPlayer.OCX");
                        return true;
                }
                else return false;
        }
        catch(e) { return false; }
}

function playMicrosoftMedia(urlMedia, wMedia, hMedia, controlMedia, divId, auth){
        var hasActX = checkAX();
	var auxDivContent;
        if (hasActX){
                auxDivContent = '<OBJECT ID="Player" width='+wMedia+' height='+hMedia+' CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">';
                auxDivContent+= '<PARAM NAME="URL" VALUE="'+urlMedia+'?auth='+auth+'">';
                auxDivContent+= '<PARAM NAME="AutoStart" VALUE="true">';
                if(controlMedia == true){
                        auxDivContent+= '<PARAM NAME="ShowControls" VALUE="True">';
                        auxDivContent+= '<PARAM NAME="uiMode" VALUE="full">';
                }else{
                        auxDivContent+= '<PARAM NAME="ShowControls" VALUE="False">';
                        auxDivContent+= '<PARAM NAME="uiMode" VALUE="none">';
                }
                auxDivContent+= '<PARAM NAME="ShowStatusBar" VALUE="False">';
                auxDivContent+= '</OBJECT>';
        }else{
                auxDivContent = '<EMBED type="application/x-mplayer2" width="'+wMedia+'" height="'+hMedia+'"';
                auxDivContent+= 'pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"';
                auxDivContent+= 'SRC="'+urlMedia+'?auth='+auth+'"';
                auxDivContent+= 'name="PlayerEmbed"';
                auxDivContent+= 'autostart="1"';
                auxDivContent+= 'showstatusbar="0"';
                if(controlMedia == true){
                        auxDivContent+= 'showcontrols="1">';
                }else{
                        auxDivContent+= 'showcontrols="0">';
                }
                auxDivContent+= '</EMBED>';

        }
        if (divId)
	{
		var objDiv = document.getElementById(divId);
        	loadEmbedObjectInDiv(objDiv, auxDivContent);
	}
	else loadEmbedObject(auxDivContent);
}

// Autorizaciones multiples de videos WMP en akamai
var mauth = new Array();



