/* $.touch plugin
 * copyright 2009 Clark Van Oyen
 * This software contained in this file is dual-licensed, under either the GPL or MIT license.
 * This is the same licensing as the jQuery library.
 */

/*
 * usage:
 * $.touch(CSS_SELECTORS) creates dom elements matching the provided CSS_SELECTORS, which is any number of string arguments.
 * $().touch(CSS_SELECTORS) is (almost) equivalent to $().append($.touch(CSS_SELECTOR))
 */
 
(function($){ /* Touch Selector plugin */
$T = $.touch = function() {
  var $out = null;
  $.each(arguments,function(i,arg){
    if (typeof arg == 'string') {
      arg_tree = arg.match(/(^[^>]+)>(.*)$/);
      if (arg_tree) arg = arg_tree(1);
      sel = arg.match(/(^[^\.#\[]+)(#[^\.#]+|)(\.[^\.#]+|)(\[[^=]+=["'][^\]"']+["']\]|)$/);
      if (!sel) utl.log('Touch Selector: Invalid Select or "'+arg+"'");
      $elem = $(document.createElement(SH.DEFS[sel[1]] || sel[1]));
      if (sel.length > 2 && sel[2]) $elem.attr('id',sel[2].substring(1));
      if (sel.length > 3 && sel[3]) $elem.addClass(sel[3].substring(1));
      if (sel.length > 4 && sel[4]) {
          pair = sel[4].match(/\[([^=]+)=["']([^\]"']+)["']\]/);
          $elem.attr(pair[1],pair[2]);
        }
      if (SH.ATTR[sel[1]]) $elem.attr(SH.ATTR[sel[1]]);
      if (arg_tree) $elem.touch(arg_tree[2])
      if (SH.FN[sel[1]]) {
        for (k in SH.FN[sel[1]]) {
          $elem[k](SH.FN[sel[1]][k]);
        }
      }
    } else { $elem = $(arg);  }
    $out = $out ? $out.add($elem) : $elem;
  });

  return $out;
}
$.extend($.touch, {
/*a set of utlities for manipulating the dom based on selectors.
 */
    SHORTHAND: {
      DEFS: { // shorthand selector map
        txt:'input',
        btn:'input',
        hid:'input',
        pwd:'input'
      },
      ATTR: { // attributes for shorthand selectors
        txt:{type:'text'},
        btn:{type:'button'},
        hid:{type:'hidden'},
        pwd:{type:'password'}
      },
      FN:{ // jquery functions to be applied to custom selectors with the form $(generated_element).key(value)
        txt:{
          keypress:function(e){if (e.which==13) this.form.submit()}
        },
        pwd:{
          keypress:function(e){if (e.which==13) this.form.submit()}
        }
      }
    },
    img: function(src,alt) {
      return $.touch('img').attr({
          src:src,
          alt:alt || src.match(/\/([^\/]*?)\.[^\.]+$/)[1]
        });
    },
    link: function(link,text) {
      return $T('a').append(text).attr('href',link);
    }
});
var SH=$.touch.SHORTHAND;
$.fn.touch = function() {
  tgt = this;
  $.each(arguments,function(i,selector) {
      if (typeof selector == 'string' && selector.substring(0,1)==' ') tgt.append(selector.substring(1));
      else {
        tgt.append( $.touch( selector ) );
      }
  });
  return tgt;
};
/* end Touch Selector plugin */
})(jQuery);

