﻿

function getElementsByClass(searchClass,node,tag) {
       //consigue todos los elementos con la cssclass de searchClass dentro del nodo node y que sean de etiqueta tag.
       var classElements = new Array();
       if ( node == null )
               node = document;
       if ( tag == null )
               tag = '*';
       var els = node.getElementsByTagName(tag);
       var elsLen = els.length;
       var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
       for (i = 0, j = 0; i < elsLen; i++) {
               if ( pattern.test(els[i].className) ) {
                       classElements[j] = els[i];
                       j++;
               }
       }
       return classElements;
}

function getElementsByTitle(titulo,etiqueta){
//consigue todos los elementos con el title titulo y que pertenezcan al tag etiqueta.
    // el arreglo contendra los titulos
    var eltsTitle = new Array();

    // el parametro etiqueta(string) indica dónde se buscara. Si se quiere buscar meter en el array todos los elementos de la pagina, utilizar '*'
    var elts = document.getElementsByTagName(etiqueta);

    // recorremos todo
    for (var n = 0; n < elts.length; ++n) {

        // si el elemento n tiene un title que coincide con el titulo que buscamos, lo metemos en el primer array
        if (elts[n].getAttribute('title') && elts[n].getAttribute('title') == titulo) {
            eltsTitle.push(elts[n]);
        }

    }

    // devolvemos el array
    return eltsTitle;
}


/*function creaTextAreaFCK(){
       //busca los elementos con clase MiTextarea y los transforma al objeto FCK.
        
        //si existe un formulario...
        if (document.getElementById("formBasico"))
        {
            var nombreFCK = "MiTextarea";
            
            var fcks = getElementsByClass(nombreFCK, document.getElementById("formBasico"), "textarea");
            if (fcks.length > 0){
                
                for(var i = 0;i<fcks.length;i++)
                {
                var oFCKeditor = new FCKeditor( nombreFCK );
                oFCKeditor.BasePath = "fckeditor/";
                //oFCKeditor.ToolbarSet = 'MiToolbar';
                oFCKeditor.ToolbarSet = 'Basic';
                oFCKeditor.Width = '100%';

                oFCKeditor.ReplaceTextarea();
               }
              }
        }
        

}*/

function creaTextAreaCK(){
       //busca los elementos con clase MiTextarea y los transforma al objeto CK.
        
        //si existe un formulario...
        if (document.getElementById("formBasico"))
        {
            var nombreCK = "MiTextarea";
            
            var cks = getElementsByClass(nombreCK, document.getElementById("formBasico"), "textarea");
            if (cks.length > 0){
                
                for(var i = 0;i<cks.length;i++)
                {
                    CKEDITOR.replace( cks[i].name );
               }
              }
        }
        

}


	
function AbreFoto(ruta, titulo){
    //abre una ventana de tipo visor con la imagen de la ruta. los dos parámetros se pasan a dos hidden fields que luego recogerá la página visor.htm 
	document.aspnetForm.hName.value = ruta;
	document.aspnetForm.hTitle.value = titulo;
window.open('visor.htm','Visor','width=5,height=5,screenX=0,screenY=0,top=0,left=0,titlebar=no,location=no,toolbar=no,directories=no,menubar=no,resizable=yes,scrollbars=no,status=no');

    return false;
}

function client_OnTreeNodeChecked(e){
    //marcado de nodos de un arbol de forma descendente (de padre a hijos)     
    var obj = null;

    if (document.all)
    {
        obj = window.event.srcElement;}
    else
    {
        obj = e.target;}
        var treeNodeFound = false;
        var checkedState;

        if (obj.tagName == "INPUT" && obj.type == "checkbox")
        {
            var treeNode = obj;
            checkedState = treeNode.checked;
            do
                {
                if (document.all)
                {obj = obj.parentElement;}
                else
                {obj = obj.parentNode;}
                }
             while (obj.tagName != "TABLE")

            var parentTreeLevel = obj.rows[0].cells.length;
            var parentTreeNode = obj.rows[0].cells[0];
            var tables = null;
            if (document.all)
                {tables = obj.parentElement.getElementsByTagName("TABLE");}
            else
                {tables = obj.parentNode.getElementsByTagName("TABLE");}
            var numTables = tables.length
            if (numTables >= 1)
            {
                for (i=0; i < numTables; i++)
                {
                    if (tables[i] == obj)
                    {
                        treeNodeFound = true;
                        i++;
                        if (i == numTables)
                            {return;}
                        }
                        if (treeNodeFound == true)
                        {
                            var childTreeLevel = tables[i].rows[0].cells.length;
                            if (childTreeLevel > parentTreeLevel)
                            {
                                var cell = tables[i].rows[0].cells[childTreeLevel - 1];
                                var inputs = cell.getElementsByTagName("INPUT");
                                inputs[0].checked = checkedState;
                            }
                            else
                                {return;}
                        }
                  }
            }
     }
}

