//Parte lógica para el uso de caso "Interactuar con el Message Board"
 var catForm;
 var folders = new Array(1);
 var ims = new Array(4);
 var ie = false;


 for(var i=0;i<ims.length;i++)
  ims[i] = new Image();

 ims[0].src = path + "/board/images/bup2.gif";
 ims[1].src = path + "/board/images/bdown.gif"; 
 ims[2].src = path + "/images/add.gif";
 ims[3].src = path + "/images/add_on.gif";

function writeRule(){
  var str = navigator.userAgent.toLowerCase();
  var browserVersion = (document.all)?getIEVersion(str):parseInt(navigator.appVersion);
 
  ie = isIE();
  var ch = (str.indexOf("msie")>-1 && browserVersion<7) || (str.indexOf("opera")>-1 && parseInt(navigator.appVersion)<9);

   document.open();
   document.writeln('<sty' + 'le media="all" type="text/css">');
   document.writeln('.section{');
   document.writeln('width:621px;');
   document.writeln('margin:' + ((ch)?'-10':'0') + 'px 0px 0px 94px;');
   document.writeln('}');
   document.writeln('</sty' + 'le>');
   document.close();
}

function showCatForm(flag){

     if(!catForm)
       catForm = $("newcat").cloneNode(true);

    if(id_folder!="newcat"){
       closeFolder(false);
       id_folder = "newcat";
    }

    $("arncat").src = path + "/board/images/bdown2.gif";
    $("anecat").setAttribute("href","javascript:hideCatForm(" + flag + ");void(0);");
    $("anecat").setAttribute("title","Clic para ocultar.");


    var _rdiv = document.createElement("div");
                _rdiv.setAttribute("id","newcat");
                _rdiv.setAttribute((ie ?"className":"class"),"section espa");
                _rdiv.style.height = "460px";
		_rdiv.style.borderLeftWidth = "1px";
		_rdiv.style.borderLeftStyle = "solid";
		_rdiv.style.borderLeftColor= "#666";
   var p = document.createElement("p");  

       p.setAttribute((ie ?"className":"class"),"des1");
       p.appendChild(document.createTextNode("Antes de agregar una nueva categoría, deberá considerar primero los siguientes aspectos:"));
      _rdiv.appendChild(p);
       var ul = createUL(new Array("La categoría debe estar relacionada con temas afines al E-marketing o a nuestro sitio o temas que traten sobre su sitio web, pero que no sean de caracter publicitario.","Las palabras o términos usados no pueden ser ofensivos o vulgares o que traten sobre sexo, violencia y/o cualquiera que se asimile.","La categoría que usted agregue con su respectivo mensaje y comentario (sí aplica), estará sujeta a una verificación en un tiempo de dos días como máximo para ser publicada y resuelta. Nos reservaremos en cualquier caso su derecho de aprobación.","El mensaje aquí redactado deberá ser realmente considerado como para una categoría nueva.","Una vez sea aprobado se le mandará por el email, que nos suministre a continuación, una confirmación de su aprobación."));
       var form = createForm(true);

         if(!form || !ul){
             alert("Ocurrio un error mientras se trataba de visualizar el formulario. Solicitamos sus disculpas.");
             return;
          }

        _rdiv.appendChild(ul);
        _rdiv.appendChild(form);

       $("newcat").parentNode.replaceChild(_rdiv,$("newcat"));
      
}

function hideCatForm(flag){

 if(catForm){
    $("arncat").src = path + "/board/images/bup2.gif";
    $("anecat").setAttribute("href","javascript:showCatForm(" + flag + ");void(0);");
    $("anecat").setAttribute("title","Clic para agregar una nueva categoria");

    $("newcat").parentNode.replaceChild(catForm,$("newcat"));
 
 }
 else{
    alert("Error al tratar de ocultar el formulario de creacion nueva categoria.");
 }
}


