var separator = '-'; // string que separa las cosas que se usan como id y valor
var counter = 1;
var z_actual = 100;
var lastRadio = "";

// plugin
jQuery.fn.jLook = function(options){
  var self = this;
  $(this).addClass('jLookForm');
  this.each(function(){
    var actualForm = this;

    // inputs
    $('input:text, input:password', this).each(function(){
      var width = $(this).css('width');
      $(this).wrap('<div class="jLookInputWrapper" style="width:'+width+';"></div>');
      $(this).addClass("jLookInput").width(width.replace("px","")-15);
      // foco
      $(this).focus(function(){
        $(this).addClass("jLookInput_hover");
        $(this).parent().addClass("jLookInputWrapper_hover");
      });
      // sale de foco
      $(this).blur(function(){
        $(this).removeClass("jLookInput_hover");
        $(this).parent().removeClass("jLookInputWrapper_hover");
      });
    });

    $('input:file', this).each(function(){
      $(this).addClass('inputFile').wrap('<div class="jLookFileWrapper"></div>');
      $(this).parent('.jLookFileWrapper').append('<div class="jLookInputWrapper"><input type="text" class="jLookInput"></div><div class="browse_button"></div>');
      $(this.parentNode).after('<span class="jLookFileName hidden_block"></span>');
      this.parentNode.iFile = this;
      this.parentNode.onmousemove = inputFileMouseMove;
      this.onchange = inputFileChanges;
    });

   // checkbox/s
    $('input:checkbox', this).each(function(){
      id = $(this).attr("name");
      if(id)
        id = id.replace('[]','');

      var checked = "";
      var value ="";
      var disabled = "";

      if($(this).attr("disabled"))
        disabled = "jLookCheckbox_disabled";

      if($(this).attr("checked")){
        checked = "jLookCheckbox_checked";
        if($(this).attr('value'))
          value = $(this).attr('value');
      }
      $(this).before('<a href="javascript:void(0)" id="'+id+ separator + $(this).attr("value")+'" class="jLookCheckbox ' + checked + ' ' + disabled + '"></a>').css('display','none');
      // necesary hidden fields
    });
    // click event
    $('.jLookCheckbox').not(jQuery('.jLookCheckbox_disabled')).bind('click', checkboxClick);


    //---------------------------------
    // select/s
    $('select', this).each(function(){
      // nombre del contenedor
      var disabled;
      var disableClass = "";

      if($(this).attr("disabled"))
        disabled = true;
      var nam = $(this).attr('name')+'_wrapper';
      // contenedor
      if (disabled)
        disableClass = "jLookDisableSelect";
      $(this).wrap('<div class="jLookSelectWrapper ' + disableClass + '" id="' + nam + '"></div>');
      var width = $(this).css('width');

      $(this).parent().width(width);

      // nombre del elemento
      var name = $(this).attr('name');
      // id seleccionado
      var indiceSeleccionado = this.selectedIndex;
      if (disabled)
        disableClass = "jLookDisableSelectOpen";
      var selectContent = '<ul>';
      // veo si est� el par�metro
      width = width.replace("px","")-10;
      var selectContent = '<ul style="overflow:auto;width:' + (width+4) + 'px">';
      var index = 0; // �ndice seleccionado
      var selectContentHeader= '<input type="hidden" value="" name="' + name + '" id="' + name + '" /><div class="jLookSelectHeader"><div></div><a href="#" class="jLookSelectOpen ' + disableClass + '"></a></div>'; // xhtml replace

      $('option', this).each(function(){
          // armo el ul
        if (disabled)
          disableClass = "jLookDisableSelectOption";
        selectContent += '<li><a href="javascript:void(0)" class="jLookSelectOption ' + disableClass + '" id="' +  name + separator + $(this).attr('value') + '">' + $(this).html() + ' </a></li>';
        // si alguno est� seleccionado lo coloco como valor
        if (disabled)
          disableClass = "jLookDisableSelectOpen";
        if(indiceSeleccionado == index){
          selectContentHeader = '<input type="hidden" value="' + $(this).attr('value') + '" name="' + name + '" id="' + name + '" /><div class="jLookSelectHeader"><div>' + $(this).html() + '</div><a href="#" class="jLookSelectOpen ' + disableClass + '"></a></div>'; // xhtml replace
        }
        $(this).remove();
        index = index + 1;
      });
      selectContent += '</ul>';
      $('#' + nam).html(selectContentHeader + selectContent);
      $('#' + nam + " .jLookSelectHeader").width(width).find('div').width(width-40);
    });
    // display select options
    $('.jLookSelectOpen').not(jQuery('.jLookDisableSelectOpen')).bind('click', selectClick);
    // select option
    $('.jLookSelectOption').not(jQuery('.jLookDisableSelectOption')).bind('click', optionClick);

    $('input:radio', this).each(function(){
      var checked = "";
      var value ="";
      var disabled = "";
      var name = $(this).attr("name");
      if($(this).attr("disabled"))
        disabled = "jLookRadio_disabled";

      if(lastRadio != name){
        $(actualForm).prepend('<input type="hidden" id="'+name+'" name="'+name+'" value="" />');
        lastRadio = name;
      }

      if($(this).attr("checked")){
        checked = "jLookRadio_checked";
        if($(this).attr('value'))
        {
          value = $(this).attr('value');
          $('#'+name).attr('value',value);
        }
      }
      $(this).before('<a href="javascript:void(0)" id="'+name+separator+$(this).attr("value")+'" class="jLookRadio ' + checked + ' ' + disabled + '"></a>');
      $(this).remove();
      // hidden necesary fields
    });
    // click event
    $('.jLookRadio').not(jQuery('.jLookRadio_disabled')).bind('click', radioClick)


     $('textarea', this).each(function(){
       if($(this).attr('class') == "no_jLook")
         return;
       var width = $(this).css('width');
       $(this).width(width.replace("px","")-15).wrap("<div class='jLookTextareaWrapper' style='width:"+width+";'></div>");
       $(this).focus(function(){
        $(this).parent().addClass("jLookTextareaWrapper_hover");
       });
       $(this).blur(function(){
        $(this).parent().removeClass("jLookTextareaWrapper_hover");
       });
     });

  });
}