function validaForm(boton){
 
     //si existe un formulario...
    if (document.getElementById("formBasico"))
    {
        var obligatorios = getElementsByClass("obligatorio",document.getElementById("formBasico"),"input");
     
        var error = false;
        var txtAlert = "Debe completar todos los campos obligatorios."
        
        for (var i=0;i<obligatorios.length;i++)
        {
            if(obligatorios[i].value==""){ error=true;//txtAlert += obligatorios[i].id;
            }
        }
        
        if(error){
        alert(txtAlert);return false;}
        else{return true;
        }
    }
}

//degradado de color rgb
var Fat = {
	make_hex : function (r,g,b) 
	{
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	},
	fade_all : function (dur)
	{
		;
		var a = document.getElementsByTagName("*");
		for (var i = 0; i < a.length; i++) 
		{
			var o = a[i];
			var r = /fade-?(\w{3,6})?/.exec(o.className);
			if (r)
			{
				if (!r[1]) r[1] = "";
				if (o.id) Fat.fade_element(o.id,null,dur,"#"+r[1]);
			}
		}
	},
	fade_element : function (id, fps, duration, from, to) 
	{
		if (!fps) fps = 30;
		if (!duration) duration = 3000;
		if (!from || from=="#") from = "#ffff33";
		if (!to) to = this.get_bgcolor(id);

		var frames = Math.round(fps * (duration / 1000));
		var interval = duration / frames;
		var delay = interval;
		var frame = 0;

		if (from.length < 7) from += from.substr(1,3);
		if (to.length < 7) to += to.substr(1,3);

		var rf = parseInt(from.substr(1,2),16);
		var gf = parseInt(from.substr(3,2),16);
		var bf = parseInt(from.substr(5,2),16);
		var rt = parseInt(to.substr(1,2),16);
		var gt = parseInt(to.substr(3,2),16);
		var bt = parseInt(to.substr(5,2),16);

		var r,g,b,h;
		while (frame < frames)
		{
			r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
			g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
			b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
			h = this.make_hex(r,g,b);

			setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay);

			frame++;
			delay = interval * frame; 
		}
		setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	},
	set_bgcolor : function (id, c)
	{
		var o = document.getElementById(id);
		o.style.backgroundColor = c;
	},
	get_bgcolor : function (id)
	{
		var o = document.getElementById(id);
		while(o)
		{
			var c;
			if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
			if (o.currentStyle) c = o.currentStyle.backgroundColor;
			if ((c != "" && c != "transparent") || o.tagName == "body") { break; }
			o = o.parentNode;
		}
		if (c == undefined || c == "" || c == "transparent") c = "#ffffff";
		var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
		if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
		return c;
	}
}


/*
//Funciones que nos mostraran un texto
function MostrarTooltip ( idObject, idTooltip ) 
{ 			
	var obj = document.getElementById( idObject ); 
	document.getElementById(idTooltip).innerHTML = obj.options[obj.selectedIndex].value;
	if(obj.options[obj.selectedIndex].value !="") 
	{
		//Formato Tooltip 
 		document.getElementById(idTooltip).style.zIndex = 9999999; 
  		document.getElementById(idTooltip).style.display = "inline"; 
  		document.getElementById(idTooltip).style.position = "absolute"; 
 		document.getElementById(idTooltip).style.border =  "ActiveBorder  1px	solid"  ; 
		document.getElementById(idTooltip).style.padding =   "3px"; > 
		document.getElementById(idTooltip).style.fontSize =  "10px"; 
		document.getElementById(idTooltip).style.fontFamily = "Verdana"; 
		document.getElementById(idTooltip).style.backgroundColor = "LemonChiffon"; 
		document.getElementById(idTooltip).style.top =    
		document.getElementById(idObject).offsetTop + document.getElementById(idObject).offsetHeight + "px";   
		document.getElementById(idTooltip).style.left =	5 + event.x;			    
	}      
} 
function OcultarTooltip ( idTooltip )
{ 
  document.getElementById(idTooltip).style.display = "none"; 
}

*/

//JS no intrusivo
function addLoadEvent(func) 
{
	if ( typeof wpOnload!='function')
	{
		wpOnload=func;
	}
	else
	{ 
	var oldonload=wpOnload;
	wpOnload=function()
		{
		oldonload();
		func();
		}
	}
}

addLoadEvent(function ()  { 
    //Fat.fade_all();
    //creaTextAreaFCK();
    creaTextAreaCK();
    gestionGlobos("colIz",180); //temporal, demasiado restrictivo
    //controlLeidosNoLeidos();
    //posElsAbs();
    clickAcordeon();
});

function clickAcordeon()
{
    var divAcordeones = getElementsByClass("ClickAcordeon",null,"div");
    
    for (var i= 0; i<divAcordeones.length ; i++)
        {
            divAcordeones[i].onclick = function() {
                var divHTML = this.innerHTML;
                
                var divHTMLPart = divHTML.split('id="');
                var divHTMLPart2;
                if(typeof divHTMLPart[1] != "undefined"){
                    divHTMLPart2 = divHTMLPart[1].split('"');
                 }else
                 {
                    var divHTMLPartIE = divHTML.split('id=');
                    divHTMLPart2 = divHTMLPartIE[1].split('>');
                 }
                var idDiv = divHTMLPart2[0];
                var id = idDiv.split('_');
                id = id[id.length - 1];
                var cadenaUrl = "ajax/LeeAccordeon.aspx?id=" + id;
                http.open("GET", cadenaUrl, true);
                http.onreadystatechange = handleHttpResponse;
                enProceso = true;
                http.send(null);
            }
        }
}