function showFields(id,cat){

 if(id>0 && !$("dc")){ //Mostrar todos los campos involucrados
 try{
     if(cat)$("newcat").style.height= "600px";

    var span = document.createElement("span");
        span.setAttribute("id","nf1");
    var label = document.createElement("label");
        label.appendChild(document.createTextNode("Tipo comentario:"));
        span.appendChild(label);
    var select = document.createElement("select");
        select.setAttribute("size","1");
        select.setAttribute("id","typc"); 
        select.setAttribute("name","typecomment");  
    var option = document.createElement("option");
        option.setAttribute("value","Observación");
        option.appendChild(document.createTextNode("Observación"));
        select.appendChild(option);

         option = document.createElement("option");
         option.setAttribute("value","Respuesta");
         option.appendChild(document.createTextNode("Respuesta"));
         select.appendChild(option);

         option = document.createElement("option");
         option.setAttribute("value","Crítica");
         option.appendChild(document.createTextNode("Crítica"));
         select.appendChild(option); 

         option = document.createElement("option");
         option.setAttribute("value","Consejo");
         option.appendChild(document.createTextNode("Consejo"));
         select.appendChild(option);

         option = document.createElement("option");
         option.setAttribute("value","Pensamiento");
         option.appendChild(document.createTextNode("Pensamiento"));
         select.appendChild(option);
  
         option = document.createElement("option");
         option.setAttribute("value","Sugerencia");
         option.appendChild(document.createTextNode("Sugerencia"));
         select.appendChild(option);

         option = document.createElement("option");
         option.setAttribute("value","Queja");
         option.appendChild(document.createTextNode("Queja"));
         select.appendChild(option);

         option = document.createElement("option");
         option.setAttribute("value","Pregunta");
         option.appendChild(document.createTextNode("Pregunta"));
         select.appendChild(option);

         option = document.createElement("option");
         option.setAttribute("value","Duda");
         option.appendChild(document.createTextNode("Duda"));
         select.appendChild(option);

         span.appendChild(select);
         $("data").insertBefore(span,$("limg"));

         span = document.createElement("span");
         span.setAttribute("id","nf2");
         label = document.createElement("label");
         label.setAttribute((ie ?"className":"class"),"ftl lab2");
         label.appendChild(document.createTextNode("Redacción comentario:"));
         span.appendChild(label);
         var textarea = document.createElement("textarea");
             textarea.setAttribute("id","dc");
             textarea.setAttribute("name","descomment");
         span.appendChild(textarea);

        $("data").insertBefore(span,$("limg")); 

   }catch(msg){
       alert("Ocurrio el siguiente error: " + msg.message);
   } 
 }
 else if(id==0){ //esconder los campos concernientes a comentario
   try{
    $("data").removeChild($("nf2"));
    $("data").removeChild($("nf1"));
    if(cat)$("newcat").style.height = "460px";
   }
   catch(msg){
       alert("No fueron posible ocultar los campos acerca del comentario. Error: " + msg.message);
   }
 }
}

function sendData(){
   //Validar informacion
   if(!p9.test($("name").value)){
       $("name").focus();
       $("name").select();
       alert("Debe diligenciar correctamente su nombre y apellido. Gracias.");
   }
   else if(!p7.test($("nickname").value) || $("nickname").value.length>20){
       $("nickname").focus();
       $("nickname").select();
       alert("Debe diligenciar correctamente su alias. Este es el nombre que saldra visible en el tablon de mensajes. No puede contener espacios  o caracteres especiales. Este campo podra contener entre 5 a 20 caracteres. Gracias.");
   }
   else if(!p2.test($("email").value)){
       $("email").focus();
       $("email").select();
       alert("Debe diligenciar correctamente su correo electronico. Gracias.");
   }
   else if( $("category") && !p9.test($("category").value) ){
       $("category").focus();
       $("category").select();
       alert("Debe especificarnos la nueva categoria bien diligenciada o reducir caracteres. Este nombre es el que aparecera en el inicio de la carpeta. No podrá ser mayor de 30 caracteres y debera contener solo letras. Gracias.");
   }
   else if($("dtheme") && (!p5.test($("dtheme").value))){
      $("dtheme").focus();
       $("dtheme").select();
       alert("Debe diligenciarnos correctamente el titulo del mensaje. Este es la pregunta o titulo o encabezado de lo que se quiere expresar. No se extienda mucho y sea breve. Gracias.");
   }
   else if($("dc") && $("dc").value.length<20){
       $("dc").focus();
       $("dc").select();
       alert("Este campo debe ser diligenciado con mas palabras. Este campo es el contenido y el soporte del titulo de mensaje especificado. Gracias.");
   }
   else{
      //Crear cookie informativo de almacenamiento de datos
      if(!getCookie("datauser")){
           createCookie("datauser",$("name").value, $("nickname").value, $("email").value);
       }
      else{
       //Verificar datos del cookie y sí son diferentes cambiarlos
        var cookie = getCookie("datauser");
        var change = false;

         if(cookie[0].toLowerCase() != $("name").value.toLowerCase()){cookie[0] = $("name").value;change=true;}
         if(cookie[1].toLowerCase() != $("nickname").value.toLowerCase()){cookie[1] = $("nickname").value;change=true;}
         if(cookie[2].toLowerCase() != $("email").value.toLowerCase()){cookie[2] = $("email").value;change=true;}

         if(change)createCookie("datauser",cookie[0],cookie[1],cookie[2]);
      }

       $("data").method = "post";
       $("data").action = path + "/msgboard.do?codigo=23";
       $("data").submit();
   }
}

