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();

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();

String.prototype.parseScripts = function () {
    var texto = this.valueOf(); 
    scriptsREGEXP = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/gi;
    resultados = texto.match(scriptsREGEXP);
    if (resultados != null) {
        for(var i=0; i<resultados.length; i++) {
            texto_script = resultados[i].replace(scriptsREGEXP,"$1");
            try {
                eval(texto_script);
            } catch(e) {
                errores(e);
            }
        }
    }
}

/*
 * 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.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) {
    		is.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) {
		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;
		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
                    );
				}
			}
			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);
			command = "cache = cacheCapas.instance.getCache('"+destino+"'); \ndocument.getElementById('"+destino+"').innerHTML=cache;\n";
		}
        command = command + ";\ncache.parseSrcScripts();\nBehaviour.apply()";
        command = command + ";\ncache.parseScripts();\nBehaviour.apply()";
        timer = setTimeout(command,5000);
		this.peticion( url,args,method, {
				onLoading: function(peticion) {
      				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;
      				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) {
					clearTimeout(timer);
					if (peticion.status != 200) {
						if (destino.constructor == Array) {
							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;
					}
					textoRetorno = peticion.responseText;
					var codigoEstado=getCodigoEstado(textoRetorno);
					if (destino.constructor == Array) {
						if ((codigoEstado=="000") || (codigoEstado=="")){
							destino = destino[0];
						} else {
							destino = destino[1];
						}
					} 
					document.getElementById(destino).innerHTML=textoRetorno;
      				try {
          				textoRetorno.parseSrcScripts();
          				textoRetorno.parseScripts();
      				} catch(e) {
          				errores(e)
      				}
					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   = 3;
	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) {
		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";
		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){
        var docElem     = document.documentElement;
		var scrollX = self.pageXOffset || (docElem&&docElem.scrollLeft) || document.body.scrollLeft;
		var scrollY = self.pageYOffset || (docElem&&docElem.scrollTop) || document.body.scrollTop;
		var width  = self.innerWidth || (docElem&&docElem.clientWidth) || document.body.clientWidth;
		var height = self.innerHeight || (docElem&&docElem.clientHeight) || document.body.clientHeight;
        var x = Math.round(width/2) - (ventW /2) + scrollX;
	    var y = Math.round(height/2) - (ventH /2) + scrollY;
        this.moveTo(x,y);
	},
	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 (){
		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 (){
		vent_locker.style.display = "none";
		vent.style.display        = "none";
	},
	elements2hide: function (visibility){
		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; }
}

// Autorizaciones multiples de videos WMP en akamai
var mauth = new Array();

function playMicrosoftMedia_(urlMedia, wMedia, hMedia, controlMedia, divId, auth){
    var hasActX = checkAX();
	var auxDivContent;
	if (auth!=null) {
		if (urlMedia.indexOf('?') > 0) urlMedia+='&auth='+auth;
		else urlMedia+='?auth='+auth;
	}

    if (hasActX){
       auxDivContent = '<OBJECT ID="Player" width='+wMedia+' height='+hMedia+' CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">';
       auxDivContent+= '<PARAM NAME="URL" VALUE="'+urlMedia+'">';
       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+'"';
       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);
}


function playFlashObject_(urlMedia, wMedia, hMedia, divId){
  var auxDivContent;
  auxDivContent ='<object width="'+wMedia+'" height="'+hMedia+'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0">\n';
  auxDivContent+=' <param name="quality" value="high" />\n';
  auxDivContent+=' <param name="wmode" value="opaque" />\n';
  auxDivContent+=' <param name="SRC" value="'+urlMedia+'" />\n';
  auxDivContent+=' <embed src="'+urlMedia+'" quality="high" wmode="opaque" width="'+wMedia+'" height="'+hMedia+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash">\n';
  auxDivContent+=' </embed>\n';
  auxDivContent+='</object>\n';

  if (divId) {
    var objDiv = document.getElementById(divId);
    loadEmbedObjectInDiv(objDiv, auxDivContent);
  }
  else loadEmbedObject(auxDivContent);
}


function makeComands(){
  var id = actualId;
  makeFSCommand(id, "podcast");
}

function popup(url, ancho, alto, nombre) {
    window.open(url, nombre, 'width=' + ancho + ',height=' + alto + ',scrollbars=no,resizable=yes,directories=no,location=no,menubar=no,toolbar=no');
    return true;
}
function playParamFlashObject_(swfFile, id, dim, transparent, clsid, flashversion, divId) {
    content = '<OBJECT classid="'+clsid+'" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+flashversion+',0,0,0" ID="'+id+'" '+dim+' ALIGN="">';

    if(swfFile.indexOf('?')!=-1){
        pos=swfFile.indexOf('?');
        fname=swfFile.substring(0,pos);
        fvars=swfFile.substring(pos+1,swfFile.length);
        content += '<PARAM NAME=movie VALUE="'+fname+'">';
        content += '<PARAM NAME=FlashVars VALUE="'+fvars+'">';
    }else{
        fname=swfFile;
        fvars='';
        content += '<PARAM NAME=movie VALUE="'+fname+'">';
    }
    content += '<PARAM NAME=quality VALUE=high><PARAM NAME="wmode" VALUE="'+transparent+'">';
    content += '<EMBED src="'+fname+'" FlashVars="'+fvars+'" quality=high wmode='+transparent+' swLiveConnect=FALSE '+dim+' name="'+id+'" align="" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">';
    content += '</EMBED></OBJECT>';
    if (divId) {
        objDiv = document.getElementById(divId);
        objDiv.innerHTML=content;
    }
    else document.write(content);
    return content;
}

function nuevaVentana(url,nombre) {
  var s = window.open(url,"audio_cadenaser2");
  return true;  
}

function popup_con_scrollbar (url, ancho, alto, nombre) {
    window.open(url, nombre, 'width=' + ancho + ',height=' + alto + ',scrollbars=yes,resizable=yes,directories=no,location=no,menubar=no,toolbar=no');
};