checkboxClick = function(target){
  var id = $(this).attr("id");
  if (id.match(separator+separator))
    var separatorPos = id.lastIndexOf(separator-1);
  else
    var separatorPos = id.lastIndexOf(separator);
  var name = id.substring(0,separatorPos);
  var checkbox = $(this).next("input[name*='" + name + "']");
  if(checkbox.attr('checked')){
          $(this).removeClass('jLookCheckbox_checked');
          checkbox.removeAttr('checked');
  }else{
          $(this).addClass("jLookCheckbox_checked");
          checkbox.attr('checked','true');
  }
  return false;
}


selectClick = function(){
  z_actual = z_actual + 10;
  // id del contenedor
  wrapperId = $(this).parent().parent().attr('id');
  // veo si est� abiero
  if($('#' + wrapperId).is('.jLookSelectOpened')){
    // lo vuelvo al estado cerrado
    $('#' + wrapperId).removeClass('jLookSelectOpened');
    // cierro
    $('ul', $('#' + wrapperId)).hide('fast', function(){
      // vuelvo todo a posiciones relativas
      $('.jLookSelectWrapper').each(function(){
        if($(this).attr('id') != wrapperId){
          $(this).css('position', 'relative');
        }
      });
    });
  }else{ // expando
    // cambio las posiciones de los otros selects
    $('.jLookSelectWrapper').each(function(){
      if($(this).attr('id') != wrapperId){
        $(this).removeClass('jLookSelectOpened').find('ul').hide();
      }
    });
    $('#' + wrapperId).addClass('jLookSelectOpened');
    $('ul', $('#' + wrapperId)).show();//slideDown();
  }

  return false;
};

optionClick = function(){
  var id = $(this).attr("id");
  var separatorPos = id.lastIndexOf(separator);
  if(separator == id.charAt(separatorPos-1))
  {
    var value = id.substring(separatorPos,id.length);
    var name = id.substring(0,separatorPos-1);
  }
  else
  {
    var value = id.substring(separatorPos+1,id.length);
    var name = id.substring(0,separatorPos);
  }
  var wrapperId = name + '_wrapper';
  $('#' + name).attr('value', value);
  // muestro el valor seleccionado
  $('div', $('#' + name + '_wrapper .jLookSelectHeader')).html($(this).html());
  // cierro el select

  // lo vuelvo al estado cerrado
  $('#' + wrapperId).removeClass('jLookSelectOpened');
  // cierro
  $('ul', $('#' + wrapperId)).hide('fast', function(){
    // vuelvo todo a posiciones relativas
    $('.jLookSelectWrapper').each(function(){
      if($(this).attr('id') != wrapperId){
        $(this).css('position', 'relative');
      }
    });
  });
  return false;
};

radioClick = function(){
  var id = $(this).attr("id");
  var separatorPos = id.lastIndexOf(separator);
  if(separator == id.charAt(separatorPos-1))
  {
    var value = id.substring(separatorPos,id.length);
    var name = id.substring(0,separatorPos-1);
  }
  else
  {
    var value = id.substring(separatorPos+1,id.length);
    var name = id.substring(0,separatorPos);
  }
  actualValue = $('#' + name).attr("value");
  if (!actualValue)
    actualValue = "";
  if( actualValue != value){
    // quito la clase del que estaba antes seleccionado
    $("a[id*='" + name + separator + actualValue + "']").removeClass('jLookRadio_checked');
    // actualizo valor
    $('#' + name).attr("value", value);
    $(this).addClass('jLookRadio_checked');
  }
  return false;
}

function inputFileMouseMove (e)
{
  if (typeof(e) == 'undefined') e = window.event;
  if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement)
  {
    e.pageX = e.clientX + document.documentElement.scrollLeft;
    e.pageY = e.clientY + document.documentElement.scrollTop;
  };

  var ox = oy = 0;
  var elem = this;
  iFile = elem.iFile;

  if (elem.offsetParent)
  {
    ox = elem.offsetLeft;
    oy = elem.offsetTop;
    while (elem = elem.offsetParent)
    {
      ox += elem.offsetLeft;
      oy += elem.offsetTop;
    };
  };

  var x = e.pageX - ox;
  var y = e.pageY - oy;
  var w = iFile.offsetWidth;
  var h = iFile.offsetHeight;

  iFile.style.top		= y - (h / 2)  + 'px';
  iFile.style.left	= x - (w - 30) + 'px';
};

function inputFileChanges()
{
  file = this.value;
  reWin = /.*\\(.*)/;
  var fileTitle = file.replace(reWin, "$1");
  reUnix = /.*\/(.*)/;
  fileTitle = fileTitle.replace(reUnix, "$1");

  var RegExExt =/.*\.(.*)/;
  var ext = fileTitle.replace(RegExExt, "$1");

  var pos;
  var input = jQuery(this.parentNode).find(".jLookInputWrapper input");
  input.attr('value',fileTitle);

};

jQuery('body').click(function(event){
  if(!event) event = window.event;
  var target =  event.target;
  if (jQuery(target).parents('.jLookSelectWrapper')[0] || jQuery(target).hasClass("jLookSelectWrapper"))
    return;
  jQuery('.jLookSelectWrapper').removeClass('jLookSelectOpened').find('ul').hide();
});

