if ( typeof(includeJS) == 'undefined') alert('Por favor incluya prelude.js antes de llamar a main.js');

//Ruta maestra del include
//alert(document.domain)
if(document.domain!=""){
   arreglo = new Array;
   includeJS.Path = 'http://'+document.domain+'/js/';
   arreglo = explodeArray(document.domain,".");
   //if(arreglo[0]=='ctu'){
      includeJS.Path = 'http://www.tchile.'+arreglo[0]+'/js/';
   //}
}
else{
   includeJS.Path = 'http://www.tchile.com/js/';
}


includeJS('prelude/quickDOM.js');
includeJS('prelude/debugMsg.js');


/**
* Funci� para inicializar el chat de php helper
*/

function explodeArray(item,delimiter) {
   tempArray=new Array(1);
   var Count=0;
   var tempString=new String(item);

   while (tempString.indexOf(delimiter)>0) {
      tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
      tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
      Count=Count+1
   }

   tempArray[Count]=tempString;
   return tempArray.reverse();
}
function startchat(mypage) {
    var winl = (screen.width-472)/2;
    var wint = (screen.height-320)/2;
    var settings = 'height=320,width=472,top='+wint+',left='+winl+',scrollbars=no,resizable=no';
    toopen=window.open(mypage,'phplivehelper',settings);
    if (parseInt(navigator.appVersion) >= 4) {
        toopen.window.focus();
    }
}


// Evento onload
window.onload = function () {
  if ( window.includeJS.IsLoading ) { window.includeJS.OnEmpty = main; }
  else main();
}




// Script maestro
function main () {
    debugMsg('Inicio de main()');
    var pagename = document.location.pathname.substr( document.location.pathname.lastIndexOf("/")+1 ).before( "." );

    // Abre funcion asociada a pagina: ej: form_seleccion_php
    [ "form_seleccion", "contratar_hosting" ].filter( function(e){ return e==pagename } ).map( function(e) { var f=e+'_php'; eval(f+'();'); } );
}



/*

Agrega validaciones a los contratos

1.
2. input.name=dominio sin www
3. input.name=dominio dm.cl sin puntos


*/
function contratar_hosting_php() {
  form_seleccion_php();
}

function form_seleccion_php() {
  if (!document.getElementById) return;

  //var validaContenidoCampos = function(form) {
  //  return function() {
  //    return true;
  //  };
  //};

  // Realiza accion sobre <form name=contrato>
  nodeCollection(
    document.getElementsByTagName("form")
  ).filter(
    function(e) { return e.name=="contrato"; }
  ).map(
    function(e) {

      // Borra input.dominio cuando cambia
      nodeCollection(e.tipo_dominio).map(
        function(option) {
          option.onchange = function() { e.dominio.value=''; };
        }
      );

      // Agrega validacion a input dominio
      nodeCollection( e.getElementsByTagName("input")
      ).filter(
        function(i) { return i.name=="dominio"; }
      ).map(
        function(i) {
          // Codigo de validacion
          var valida=function () {
            this.value = this.value.trim().str_replace(' ', '').toLowerCase().str_replace('www.', '');

            if (this.value=='') return true;

            var mal_escrito = function(input) {
              alert('Dominio mal escrito');
              input.value='';
              input.focus();
              return false;
            };

            // Dominio entregado por el cliente
            // cat = dedicados
            // XXXX.YY
            if ( tipo_dom() == 'tipodom1' || e.cat && ['dedicados', 'renovar_anual'].exists(e.cat.value) ) {
              // Verifica a.b
              if ( this.value.split('.').length != 2 ) return mal_escrito(this);
              else if ( ! /^[.0-9a-z\-]+\.+[.0-9a-z]+$/.test(this.value) ) return mal_escrito(this);
              else return true;
            }

            // nombre.dm.cl --- Gratis
            // XXXX.dm.cl
            else if ( tipo_dom() == 'tipodom2') {
              if ( this.value.indexOf('.dm.cl') < 1 ) this.value += '.dm.cl';
              // Verifica sin puntos
              if ( this.value.split('.').length != 3 ) return mal_escrito(this);
              else if ( ! /^[.0-9a-z\-]+$/.test(this.value.before('.dm.cl') ) ) return mal_escrito(this);
              else return true;
            }

            // Contratar dominio simple.
            // XXXX
            else if ( e.cat && e.cat.value=='dominios') {
              // Verifica sin puntos
              if ( this.value.split('.').length != 1 ) return mal_escrito(this);
              else if ( ! /^[.0-9a-z\-]+$/.test(this.value) ) return mal_escrito(this);
              else return true;
            }

            // nombre.com, .net, .org
            else if ( tipo_dom() == 'tipodom3' ) {
              var partes = this.value.split('.');
              // Verifica sin puntos
              if ( this.value.split('.').length != 2 ) return mal_escrito(this);
              else if ( ! /^[.0-9a-z\-]+$/.test(this.value) ) return mal_escrito(this);
              else if ( ! ['com', 'net', 'org'].exists( partes[1] )  ) return mal_escrito(this);
              else return true;
            }

          };
          // Determina el tipo de dominio elegido
          var tipo_dom = function(tipo) {
            var id = '';
            nodeCollection(e.tipo_dominio).map(
              function(option) { if (option.checked) id = option.id; }
            );
            return id;
          };

          // Borra al inicio
          // i.value = ''; // Esto causaba problemas inesperados en el segundo paso del form
          i.onchange = 'function'==(typeof(i.onchange)) ? (i.onchange).ifTrue( valida ) : valida;
        }
      );
    }
  );
}