function controlLeidosNoLeidos(){

    var acordeonPanes = getElementsByClass("sustituir","node","input");
    for (var i=0;i<inputs.length;i++){
        traeAJAX("actualizacion.aspx", id);
    }

}

//DISPARADORES ASÍNCRONOS
var lugarRecepcion;
function AcuseRecibo(lugarDestino, idUnico)
{  
    
    lugarRecepcion = document.getElementById("recepcionDatosAcuseRecibo_" + idUnico); //div de un globo
    funcionEjecucion = "AcuseRecibo";
    if(lugarRecepcion.innerHTML=="")
    {
        var txtCargando = '<img src="imagen/maqueta/cargando.gif" alt="Icono de carga" style="vertical-align:middle;"> Cargando...';
        cargando(txtCargando);
        traeAJAX("AcuseRecibo.aspx", null, idUnico);
    }
}


//FIN DISPARADORES ASÍNCRONOS

//RESPUESTAS ASÍNCRONAS
function cargando(datos)
{
    if(datos != "")
    {   
        lugarRecepcion.innerHTML = datos;
    }
}

function manejaRespuestaAcuseRecibo(datos)
{
    if(datos != "")
    {   
            var datosPart = datos.split('Principal">');
            var datosPart2 = datosPart[1].substring(0, datosPart[1].length - 9);
            lugarRecepcion.innerHTML = datosPart2;
    }
}


function manejaRespuesta(datos)
{
    if(datos != "")
    {   
        var divContenedor = document.getElementById(coletillaPagina + "datosDetalle");
        var resultadosTemp1 = datos.split("<p>");
        var resultadosTemp2 = resultadosTemp1[1].split("</p>");
        var resultadosTemp3 = resultadosTemp2[0].split("///");

        if(String(resultadosTemp3).indexOf("Accordion: ")==-1){
         //buscamos los campos donde guardar resultados
        var idBanners = resultadosTemp3[0].split("·");
        var idBanner = idBanners[1];
        
        for(var i=0; i<=resultadosTemp3.length - 1; i++)
        {
            var identificadores = resultadosTemp3[i].split("·");
            
            
            //tratamiento de imagen
            var imgPrevia = document.getElementById(coletillaPagina + "bannerI");
            
            if(imgPrevia.id=="principal_columnaIz_" + tabla.toLowerCase() + "I" && identificadores[0].toLowerCase() == tabla.toLowerCase()){
               //encontramos la imagen del form, buscamos también su texto asociado y el titulo legend del fieldset
                imgPrevia.style.display = "block";
                
                var carpetaImgs = tabla.toLowerCase()
                //si resulta que estamos en carrusel, la ruta cambia
                var flag = document.getElementById("principal_columnaIz_modoHerramienta");
                if (typeof(flag) != "undefined")
                {carpetaImgs = flag.value;}
                
                imgPrevia.src= "imagen/maqueta/" + carpetaImgs + "/" + idBanner + identificadores[1];
                imgPrevia.parentNode.parentNode.childNodes[1].innerHTML = identificadores[1];
                imgPrevia.parentNode.parentNode.parentNode.childNodes[0].innerHTML = "Datos de " + identificadores[1];
            }
            
            
            var etiqueta = document.getElementById(coletillaPagina + identificadores[0].toLowerCase());
            if(etiqueta != null){
                if(etiqueta.type=="text" || etiqueta.type=="hidden"){
                        etiqueta.value= identificadores[1];
                }
                if(etiqueta.type=="select-one"){
                        
                        if(identificadores[1]=="True")
                        {
                        
                            if(etiqueta[1].value=="1")
                            {
                                etiqueta[1].selected = true;
                                etiqueta[0].selected = false; 
                            }else if(etiqueta[1].value=="0")
                            {
                                etiqueta[1].selected = false;
                                etiqueta[0].selected = true; 
                            }
                            
                            //etiqueta.selectedIndex = 1; 
                        }
                        else if (identificadores[1]=="False"){
                            
                            if(etiqueta[1].value=="1")
                            {
                                etiqueta[1].selected = false;
                                etiqueta[0].selected = true; 
                            }else if(etiqueta[1].value=="0")
                            {
                                etiqueta[1].selected = true;
                                etiqueta[0].selected = false; 
                            }
                            //etiqueta.selectedIndex = 0; 
                        };
                }
            }
        }
    
        //habilitamos el botón de Anyadir nuevo
        var enlaceNuevoElemento = getElementsByClass("lbNuevo", divContenedor , "a");
        enlaceNuevoElemento[0].style.display = "block";
         //habilitamos los botones de gestión Servicios y Eliminar
        var btnsGestion = document.getElementById("btnsGestion");
        btnsGestion.style.display = "inline-block";
        //tapamos la caja de input file
        var spanMantaRaya = document.getElementById("mantaraya");
        spanMantaRaya.style.display = "block";
        
        }//fin indexOf Accordion:
    }//fin if hay datos

}

