(function() {
var separator = '-'; // string que separa las cosas que se usan como id y valor

var bind_select_events = (function() {
  var click_option = function(select_events, option) 
  {
    var wrapperId = select_events.wrapperId;
    var id = option.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);
    }

    $('#' + name, select_events.context).val(value).change();
    $('div', $('#' + name + '_wrapper .jLookSelectHeader', select_events.context)).html(option.html());
    select_events.wrap.removeClass('jLookSelectOpened');
    $('ul', select_events.wrap).hide('fast', function() {
      $('.jLookSelectWrapper', select_events.context).each(function(){
        if($(this).attr('id') != wrapperId){
          $(this).css('position', 'relative');
        }
      });
    });
  };

  var select_events = function(el, wrapperId, context) 
  { 
    var link = this;
    this.el = jQuery(el);
    this.wrapperId = wrapperId;
    this.wrap = jQuery('#' + this.wrapperId, context);
    this.context = jQuery(context);

    this.bind_function = function() {
      if(link.wrap.hasClass('jLookSelectOpened'))
        link.wrap.removeClass('jLookSelectOpened').find('ul').hide('fast');
    };

    this.wrap.find('.jLookSelectOpen,.jLookSelectTitle').click(function() {
      link.click();
      return false;
    });
    this.wrap.find('.jLookSelectOption').click(function() {
      click_option(link, jQuery(this));
      return false;
    });
    this.click();
  };
  select_events.prototype.click = function() {
    var link = this;
    if(this.wrap.hasClass('jLookSelectOpened')) {
      this.wrap.removeClass('jLookSelectOpened');
      jQuery('ul', this.wrap).hide('fast', function() {
        $('.jLookSelectWrapper', link.context).each(function(){
          if($(this).attr('id') != link.wrapperId){
            $(this).css('position', 'relative');
          }
        });
      });
    } else { 
      this.wrap.addClass('jLookSelectOpened');
      $('ul', this.wrap).show();
      setTimeout(function() { jQuery('body').one('click', link.bind_function); }, 150);
    }
    return false;
  };

  return function(el, context) 
  {
    wrap = jQuery(el).parent().parent();
    wrapperId = wrap.attr('id');
    if(!wrap.data('-jlook-is_bind_select'))
    {
      wrap.data('-jlook-is_bind_select', 1);
      new select_events(el, wrapperId, context);
    }
    return false;
  };
})();

