$j(document).ready(function() {

  // Contact Us Form - JQueryUI
  if ($j('dialog')!=null) {
    var firstname = $j("#firstname"),
        lastname = $j("#lastname"),
        email = $j("#email"),
        subject = $j("#subject"),
        message = $j("#message"),
        allFields = $j([]).add(firstname).add(lastname).add(email).add(subject).add(message),
        tips = $j("#validateTips");
    
    $j.effects.fade = function(o) {
      return this.queue(function() {

        // Create Element
        var el = $j(this);

        // Set Options
        var speed = o.options.speed || 1000;
        var mode = o.options.mode || 'show'; // Set Mode

        // Animate
        if (mode == 'show') {
                el.fadeIn(speed);
        } else {
                el.fadeOut(speed);
        };
      
        el.queue('fx', function() { el.dequeue(); });
        el.dequeue();
      
      });
    }; 

    // Error Handling
    function updateTips(t) {
      tips.text(t).effect("highlight",{},1500);
    }

    function checkLength(o,n,min,max) {
      if ( o.val().length > max || o.val().length < min ) {
        o.addClass('ui-state-error');
        updateTips("The length of your " + n + " must be between "+min+" and "+max+" characters.");
        return false;
      } else {
        return true;
      }
    }

    function checkRegexp(o,regexp,n) {
      if ( !( regexp.test( o.val() ) ) ) {
        o.addClass('ui-state-error');
        updateTips(n);
        return false;
      } else {
        return true;
      }
    }

    // Open The Dialog
    $j("#dialog").dialog({
      bgiframe: true,
      autoOpen: false,
      height: 'auto',
      width: 430,
      modal: true,
      show: 'fade',
      hide: 'fade',
      position: 'center',
      buttons: {
        'Send Now': function() {
          var bValid = true;
          allFields.removeClass('ui-state-error');

          bValid = bValid && checkLength(message,"message",10,500);
          bValid = bValid && checkLength(firstname,"first name",2,50);
          bValid = bValid && checkLength(lastname,"last name",2,50);
          bValid = bValid && checkLength(email,"email address",6,30);
          bValid = bValid && checkLength(subject,"subject",10,50);
          //bValid = bValid && checkLength(message,"message",1,50);

          //bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
          // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
          bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Please enter a valid email address.");
          //bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
          
          if (bValid) {
            HandleFormSubmition();
            //$j(this).dialog('close');
            updateTips("sending ...");
          }
        }
        
        ,'Close': function() { $j(this).dialog("close"); }
        ,'Cancel': function() { $j(this).dialog("close"); }
      },
      
      close: function() {
        allFields.val('').removeClass('ui-state-error');
        //var  f = $j("fieldset#contactus");
        var  f = $j("#contactusForm");
        f.show();
        f = $j("#contactusMessage");
        f.hide();
        updateTips("All form fields are required.");
      }
      
    });

    $j('[href=http://www.gox.com/public/department6.cfm]').click(function() {	
      allFields.val('').removeClass('ui-state-error');
      var  f = $j("#contactusForm");
      f.show();
      f = $j("#contactusMessage");
      f.hide();
      updateTips("All form fields are required.");
      $j('#dialog').dialog('open');
      $j(":button:contains('Send')").show();
      $j(":button:contains('Close')").hide();
      $j(":button:contains('Cancel')").show();
      $j('#test').text("message length:" + $j('#message').val().length);
      return false;
    })
    
    // Handle The Form Submission
    function HandleFormSubmition(){
      $j.getJSON(
        "/com/forms.cfc?wsdl", {
          method : "contactForm",
          firstname : $j( "#firstname" ).val(),
          lastname : $j( "#lastname" ).val(),
          email : $j( "#email" ).val(),
          subject : $j( "#subject" ).val(),
          message : $j( "#message" ).val()
        },
        handleFormCallback
      );
    }
    
    function handleFormCallback(aResult, aState) {
      var  tips = $j("#validateTips");
      var t = "Submission Status: " + aState + ".";
      tips.text(t).effect("highlight",{},1500);
      //var  f = $j("fieldset#contactus");
      var  f = $j("#contactusForm");
      f.hide();
      var  f = $j("#contactusMessage");
      if((aState == "success") && (aResult.SUCCESS)){
        t = "<span style=\"font: bold 11px Verdana, Arial, sans-serif\;\">Thank's for contacting us " + aResult.FIRSTNAME +".</span><br /><br />If a response is required, we'll do out best to to get back to you as soon as possible (usually the same day).<br /><br />Best,<br /><br />Gregory Matthews, Publisher<br />Photoshop Masters Association<br />13446 Poway Road<br />PMB 147<br />Poway, CA  92064<br />(858) 842-1253 - ph<br />(858) 842-1257 - fx";
        f.html(t).effect("highlight",{},1500);  
      } else {
        t = "<strong><span style=\"color: red;\">We experienced an error communicating with the mail program</span>.</strong><br /><br />Please <a href='mailto:error@gox.com?subject=Error Calling LIB.JS&body=Please tell us what you were doing when this error occurred along with any other details that might help us. Thanks. ...'><strong>[ click here ]</strong></a> to notify the Webmaster.<br /><br />Chances are our ninja dudes are already on it, but just in case, please let us know.<br /><br />Thanks!<br /><br />Photoshop Masters Association";
        f.html(t).effect("highlight",{},1500);
      }
    
      $j(":button:contains('Send')").hide();
      $j(":button:contains('Close')").show();
      $j(":button:contains('Cancel')").hide();
    }
  
  }
  
});  