//requires melt-coolie

(function($){
 
  
  $.fn.meltEmail = function(method) {
    
    //default class
    var defOptions = {
      "invalid-class" : "invalid",
      "error-box-class": "error-box",
      "required-class" : "required",
      "success-msg" : "Your message has been sent!",
      "error-msg" : "Server Error: Please try later.",
      formId: "no-id-form"
    }
    
    
    var validator = {
      "name": new RegExp("[a-zA-Z ]"),
      "email": new RegExp("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"),
      "message": new RegExp("[a-zA-Z0-9]")
    }
    
    
    
    return this.each(function() {
      
      var $form,
          elements,
          $modal,
          cfg,
          sending = false;
      
      function init(){
        
        $form = $(this);
                  
        cfg = $.extend({},defOptions,method || {},$form.dataset());    
        
        initElements();
        
        initEvents();
        
      }
      
      
      function initElements(){
        
        $modal = $("<div />").dialog({
          hide: 'fade',
          autoOpen: false,
          closeOnEscape: false,
          dialogClass: "melt-popup email-popup",
          buttons: [
            {
              text: "OK",
              click: function() { 
                $(this).dialog("close");
              }
            }
          ]
        })
        
        
        elements = [];
        
        $form.find("input[type!=hidden],textarea").each(function(i){
          
          var $tg = $(this),
              data = $tg.dataset(),
              eMsg = data["error-message"] = data["error-message"] || "invalid "+$tg.attr("title");
              eBox = $("<div class='"+cfg["error-box-class"]+"'  />").appendTo($tg.parent()).html(eMsg).hide(); 
          
          var item = {
            
            id: i,
            
            el: $tg,
            
            isValid: false,
            
            required: data.required,
            
            type: data.type,
            
            errorBox: eBox
            
          }
          
          
          elements.push(item) 
          
           
          initElementEvents.call(item);   
          
        })
       
          
      }
      
      
      function initElementEvents(){
        
        var $tg = this.el;
        
        $tg.bind({
          focus: $.proxy(clearText,$tg),
          blur: $.proxy(validate,this)
        });
        
        $form.bind("submit",$.proxy(validate,this));   
        
      }
      

      function clearText(){
        if($.trim(this.val()) == this[0].title) this.val("");
      };
    
    
      function restoreText(){ 
        if($.trim(this.val()).length == 0) this.val(this[0].title);
      };

      
      function validate(){
       
        var $tg = this.el,
            type = this.type,
            eBox = this.errorBox,
            v = $.trim($tg.val());
        
        if(validator[type].test(v) && v!==$tg[0].title){
          
          eBox.hide("fast");
          $tg.removeClass();
          this.isValid = true;
          
        }else{
          
          eBox.show("fast");
          
          this.isValid = false;
          
        }
        
        if(v.length===0)restoreText.call($tg);
        
      }
      
      
      function initEvents(){ 
     
        $form.submit(submit); 
        
      }
      
      
      function submit(e){
        
        e.preventDefault();
        
        if(sending || !isAllValid()) return;
        
        $form.trigger("email:send");
        
        sending = true;
        
        $.ajax({
          url: $form[0].action,
          data: $form.serialize(),
          type: "POST",
          context: this,
          complete: onComplete,
          success: onSuccess,
          error: onError
        });
        
        
      } 
      

      function isAllValid(){
      
        var isValid = true;
      
        $(elements).each(function(){
          
          isValid = this.isValid;
          
          if(!isValid) return false;
           
        })
        
        return isValid;
        
      }
      
      
      function onComplete(){
        $form[0].reset();
        sending = false;
        $form.trigger("email:complete");
      }
      
      function onSuccess(){
        $modal.html(cfg["success-msg"]).dialog("open");
        $form.trigger("email:success");
      }
      
      function onError(){
        $modal.html(cfg["error-msg"]).dialog("open");
        $form.trigger("email:error");
      }
      
      
      var _public = {

      
      }
      
      
      
      
      if ( _public[method] ) {
        
        return _public[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        
      } else if ( typeof method === 'object' || ! method ) {
        
        return init.apply( this, arguments );
        
      } else {
        
        $.error( 'Method ' +  method + ' does not exist on meltEmail' );
        
      }
      
      
      
    })
    
    

  };

})(jQuery);