function addSubject(id_folder){
  if(!$("data")){
    var table = $(id_folder).getElementsByTagName("table")[0];
   
      if(!table){
           alert("No fue posible mostrar formulario para agregar el tema por un error interno. Solicitamos sus disculpas.");
       }
      else{
          try{
              var tbody = table.getElementsByTagName("tbody")[0];
              var del = tbody.removeChild(tbody.lastChild);
              if(!del || (del.nodeType==3 && $("addsub")) )tbody.removeChild($("addsub"));

              var p = document.createElement("p");  
                  p.setAttribute((ie ?"className":"class"),"des1");
                  p.appendChild(document.createTextNode("Antes de agregar un nuevo tema deberá considerar los siguientes aspectos:"));
                  $(id_folder).appendChild(p);
                  var ul = createUL(new Array("Las palabras usadas no pueden ser ofensivas o vulgares o traten de temas prohibidos como sexo, violencia y/o cualquiera que se asimile.","El respectivo tema que usted agregue y comentario (si aplica), estará sujeto a una verificación en un tiempo promedio de dos días como máximo para ser publicado y/o resuelto. Nos reservaremos en cualquier caso su derecho de aprobación y/o inclusión.","Una vez sea aprobado se le mandara por email su confirmacion a los datos que usted nos suministre a continuacion, los cuales gozaran del derecho de privacidad y confidencialidad de datos."));
                  var form = createForm(false,id_folder.substring((id_folder.indexOf("n")+1)));

                     if(!ul || !form){
                       alert("Ocurrio un error mientras se trataba de visualizar el formulario para agregar temas. Solicitamos sus disculpas.");
                       return;
                     }

                 $(id_folder).appendChild(ul);
                 $(id_folder).appendChild(form);

           }
          catch(msg){
              alert("No fue posible visualizar el formulario por que el visualizador no soporto esta funcion. Expresamos nuestras disculpas, gracias por su comprension. Error causado: " + msg.message);
          }
      }
   }
}


function createForm(cat,idcat){

  try{
        var cookie = getCookie("datauser");
        var form = document.createElement("form");   
            form.setAttribute("id","data");
        var span = document.createElement("span");
        var label = document.createElement("label");
        var input = document.createElement("input");
        label.appendChild(document.createTextNode("Nombre y Apellido:"));  
        input.setAttribute("type","text");
        input.setAttribute("name","nas");
        input.setAttribute("id","name");
        if(cookie)input.setAttribute("value",cookie[0]);
        span.appendChild(label);
        span.appendChild(input);
        form.appendChild(span);

        span = document.createElement("span");
        label = document.createElement("label");
        input = document.createElement("input");
        label.appendChild(document.createTextNode("Su alias:"));  
        input.setAttribute("type","text");
        input.setAttribute("name","nn");
        input.setAttribute("id","nickname");
        if(cookie)input.setAttribute("value",cookie[1]);
        span.appendChild(label);
        span.appendChild(input);
        form.appendChild(span);

        span = document.createElement("span");
        label = document.createElement("label");
        input = document.createElement("input");
        label.appendChild(document.createTextNode("E-mail:"));  
        input.setAttribute("type","text");
        input.setAttribute("name","eml");
        input.setAttribute("id","email");
        if(cookie)input.setAttribute("value",cookie[2]);
        span.appendChild(label);
        span.appendChild(input);
        form.appendChild(span);

        if(cat){
          span = document.createElement("span");
          label = document.createElement("label");
          input = document.createElement("input");
          label.appendChild(document.createTextNode("Nombre Categoría:"));  
          input.setAttribute("type","text");
          input.setAttribute("name","cty");
          input.setAttribute("id","category");  
          if(ie){input.setAttribute("maxLength",30);}else{input.setAttribute("maxlength","30");};
          span.appendChild(label);
          span.appendChild(input);
          form.appendChild(span);
        }
        else{
           input = document.createElement("input");
           input.setAttribute("type","hidden");
           input.setAttribute("name","id_cat");
           input.setAttribute("value",idcat);
           form.appendChild(input);
        } 

        span = document.createElement("span");
        label = document.createElement("label");
        label.appendChild(document.createTextNode("Tipo mensaje:"));
        var select = document.createElement("select");
        select.setAttribute("size","1");   
        select.setAttribute("id","typm");
        select.setAttribute("name","typemsg");
        var option = document.createElement("option");
          option.setAttribute("value","Pregunta");
          option.appendChild(document.createTextNode("Pregunta"));
        select.appendChild(option); 
          option = document.createElement("option");
          option.setAttribute("value","Opinion");
          option.appendChild(document.createTextNode("Opinion"));
        select.appendChild(option); 

          option = document.createElement("option");
          option.setAttribute("value","Varios");
          option.appendChild(document.createTextNode("Varios"));
        select.appendChild(option); 
      
         select.selectedIndex = 0;
         select.onchange = function(){showFields(this.selectedIndex,cat);};

         span.appendChild(label);
         span.appendChild(select); 
         form.appendChild(span)

        span = document.createElement("span");
        label = document.createElement("label");
                label.setAttribute((ie ?"className":"class"),"ftl lab1");
        label.appendChild(document.createTextNode("Título del mensaje:"));
       var textarea = document.createElement("textarea");
           textarea.setAttribute("id","dtheme");
           textarea.setAttribute("name","destheme");
        span.appendChild(label);
        span.appendChild(textarea);
        form.appendChild(span);

       var a = document.createElement("a");
           a.setAttribute("href","javascript:sendData();void(0);");
           a.setAttribute("id","limg");
           a.setAttribute("title","Clic para agregar una categoria");
       var img = document.createElement("img");
           img.setAttribute("id","btun");
           img.setAttribute("src",path + "/images/add.gif");
           img.setAttribute("alt","agregar");
           a.appendChild(img);
          form.appendChild(a);

        var button1 =new Bobj(img,"images/add");
          
          return form;
      }
      catch(msg){
         return null;
      }
}