//FIN RESPUESTAS ASÍNCRONAS



//Funcion que pone disabled un check de un tree
  function CheckDisabled(idTree)
        {
           var arbolCentros = document.getElementById(idTree);
           var nodosDelArbol = arbolCentros.getElementsByTagName("input");
           
           for(var i=0;i<=nodosDelArbol.length;i++)
           {
           
           //nodosDelArbol[i].tagName == "input" && 
           
           if (nodosDelArbol[i].type == "checkbox")
           {
                nodosDelArbol[i].disabled = true;
                return;
           }
           
           }
           
}

function PonFoco(id) {
    document.getElementById(id).focus();
}


/************************************************
GLOBOS
**************************************************/

function gestionGlobos(lugarClick,altura)
{
    var enlaces = getElementsByClass("clickGlobo",document.getElementById(lugarClick),"a");
    var enlacesG = getElementsByClass("clickGloboG",document.getElementById(lugarClick),"a");
    var enlacesXG =  getElementsByClass("clickGloboXG",document.getElementById(lugarClick),"a");
    var globos = getElementsByClass("haloGlobo",document.getElementById("globos"),"div");
   var equis = getElementsByClass("equisCerrar",document.getElementById("globos"),"a");
    
    //ocultamos todos los globos,los dejamos flotando y le damos altura
    if (globos.length > 0){
        for(var i = 0;i<globos.length;i++)
        {
            globos[i].style.position = 'absolute';
            globos[i].style.display = 'none';
            
            var blancoGlobo = getElementsByClass("globo",globos[i],"div");
            //blancoGlobo[0].style.height = altura + "px";
            //blancoGlobo[0].firstChild.style.height = altura + "px";
        }
    }
    
    //creamos la funcionalidad de los enlaces
    if (enlaces.length > 0){
           funcionalidadEnlaces(enlaces, "normal");
    }
    
      if (enlacesG.length > 0){
           funcionalidadEnlaces(enlacesG, "grande");
    }
     if (enlacesXG.length > 0){
           funcionalidadEnlaces(enlacesXG, "extragrande");
    }
        //creamos la funcionalidad de cierre de las equis
         if (equis.length > 0){
            for(i = 0;i<equis.length;i++)
            {
                equis[i].onclick = function(){
                    
                    this.parentNode.style.display = 'none';
                    return false;
                }
             }
        } 
}


function funcionalidadEnlaces(enlaces, tamanyo)
{
     for(i = 0;i<enlaces.length;i++)
            {
                enlaces[i].onclick = function(){
                    var sIdEnlace = this.id;
                    var vIdEnlace = sIdEnlace.split("_");
                    
                    var posLeft = findPosition(this, "X");
                    var posTop = findPosition(this, "Y");
                    
                    var globoAbrir = document.getElementById("globo_" + vIdEnlace[1]);
                    
                    if(globoAbrir != null)
                    {
                        if(globoAbrir.style.display == ''){
                            globoAbrir.style.display = 'none'; 
                        }else{
                            var tope = (parseInt(posTop) + 20) + "px";
                            var izquie = (parseInt(posLeft)) + "px";
                            globoAbrir.style.display = '';
                            globoAbrir.style.position = 'absolute';
                            globoAbrir.style.left = izquie;
                            globoAbrir.style.top = tope;
                        }
                        var globoDibujado;
                        var contenidoGlobo;
                        var equisGlobo;
                        
                        if(tamanyo=="grande"){
                            globoDibujado = getElementsByClass("globo",globoAbrir,"div");
                            contenidoGlobo = getElementsByClass("contenidoGlobo",globoDibujado[0],"div");
                            globoDibujado[0].style.height = "290px";
                            contenidoGlobo[0].style.height = "270px";
                        }
                        
                        if(tamanyo=="extragrande"){
                            globoDibujado = getElementsByClass("globo",globoAbrir,"div");
                            contenidoGlobo = getElementsByClass("contenidoGlobo",globoDibujado[0],"div");
                            globoDibujado[0].style.height = "290px";
                            contenidoGlobo[0].style.height = "270px";
                            contenidoGlobo[0].style.width = "580px";
                            globoDibujado[0].style.width = "600px";
                            globoAbrir.style.width = "700px";
                            
                            equisGlobo = getElementsByClass("equisCerrar",globoAbrir,"a");
                            equisGlobo[0].style.left = "710px";
                        }
                        
                    }

                    if(this.id.indexOf("acuseRecibo")>=0)
                    {
                        AcuseRecibo(globoAbrir, vIdEnlace[1]);
                    }
                    
                    return false;
                
                }
            }

}