var 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
    $(this).addClass('jLookRadio_checked');
    $('#' + name).val(value).change();
  }
  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;
  if (ext){
      switch (ext.toLowerCase())
      {
          case 'bmp': pos = '-360px -124px'; break;
          case 'jpg': pos = '-380px -104px'; break;
          case 'jpeg': pos = '-380px -104px'; break;
          case 'png': pos = '-400px -84px'; break;
          case 'gif': pos = '-420px -64px'; break;
          case 'avi': case 'flv': pos = '-440px -44px'; break;
          default: pos = '-460px -24px'; break;
      };

      var fileName = jQuery(this.parentNode).next(".jLookFileName");
      fileName.text(fileTitle).css('background','url(images/icons.gif) no-repeat '+pos).removeClass('hidden_block');
  };

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

    $('input:file', this).each(function(){
      $(this).wrap('<div class="jLookFileWrapper"></div>');
      $(this.parentNode).after('<span class="jLookFileName hidden_block"></span>');
      this.parentNode.iFile = this;
      this.parentNode.onmousemove = inputFileMouseMove;
      this.onchange = inputFileChanges;
    });
    
    //label
    jQuery('label', this).each(function(){
      jQuery(this).click(function(){
        input_name = jQuery(this).attr("for");
        all_input = jQuery("input", self);
        for (var i = 0; i < all_input.length; i++) {
          if (all_input.eq(i).attr("id") == input_name){
            our_input = all_input.eq(i);
            if (jQuery(our_input).attr("type") == "checkbox"){
              link_for_our_input = jQuery(our_input).prev();
              var checkbox = jQuery(our_input);
              if(checkbox.attr('checked')){
                jQuery(link_for_our_input).removeClass('jLookCheckbox_checked');
              }else{
                jQuery(link_for_our_input).addClass("jLookCheckbox_checked");
              }
            } else if((jQuery(our_input).attr("type") == "text")||(jQuery(our_input).attr("type") == "password")) {
                jQuery(our_input).focus();
            } else {
            };
          }
        }
      });
    });

    // inputs
    $('input:text, input:password', this).each(function(){
       if($(this).hasClass('no_jLook'))
         return;
       if ($(this).css('width')=='0px'){
         var breaking = false;
        all_parent = $(this).parents();
        for(var i in all_parent) {
          if (breaking)
            continue;
          if (jQuery(all_parent[i]).get(0).tagName)
            if (jQuery(all_parent[i]).css("display") == "none"){
              jQuery(all_parent[i]).css("display","block");
              var width_css = $(this).css('width');
              jQuery(all_parent[i]).css("display","none");
              breaking = true;
            }
        }
       }
       else{
         width_css = $(this).css('width');
       }
      $(this).wrap('<div class="jLookInputWrapper" style="width:'+width_css+';"></div>');
      $(this).addClass("jLookInput");
      // 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");
      });
    });

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

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

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

      if($(this).attr("checked")){
        checked = "jLookCheckbox_checked";
        if($(this).attr('value'))
          value = $(this).attr('value');
      }
      if (jQuery(this).attr("tabindex")) {
        tab_control = 'tabindex="'+jQuery(this).attr("tabindex")+'"';
      }
      $(this).before('<a href="javascript:void(0)" id="'+id+ separator + $(this).attr("value")+'" '+tab_control+' 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(){
      var disabled;
      var disableClass = "";
      var isTitle = "";
      var disableClassOpen = "";
      var disableClassTitle = "";
      if ($(this).css('width')=='0px') 
      {
        var breaking = false;
        all_parent = $(this).parents();
        for(var i in all_parent) 
        {
          if (jQuery(all_parent[i]).get(0).tagName)
          {
            if (jQuery(all_parent[i]).css("display") == "none")
            {
              jQuery(all_parent[i]).css("display","block");
              var width = $(this).css('width');
              jQuery(all_parent[i]).css("display","none");
              break;
            }
          }
        }
      } 
      else 
         width = $(this).css('width');
      
      if($(this).attr("title"))
        isTitle = 'title="' + $(this).attr("title") + '"';

      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().css("width", width);

      // nombre del elemento
      var name = $(this).attr('name');
      // id seleccionado
      var indiceSeleccionado = this.selectedIndex;
      if (disabled)
      {
        disableClassOpen = "jLookDisableSelectOpen";
        disableClassTitle = "jLookDisableSelectTitle";
      }
      var selectContentHeader= '<input type="hidden" value="" name="' + name + ' "' + isTitle + ' id="' + name + '" /><div class="jLookSelectHeader"><div class="jLookSelectTitle ' + disableClassTitle + '"></div><a href="javascript:void(0)" class="jLookSelectOpen ' + disableClassOpen + '"></a></div>'; // xhtml replace
      var selectContent = '<ul>';
      // veo si est� el par�metro
      var selectContent = '<ul class="jLookSelectClose" style="overflow:auto;width:' + width + '">';
      var index = 0; // �ndice seleccionado
      // recorre las opciones
      $('option', this).each(function(){
        var el = jQuery(this);
          // armo el ul
        selectContent += '<li><a href="javascript:void(0)" class="jLookSelectOption" id="' +  name + separator + el.attr('value') + '">' + el.html() + ' </a></li>';
        // si alguno est� seleccionado lo coloco como valor
        if(indiceSeleccionado == index) {
          selectContentHeader = '<input type="hidden" value="' + el.attr('value') + '" name="' + name + '" ' + isTitle +' id="' + name + '" /><div class="jLookSelectHeader"><div class="jLookSelectTitle ' + disableClassTitle + '">' + el.html() + '</div><a href="javascript:void(0)" class="jLookSelectOpen ' + disableClassOpen + '"></a></div>'; // xhtml replace
        }
        index = index + 1;
      });
      jQuery(this).remove();
      selectContent += '</ul>';
      $('#' + nam, actualForm).html(selectContentHeader + selectContent);
      $('#' + nam + " .jLookSelectHeader", actualForm).css("width", width);
    });
    // display select options
    $('.jLookSelectOpen', actualForm).not('.jLookDisableSelectOpen').one('click', function() { return bind_select_events(this, actualForm); });
    $('.jLookSelectTitle', actualForm).not('.jLookDisableSelectTitle').one('click', function() { return bind_select_events(this, actualForm); });

    $('input:radio', this).each(function(){
      var checked = "";
      var value ="";
      var disabled = "";
      var our_label = 0;
      all_labels = jQuery('label', self);
      for (var k = 0; k < all_labels.length; k++) {
       if (jQuery(all_labels[k]).attr("for") == jQuery(this).attr("id"))
        our_label =  jQuery(all_labels[k]);
      }
      if(jQuery(this).parents()[0].tagName.toLowerCase()=="label")
        our_label=jQuery(this).parents().get(0);
      var name = $(this).attr("name");
      var isTitle = "";
      if($(this).attr("disabled"))
        disabled = "jLookRadio_disabled";

      if($(this).attr("title"))
        isTitle = 'title="' + $(this).attr("title") + '"';

      if(lastRadio != name){
        jQuery(actualForm).append('<input type="hidden" id="'+name+'"' + isTitle + ' 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>');
      if(our_label!=0) {
        jQuery(our_label).attr("for",jQuery(this).prev().attr("id"));
        jQuery(our_label).click(function() { 
          element_click = jQuery(this).attr("for");
          jQuery("#"+element_click, self).click();
        });
      }

      $(this).remove();
      // hidden necesary fields
    });
    // click event
    $('.jLookRadio', this).not(jQuery('.jLookRadio_disabled')).bind('click', radioClick)


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

  });
  return this;
}


checkboxClick = function(target){
  var checkbox = jQuery(this).next("input:checkbox");
  if(checkbox.attr('checked')){
          $(this).removeClass('jLookCheckbox_checked');
          checkbox.removeAttr('checked');
  }else{
          $(this).addClass("jLookCheckbox_checked");
          $(checkbox).attr('checked', 'checked')
  }
  return false;
}
})();
