(function($) {
    
  /**
   * gzPrettyForms
   *   http://www.gijsvanzon.com/prettyforms
   *
   * Copyright (c) 2010 Gijs van Zon
   * Copyright (c) 2010 Freshheads
   * 
   * Built on top of the jQuery 1.4 library
   *   http://jquery.com
   *
   * @name gzPrettyForms
   * @type jQuery
   * @cat Plugins/gzPrettyForms 
   *
   
   *
   * Default Usage:
   * The function works on all inputs, buttons, selects & textareas passed by a selector:
   * $('input[type=text], textarea').gzPrettyForms();
   * Each element is given a class prefix .gzPrettyForms followed by the elements type e.g. .gzPrettyForms-input
   * if clearInput is set to true each input and textarea will get a default value taken from the title attribute
   *
   
   *
   * Authors: Gijs van Zon MA
   * Return: Object (this)
   * Params:
   *   classPrefix: String ('gzPrettyForms')
   */
   
  $.fn.gzPrettyForms = function(o) {
    
    var _this = this;
            
    $('form').bind('submit', function(e) {
      _this.each(function() {
        $this = $(this);
        
        if($this.val() == $this.data('value')) {
          $this.val('');
        }
      });
    });
    
    return this.each(function() {
      new $gzpf(this, o);
    });
  };
  
  var defaults = {
    classPrefix: 'gzPrettyForms',
    emptyClass: 'gzPrettyForms-empty',
    clearInput: true
  };
  
  $.gzPrettyForms = function(e, o){
    
    var self = this;
    tagName = e.tagName;
    
    this.options = $.extend({}, defaults, o || {});
    this.element = $(e);
    
    this.attributes = this.element.attr('title').replace(/^\s+|\s+$/g,"").split(',');
    for(var i = 0; i < this.attributes.length; i++){
      var value = this.attributes[i].split(':');
      if(value[0] == 'value')   this.element.data('value', value[1]);
    };
    
    if(this.element.attr('title')){
      if(this.element.attr('maxlength')){
        this.element.data('maxlength', this.element.attr('maxlength'));
        if(this.element.data('maxlength') <= 0){
          this.element.data('maxlength', 87255);
        };
      };
      
      if(this.element.data('value') && this.options.clearInput){
        if(this.element.val() == '') {        
          if(this.element.attr('maxlength')){
            this.element.attr('maxlength', 100);
          };
          
          this.element
            .val(this.element.data('value'))
            .addClass(this.options.emptyClass);
        };
      
        this.element
          .bind('focus', function() {
            var $this = $(this);
            if($this.val() == $this.data('value')) {
              $this
                .val('')
                .removeClass(self.options.emptyClass);
              if($this.attr('maxlength')){
                $this.attr('maxlength', $this.data('maxlength'));
              };
            };
          })
          .bind('blur', function() {
            var $this = $(this);
            if($this.data('value') != '' && $this.val() == '') {
              if($this.attr('maxlength')){
                $this.attr('maxlength', 100);
              };
              $this
                .val($this.data('value'))
                .addClass(self.options.emptyClass);
            };
          });
      };
    };
    
    switch(tagName){
      
      case 'TEXTAREA':
      case 'textarea':
          this.element.addClass(this.options.classPrefix + '-textarea');
        break;
        
      case 'INPUT':
      case 'input':
        var type = this.element.attr('type');
        
        switch(type){
          case 'text':
          case 'submit':
          case 'password':
            this.element.addClass(this.options.classPrefix + '-' + type);
            
            break;
          case 'radio':
          case 'checkbox':
            this.element.addClass(this.options.classPrefix + '-' + type);
            
            if(!this.element.next().is('label')) this.element.after($('<label><!-- --></label>').addClass('emptyLabel'));
            
            this.element
              .width(this.element.next().outerWidth())
              .height(this.element.next().outerHeight());
            
            if(this.element.attr('checked')){
              this.element.next()
                .data('checked', true)
                .addClass('checked');
            }else{
              this.element.next().data('checked', false);
            };
            
            if(this.element.is(':disabled')){
              this.element.next().addClass('disabled');
            };
            
            if(type == 'radio'){
              this.element.bind('change', function(e){
                var label = $(this).next();
                
                $('input[name=' + $(this).attr('name') + ']').attr('checked', false);
                $('input[name=' + $(this).attr('name') + '] + label').removeClass('checked');
                $(this)
                  .attr('checked', 'checked')
                  .next().addClass('checked');
              });
            }else{
              this.element.bind('change', function(e){
                var label = $(this).next();
                
                if($(this).is(':disabled')){
                  label.addClass('disabled');
                }else{
                  label.removeClass('disabled');
                };
                
                if($(this).attr('checked')){
                  label
                    .data('checked', true)
                    .addClass('checked');
                }else{
                  label
                    .data('checked', false)
                    .removeClass('checked');
                };
              });
            };
            break;
          case 'file':
          
            var button = $('<div>')
              .addClass(this.options.classPrefix + '-file-button')
              .html('Bladeren')
              .attr('title', this.element.attr('title'));
            
            var attributes = this.element.attr('title').replace(/^\s+|\s+$/g,"").split(',');
            for(var i = 0; i < attributes.length; i++){
              var value = attributes[i].split(':');
              if(value[0] == 'route') button.data('route', value[1]);
              if(value[0] == 'target') button.data('target', value[1]);
              if(value[0] == 'multiple') button.data('multiple', value[1]);
            }
            
            if(button.data('multiple')){
              this.element.after(button);
              this.element.remove();
            	
              new AjaxUpload(button,{
              	action: button.data('route'),
              	name: 'file',
              	onSubmit: function(){
                  button.html('Bezig met uploaden').addClass('uploading');
              	},
              	onComplete: function(file, response){
                  button.html('Bladeren').removeClass('uploading');
              		  
                  var image = $(button.data('target'));
                  
                  if(image.find('ul').length == 0) $(button.data('target')).append('<ul>');
                    
                  var ul  = $(button.data('target')).find('ul');
                  
                  if($(response).length < 1){
                    var li  = $('<li>').html(response);
                  }else{
                    var li = $(response);
                  };
                  li.appendTo(ul);
              	}
              });
            }else{
              this.element.addClass('gzPrettyForms-file').wrap('<div class="gzPrettyForms-file-holder">');
              
              var fakeFile = $('<div class="gzPrettyForms-file-fake">');
              var input = $('<input type="text">').gzPrettyForms();
              fakeFile
                .append(input)
                .append(button);
              this.element.after(fakeFile);
              
              button
                .data('element', this.element)
                .bind('click', function(e){
                  e.preventDefault();
                  $(this).data('element').trigger('click');
                });
              this.element.bind('change', function(){
                input.val($(this).val());
              });
            }
            break;
        };
        break;
      
      case 'SELECT':
      case 'select':
        
        var $selectWrapper = $('<div class="' + this.element.attr('class') + ' ' + this.options.classPrefix + '-select">');
        this.element.wrap($selectWrapper);

        var $select = $('<a></a>')
          .attr('class', 'gzPrettyForms-select-option')
          .css('width', this.element.outerWidth())
          .data('element', this.element)
          .html(this.element.find('option:selected').text())
          .prepend('<span><!-- --></span>');

        if(this.element.is(':disabled')){
          $select.addClass('disabled');
        };
          
        this.element
          .before($select)
          .addClass('gzPrettyForms-original-select')
          .data('select', $select)
          .bind('focus', function(){
            $(this).data('select').addClass('focus');
          })
          .bind('blur', function(){
            $(this).data('select').removeClass('focus');
          })
          .bind('keydown', function(e){
            if(e.keyCode == 13){
              $(this).closest('form').submit();
            }
          })
          .bind('change', function(e){
            if($(this).is(':disabled')){
              $(this).data('select').addClass('disabled');
            }else{
              $(this).data('select').removeClass('disabled');
            };
            $(this).data('select').html('<span><!-- --></span>' + this.options[this.selectedIndex].text);
          });
        break;
        
        break;
      case 'button':
      case 'BUTTON':
        this.element.addClass(this.options.classPrefix + '-button');
      break;
    };
    
    if(this.options.initCallback != null){
      this.options.initCallback(this);
    };
  };

  var $gzpf = $.gzPrettyForms;
  $gzpf.fn = $gzpf.prototype = {
    gzPrettyForms: '1.0'
  };

  $gzpf.fn.extend = $gzpf.extend = $.extend;
  
  $gzpf.fn.extend({
  });
  
})(jQuery);