//devuelve las coordenadas de un objeto incluso en IE7.
function findPosition( oElement, RequiredCoordinate ) {
    //if XY returns o/p asarray obj else as string
    requestedCo="XY";
    if( RequiredCoordinate ){
    if( RequiredCoordinate=="X" ) requestedCo="X";
    else if( RequiredCoordinate=="Y" ) requestedCo="Y";
    else requestedCo="XY";
    }else requestedCo="XY";

    if( typeof( oElement.offsetParent ) != 'undefined' ) {
        for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
            posX += oElement.offsetLeft;
            posY += oElement.offsetTop;
        }

        if( requestedCo=="X" ) return(posX);
        else if( requestedCo=="Y" ) return(posY);
        else return [ posX, posY ];


    } else {
        if( requestedCo=="X" ) return(oElement.x);
        else if( requestedCo=="Y" ) return(oElement.y);
        else return [ oElement.x, oElement.y ];
    }
} 

/*******************************************************************
Carrusel - Mootools eventos DOM para rotar "En UNED Barbastro"
********************************************************************/

if(typeof(MooTools)!="undefined"){

window.addEvent('domready',function() {
	var scroll = new Fx.Scroll('scroll_container_inner', {
			wait: false,
			duration: 800,
			transition: Fx.Transitions.Cubic.easeInOut
	});
	var arrayScrollingContent = $$('.scroll_section');
	var numberofitems = arrayScrollingContent.length;
	var currentItem = 0;
	for (var i=0; i<numberofitems; i++) {
		var scroll_placement = $('scroll_placement');
		var my_img = new Element('img', {'src': '/images/otsw/scroll_placement_button_off.gif', 'class': 'scroll_button' }).injectInside(scroll_placement);		
	};
	var arrayScrollPlacement = $$('.scroll_button');
	if(arrayScrollPlacement[0] != null){
	
	arrayScrollPlacement[0].setProperty('src', '/images/otsw/scroll_placement_button_on.gif');
	$('scroll_right_shift').addEvent('click', function(event) {
		event = new Event(event).stop();
		currentItem = currentItem + 1;
		if (currentItem > arrayScrollingContent.length - 1) { 
			(currentItem = 0) }; 
		arrayScrollPlacement.setProperty('src', '/images/otsw/scroll_placement_button_off.gif');
		arrayScrollPlacement[currentItem].setProperty('src', '/images/otsw/scroll_placement_button_on.gif');
		scroll.toElement(arrayScrollingContent[currentItem]);
	});
	$('flechaIzScroll').addEvent('click', function(event) {
		event = new Event(event).stop();
		currentItem = currentItem - 1;
		if (currentItem < 0) { 
			(currentItem = 0) };
		arrayScrollPlacement.setProperty('src', '/images/otsw/scroll_placement_button_off.gif');
		arrayScrollPlacement[currentItem].setProperty('src', '/images/otsw/scroll_placement_button_on.gif');
		scroll.toElement(arrayScrollingContent[currentItem]);	
	});
	
	}
	
});

}

/*******************************************************************
Arrastrar y soltar
********************************************************************/

// Variables globales
var indiceZ=0; 
var posElInicial=new Array();
var posElFinal=new Array();
var posEls=new Array();
var posMouseInicial=new Array();
var elEnMov=null;

//globales de los elementos
var coletillaPagina = "principal_columnaIz_"
var tipoElementoArrastrable = "img";
var idElementoArrastrable = coletillaPagina + "arrastra";
var classElementoArrastrable = "arrastrable";
var idPadreElementoArrastrable = "seccionArrastrable"

//var globales actualizaciones ajax
var tipo = "";
var tabla = "";
var campo = "";

// Cargo las posiciones de las capas en el documento
onload=bannerArrastraSuelta;
onresize=posElsAbs;

// Detecto el navegador
if(navigator.userAgent.indexOf("MSIE")>=0) navegador=0; // IE
else navegador=1; // Otros

function delay() 
{ 
	/* 
	En IE sin un pequeño delay parece haber problemas con la captura de las posiciones de las capas. Lo extraño es que no siempre sucede por lo que este retraso puede no ser necesario.
	*/
}

function bannerArrastraSuelta()/*inicial*/
{
    posElsAbs();
    interfazNuevoElemento();
}

function interfazNuevoElemento()
{


    //comprobamos que el formulario no esté vacio
     var pBtnsGuardar = document.getElementById("btnsGuardar");
     if(typeof ptBtnsGuardar !="undefined")
     {
        if(pBtnsGuardar.firstChild.value == "0")
        {
           crearFormularioAdd(); 
        }
    }

    //var fieldset = document.getElementById("campos");
    //fieldset.style.display = "block";
    var divContenedor = document.getElementById(coletillaPagina + "datosDetalle");
    var enlacenuevo = getElementsByClass("lbNuevo", divContenedor, "a");    
    if(enlacenuevo.length > 0)
    {
            enlacenuevo[0].onclick = function(){
            crearFormularioAdd();
            return false;
        }
    }
    
}