function openFolder(id_new){
    var id = parseInt(id_new.substring(id_new.indexOf("n")+1));

       if(id_folder != id_new){
         closeFolder(false);
         id_folder = id_new;
       }

    $("ig" + id).src = ((id_new=="sctn1")?ims[1].src:path + "/board/images/bdown2.gif");
    $("anc" + id).setAttribute("href","javascript:closeFolder(" + (id_new=="sctn1") + ");void(0);"); 
    $("anc" + id).setAttribute("title","Clic para ocultar.");

     if( (id-1) < folders.length && folders[id-1]){
         $(id_new).parentNode.replaceChild(folders[id-1],$(id_new));
         var form = $("data");
            if(form){
                var select = $("typm");
                select.onchange = function(){showFields(this.selectedIndex,false);};
                var button1 =new Bobj($("btun"),"images/add");
            }  
     }
     else{
       //Armar nueva capa y traer imagen de division
       var im = document.createElement("img"); 
           im.setAttribute("src",path + "/images/div.gif"); 
       var div = document.createElement("div");
           div.setAttribute((ie ?"className":"class"),"section");
           div.setAttribute("id",id_new);
       //Armar tabla
       var table = document.createElement("table");
           table.setAttribute((ie?"cellSpacing":"cellspacing"),"0");
       var thead = document.createElement("thead"); 
       var tr = document.createElement("tr");
       var th = document.createElement("th");
           th.setAttribute((ie ?"className":"class"),"rng1");
           th.appendChild(im.cloneNode(false));
           th.appendChild(document.createTextNode("Tema"));
           tr.appendChild(th);

           th = document.createElement("th");
           th.setAttribute((ie ?"className":"class"),"rng2");
           th.appendChild(im);
           th.appendChild(document.createTextNode("Clase"));
           tr.appendChild(th);

           th = document.createElement("th");
           th.setAttribute((ie ?"className":"class"),"rng4");
           th.appendChild(document.createTextNode("Comentarios"));
           tr.appendChild(th);
              
           thead.appendChild(tr); 
           table.appendChild(thead);
           var tbody = document.createElement("tbody");
      
        //Conexión AJAX para armar tbody
         var xhReq = createXMLHttpRequest( );

           if(xhReq!=null){
              var p = document.createElement("p");
              p.appendChild(document.createTextNode("Trayendo temas ..."));
              p.style.marginTop = "1px";
              p.style.marginLeft = "250px";
              p.style.marginRight = "0px";
              p.style.marginBottom = "-1px";
              p.style.color = "#f00";
              p.style.textAlign = "center";
              p.style.fontWeight = "bold";
              $(id_new).appendChild(p);
         }
 
          xhReq.onreadystatechange = function( ) {
               try{
                     if (xhReq.readyState==4) {
                               if (xhReq.status==200) {
                                  docXML = xhReq.responseXML;
                                  var records = docXML.getElementsByTagName("record");
                                  var idCat = docXML.getElementsByTagName("id")[0].firstChild.nodeValue;

                                  for(var i=0;i<records.length;i++){
                                         var row = document.createElement("tr");
                                         if((i+1)%2==0)row.setAttribute((ie ?"className":"class"),"bk1");
                                         var col = document.createElement("td");
                                         col.setAttribute((ie ?"className":"class"),"lft");
                                         var an = document.createElement("a");
                                             an.setAttribute("href",path + "/msgboard.do?codigo=45&idcat=" + idCat + "&idtheme=" + records[i].getElementsByTagName("idtheme")[0].firstChild.nodeValue); 
                                             an.setAttribute("title","Clic para visualizar comentarios o agregar un nuevo comentario.");                                  
                                             an.appendChild(document.createTextNode(records[i].getElementsByTagName("name")[0].firstChild.nodeValue));
                                             col.appendChild(an);
                                          row.appendChild(col);
                                          col = document.createElement("td");
                                          col.appendChild(document.createTextNode(records[i].getElementsByTagName("type")[0].firstChild.nodeValue));
                                          row.appendChild(col);
                                          col = document.createElement("td");
                                          col.appendChild(document.createTextNode(records[i].getElementsByTagName("number")[0].firstChild.nodeValue));
                                          row.appendChild(col);
                                          tbody.appendChild(row);
                                    }

                                   var row = document.createElement("tr");
                                   var col =  document.createElement("td");   
                                       col.setAttribute((ie?"colSpan":"colspan"),"4");  
                                       col.setAttribute((ie ?"className":"class"),"mspt2");  
                                   var an = document.createElement("a");                             
                                       an.setAttribute("href","javascript:addSubject('sctn" + docXML.getElementsByTagName("id")[0].firstChild.nodeValue + "');void(0);");
                                       an.setAttribute("title","Clic aqui para agregar una nueva inquietud o comentario.");
                                       an.appendChild(document.createTextNode("+ Agregar tema"));
                                       col.appendChild(an);
                                       row.appendChild(col);
                                       tbody.appendChild(row);          
                              } else {
                                  alert("Error al recibir respuesta del servidor. Error: " + xhReq.statusText);
                                }
                      }
                   }
                 catch(exc){
                           alert("Ocurrio el siguiente error en el visualizador: " + exc.message);
                 }
          };

          xhReq.open("GET", path + "/msgboard.do?codigo=10&id=" + id, true);
          xhReq.send(null);
          
          table.appendChild(tbody);
          div.appendChild(table);

          $(id_new).parentNode.replaceChild(div,$(id_new));
     }

     //Actualizar botón de la carpeta de abajo
     if($("sctn"+(id+1))){
        $("ig"+(id+1)).src = path + "/board/images/bup.gif"; 
     }
     else{
         $("arncat").src = path + "/board/images/bup.gif";
     }
}