function crearFormularioAdd()
{

    var divContenedor = document.getElementById(coletillaPagina + "datosDetalle");
    var inputs = divContenedor.getElementsByTagName("input");
    for(var i=0; i<=inputs.length - 2; i++)
    {
        inputs[i].value="";
    }

    var selects = divContenedor.getElementsByTagName("select");
    for(var j=0;j<=selects.length - 1;j++)
    {
        selects[j][0].selected=true;
    }

    //cambiamos la imagen por una caja de subida de archivos
    var pImgBanner = document.getElementById("imgBanner");

    var pTxtImgBanner = document.getElementById("txtImgBanner");
    pTxtImgBanner.innerHTML = "";

    //pImgBanner.removeChild(pImgBanner.childNodes[0]);

    pImgBanner.childNodes[2].style.display = "none";
    pImgBanner.childNodes[1].style.display = "block";

    //ocultamos la caja que enmascara el input file
    var spanMantaRaya = document.getElementById("mantaraya");
    spanMantaRaya.style.display = "none";

    /*var nuevoFile = document.createElement("input");
    nuevoFile.type= "file";
    nuevoFile.name = "image"
    pImgBanner.appendChild(nuevoFile);*/



    //cambiamos el texto del botón
    var pBtnsGuardar = document.getElementById("btnsGuardar");
    //pBtnsGuardar.firstChild.text; hidden field
    pBtnsGuardar.childNodes[1].value = "Guardar datos";


    //ponemos el hiddenfield a 0 para indicar que es nuevo
    pBtnsGuardar.firstChild.value = "0";

    //cambiamos el legend
    var legend = divContenedor.getElementsByTagName("legend");
    legend[0].innerHTML = "Añadir nuevo elemento";

    //inhabilitamos el propio botón que ha generado este evento (Anyadir nuevo)
    var enlaceNuevoElemento = getElementsByClass("lbNuevo", divContenedor , "a");
    enlaceNuevoElemento[0].style.display = "none";

    //inhabilitamos los botones de gestión Servicios y Eliminar
    var btnsGestion = document.getElementById("btnsGestion");
    btnsGestion.style.display = "none";

}


function posElsAbs() 
{
	/*
	funcion: almacenar las posiciones absolutas de los elementos movibles de la pagina
	parametros:
	retorno:
	*/
	setTimeout("delay()", 200);
	var divContenedor = document.getElementById(idPadreElementoArrastrable);
	var el=getElementsByClass(classElementoArrastrable,divContenedor,tipoElementoArrastrable);
	var i=0;
	while(el[i])
	{

		if(el[i].id.substr(0, idElementoArrastrable.length)==idElementoArrastrable)
		{
		    
			el[i].onmousedown=inicioMov;
			posEls[el[i].id]=posElAbs(el[i].id);
		}
		i++;
	}
}

function noEventos(event)
{
	if(navegador==0)
	{
		window.event.cancelBubble=true;
		window.event.returnValue=false;
	}
	if(navegador==1) event.preventDefault();
}

function getEl(idEl) 
{
	/*
	funcion: devolver el elemento cuyo id se recibe
	parametros: (string) id de elemento
	retorno: (objeto) elemento cuyo id se recibe
	*/
	return document.getElementById(idEl); 
}

function copiaArr(arr) 
{ 
	/*
	funcion: devolver una copia exacta del array que se recibe por parametro
	parametros: (array) array a copiar
	retorno: (array) duplicado del array recibido
	*/
	var tArr=new Array();
	for(var n in arr) tArr[n]=arr[n];
	return tArr;
}

function posMouse(event)
{
	/*
	funcion: devolver la posicion del puntero en un momento determinado
	parametros: (objeto) objeto event
	retorno: (array=>["x"] - ["y"]) posicion del puntero
	*/
	var pos=new Array();
	if(navegador==0)
	{
		/* document.body.clientLeft/clientTop es el tamaño del borde (usualmente 2px) que
		encierra al documento ya que en IE este no empieza en (0,0) */
	 	pos["x"]=window.event.clientX+document.body.clientLeft+document.body.scrollLeft;
		pos["y"]=window.event.clientY+document.body.clientTop+document.body.scrollTop;
	}
	if(navegador==1)
	{
		pos["x"]=event.clientX+window.pageXOffset;
		pos["y"]=event.clientY+window.pageYOffset;
	}
	return pos;
}

function posElAbs(idEl)
{
	/*
	funcion: devolver la posicion del elemento con respecto a los bordes del documento
	parametros: (string) id del elemento
	retorno: (array=>["xInicial"] - ["xFinal"] - ["yInicial"] - ["yFinal"]) posicion del elemento
	*/
	var el=elP=getEl(idEl);
	var pos=new Array();
	pos["xInicial"]=pos["yInicial"]=pos["xFinal"]=pos["yFinal"]=0;
	
	do
	{
		pos["xInicial"]+=elP.offsetLeft;
		pos["yInicial"]+=elP.offsetTop;
		elP=elP.offsetParent;
	} while(elP);

	pos["xFinal"]=el.offsetWidth+pos["xInicial"];
	pos["yFinal"]=el.offsetHeight+pos["yInicial"];

	return pos;
}

function posElRel(idEl)
{
	/*
	funcion: devolver la posicion del elemento con respecto a su contenedor (left y top)
	parametros: (string) id del elemento
	retorno: (array=>["x"] - ["y"]) posicion del elemento
	*/
	var el=getEl(idEl);
	var pos=new Array();
	pos["x"]=parseInt(el.style.left);
	pos["y"]=parseInt(el.style.top);
	return pos;
}

function reOrdena(posMouse)
{
    
	for(var idEl in posEls)
	{
		if(idEl!=elEnMov.id)
		{
			if(posMouse["x"]>=posEls[idEl]["xInicial"] && posMouse["x"]<=posEls[idEl]["xFinal"] &&
			posMouse["y"]>=posEls[idEl]["yInicial"] && posMouse["y"]<=posEls[idEl]["yFinal"]) 
			{
				// La capa cuyo id es idEl debe posicionarse en la posicion de comienzo de la capa en movimiento
				var el=getEl(idEl);
				
				// Intercambio la posicion de la capa estatica por la posicion final de la capa en movimiento
				var temp=new Array();
				temp["x"]=parseInt(el.style.left);
				temp["y"]=parseInt(el.style.top);
				el.style.left=posElFinal["x"]+"px";
				el.style.top=posElFinal["y"]+"px";
				posElFinal=copiaArr(temp);
				
				// Cambio los valores de posicion de la capa estatica y la capa en movimiento en el array de posiciones
				var temp1=new Array();
				temp1=copiaArr(posEls[elEnMov.id]);
				posEls[elEnMov.id]=copiaArr(posEls[idEl]);
				posEls[idEl]=copiaArr(temp1);
			}
		}
		
	}
	
	
}

function inicioMov(event)
{
	if(navegador==0)
	{
	 	elEnMov=window.event.srcElement;
		
		document.attachEvent("onmousemove", enMov);
		document.attachEvent("onmouseup", finMov);
	}
	if(navegador==1)
	{
		elEnMov=event.target;
		
		document.addEventListener("mousemove", enMov, true);
		document.addEventListener("mouseup", finMov, true);
	}

	posElInicial=posElRel(elEnMov.id);
	posMouseInicial=posMouse(event);
	posElFinal=copiaArr(posElInicial);
	
	
	elEnMov.style.zIndex=++indiceZ;
	noEventos(event);
}

function enMov(event)
{	 
	var pos=posMouse(event);
	reOrdena(pos);
	
	elEnMov.style.left=posElInicial["x"]+pos["x"]-posMouseInicial["x"]+"px";
	elEnMov.style.top=posElInicial["y"]+pos["y"]-posMouseInicial["y"]+"px";
	
	noEventos(event);
}

function finMov(event)
{
	//viajo a la bd y actualizo el campo ORDEN
	
	
	elEnMov.style.left=posElFinal["x"]+"px";
	elEnMov.style.top=posElFinal["y"]+"px";
	
	if(navegador==0)
	{    
		document.detachEvent("onmousemove", enMov);
		document.detachEvent("onmouseup", finMov);
	}
	if(navegador==1)
	{
		document.removeEventListener("mousemove", enMov, true);
		document.removeEventListener("mouseup", finMov, true); 
	}
	
	tabla="BANNER";
	campo="ORDEN";
	tipo="ordenacion";
	actualizaCampos();
}


function actualizaCampos()
{
    //comprobamos el eje 'y' y actualizamos en la BD
    if (tipo=="ordenacion")
    {
        
        var  posicionesFinales = new Array();
        
        var stringDeIds = "";
        
        var divContenedor = document.getElementById(idPadreElementoArrastrable);
	    var el=getElementsByClass(classElementoArrastrable,divContenedor,tipoElementoArrastrable);
	    
        for (var i=0; i<=el.length - 1; i++)
        {
           posicionesFinales[i] = new Array(parseInt(el[i].id.substr(idElementoArrastrable.length, el[i].id.length)), parseInt(el[i].style.top.substr(0, el[i].style.top.length-2)));
          
            //stringDeIds += el[i].id.substr(8, el[i].id.length) + ",";
        }
        
         posicionesFinales.sort(sortPorId);
         
         //pasamos el array ordenado a una cadena
         var cadenaIds = "" 
         for(i=0; i<=posicionesFinales.length - 1; i++){
         
            cadenaIds += posicionesFinales[i][0] + ",";
         
         }
         
        traeAJAX("actualizacion.aspx", cadenaIds.substr(0,cadenaIds.length - 1), elEnMov.id.substr(idElementoArrastrable.length, elEnMov.id.length), tipo, tabla, campo);
         
   }
    
}