function closeFolder(flag){
     
       if(id_folder!="newcat"){ //Folder comun
         var id = parseInt(id_folder.substring(id_folder.indexOf("n")+1));

            //Guardar en memoria
             if(folders.length < id || !folders[id-1]){
                 folders[id-1] = $(id_folder).cloneNode(true); 
             }

            //Cerrar la respectiva carpeta
             $("ig"+id).src = path + ((flag || id==1)?"/board/images/bup.gif":"/board/images/bup2.gif");
             $("anc"+id).setAttribute("href","javascript:openFolder('" + id_folder + "')");
             $("anc"+id).setAttribute("title","Clic para mostrar los temas");
 
             var div = document.createElement("div");
                 div.setAttribute("id","sctn"+id);
                 div.setAttribute((ie ?"className":"class"),"section espb");
            
              //Verificar si tiene carpeta comun abajo
              if($("sctn"+(id+1))){
                //Realizar cambios
                  $("ig"+(id+1)).src = path + "/board/images/bup2.gif";
                  if($("thc" + (id+1)).style.marginTop!="-20px"){
                     $("thc" + (id+1)).style.marginTop = "-20px";
                   }
               }  
              else{
                  $("arncat").src = path + "/board/images/bup2.gif";
                  if($(id_folder).getElementsByTagName("form")[0])$("ntcat").style.marginTop = "-20px";
              }

           $(id_folder).parentNode.replaceChild(div,$(id_folder));
       }
       else{ //Folder de nueva categoria 
           hideCatForm(flag);
       }
}

function createUL(items){
  try{
     var ul = document.createElement("ul");
     for(var i=0;i<items.length;i++){
         var li = document.createElement("li");
             li.appendChild(document.createTextNode(items[i]));
             ul.appendChild(li);
      }
      
      return ul;
   }
   catch(msg){
         return null;
    }
}