function sortPorId(a, b) {
    var x = a[1];
    var y = b[1];
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function anularSelectDondeMostrar()
{
var fullbanner= document.getElementById('principal_columnaIz_fullbanner');
var dondeMostrar = document.getElementById('principal_columnaIz_dondemostrar');

if(fullbanner!=null && dondeMostrar!=null){
    fullbanner.onchange = function(){
            if(fullbanner.selectedIndex==1){dondeMostrar.disabled =true;}else{dondeMostrar.disabled =false;}
    }

}

}

//google analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-19262661-1']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();



//control DNI/NIE/Pasaporte
 function controlCheckBoxes()
    {   
       var rbNIF = document.getElementById("principal_columnaIz_rbNIF");
       var rbNIE = document.getElementById("principal_columnaIz_rbNIE");
        
        var tbNIF = document.getElementById("principal_columnaIz_tbNIF");
        var tbLetra = document.getElementById("principal_columnaIz_tbLetra");
         var tbNIE = document.getElementById("principal_columnaIz_tbNIE");
        
        if(tbNIE.value != ""){
            tbNIF.disabled = true;
            tbLetra.disabled = true;
            tbNIE.disabled = false;
            
        }else
        {
           tbNIF.disabled = false;
           tbLetra.disabled = false;
           tbNIE.disabled = true;
        }
        
        
        
        rbNIF.onclick = function(){
            controlaEstadoNIF();
        }
        rbNIE.onclick = function(){
            controlaEstadoNIE();
        }

    }

    function controlaEstadoNIF()
    {
        var tbNIF = document.getElementById("principal_columnaIz_tbNIF");
        var tbLetra = document.getElementById("principal_columnaIz_tbLetra");
        var tbNIE = document.getElementById("principal_columnaIz_tbNIE");
        
        tbNIF.disabled = false;
        tbLetra.disabled = false;
        tbNIE.disabled = true;
        tbNIE.value = "";
    }
    function controlaEstadoNIE()
    {
        var tbNIF = document.getElementById("principal_columnaIz_tbNIF");
        var tbLetra = document.getElementById("principal_columnaIz_tbLetra");
        var tbNIE = document.getElementById("principal_columnaIz_tbNIE");
        tbNIE.disabled = false;
        tbNIF.disabled = true;
        tbLetra.disabled = true;
        tbNIF.value = "";
        tbLetra.value = "";
    }

    function compruebaCIF(source, arguments) {
    /*A - Sociedad Anónima.
        'B - Sociedad de responsabilidad limitada.
        'C - Sociedad colectiva.
        'D - Sociedad comanditaria.
        'E - Comunidad de bienes.
        'F - Sociedad cooperativa.
        'G - Asociación.
        'H - Comunidad de propietarios.
        'K - Formato antiguo.
        'L - Formato antiguo.
        'M - Formato antiguo.
        'N - Formato antiguo.
        'P - Corporación local.
        'Q - Organismo autónomo
        'S - Organo de la administración.*/
        var cif = source;
        cif = cif.toUpperCase();
        if (cif.length == 9) {
            var sTipoEmpresa = cif.substring(0, 1);
            var sCif = cif.substring(1, 8);
            var sControl = cif.substring(8, 9);

            if ((sTipoEmpresa == "A" || sTipoEmpresa == "B" || sTipoEmpresa == "C" || sTipoEmpresa == "D" || sTipoEmpresa == "E" || sTipoEmpresa == "F" || sTipoEmpresa == "G" || sTipoEmpresa == "H" || sTipoEmpresa == "K" || sTipoEmpresa == "L" || sTipoEmpresa == "M" || sTipoEmpresa == "N" || sTipoEmpresa == "P" || sTipoEmpresa == "Q" || sTipoEmpresa == "S") && IsNumeric(sCif)) {
                var A = 0;
                var B = 0;
                var B1 = 0;
                var sB1 = "";
                var C = 0;
                var sLetraControl = "";
                
                var x = 0;
                for (x = 0; x < sCif.length; x++) {                                     
                    if(x % 2 == 0){ //Si es 0, son los impare, si es 1 son los pares
                       B1 = sCif[x] * 2;
                       sB1 = B1 + "";                       
                       var y = 0;
                       for (y = 0; y < sB1.length; y++) {
                           B += parseInt(sB1[y]);                           
                       }//fin for                                                 
                    }else{
                        A += parseInt(sCif[x]);
                    }//fin par o impar
                } //fin for
                C = A + B;
                sB1 = C + "";
                C = 10 - parseInt(sB1[sB1.length - 1]);
                switch (C) { 
                    case 1:{sLetraControl = "A"; break }
                    case 2:{sLetraControl = "B"; break }
                    case 3:{sLetraControl = "C"; break }
                    case 4:{sLetraControl = "D"; break }
                    case 5:{sLetraControl = "E"; break }
                    case 6:{sLetraControl = "F"; break }
                    case 7:{sLetraControl = "G"; break }
                    case 8:{sLetraControl = "H"; break }
                    case 9:{sLetraControl = "I"; break }
                    case 0:{sLetraControl = "J"; break }
                }
                if (sLetraControl == sControl || C == sControl) {                    
                    arguments.isValid=true;}
            }            
        }        
        arguments.isValid = false;
    }

    function IsNumeric(input) {
        return (input - 0) == input && input.length > 0;
    }
    
    
    
function abrirVentanaReproductorVideo()

{
	window.open('Player.html','window','HEIGHT=370,resizable=yes,WIDTH=350');

}


