$j(document).ready(function() {
  
  var firstname = $j("#firstname"),
    firstnameNL = $j("#firstnameNL"),
    lastname = $j("#lastname"),
    emailCF = $j("#emailCF"),
    emailRP = $j("#emailRP"),
    emailNL = $j("#emailNL"),
    subject = $j("#subject"),
    department = $j("#department"),
    message = $j("#message"),
    allFields = $j([]).add(firstname).add(lastname).add(emailCF).add(subject).add(department).add(message).add(emailRP).add(emailNL).add(firstnameNL),
    tips = $j("#validateTips"),
    tipsRP = $j("#validateTipsRP"),
    tipsNL = $j("#validateTipsNL")
    cfURL = 'http://www.gox.com/public/3.cfm';
    wlURL = 'http://c.gox.com/whitelist';
    
   function updateTips(t) {
    tips.text(t).effect("highlight",{},1500);
  }
  
   function updateTipsRP(t) {
    tipsRP.text(t).effect("highlight",{},1500);
  }  
  
   function updateTipsNL(t) {
    tipsNL.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 checkLengthRP(o,n,min,max) {
    if ( o.val().length > max || o.val().length < min ) {
      o.addClass('ui-state-error');
      updateTipsRP("The length of your " + n + " must be between "+min+" and "+max+" characters.");
      return false;
    } else {
      return true;
    }
  }  
  
  function checkLengthNL(o,n,min,max) {
    if ( o.val().length > max || o.val().length < min ) {
      o.addClass('ui-state-error');
      updateTipsNL("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;
    }
  }
  
  function checkRegexpRP(o,regexp,n) {
    if ( !( regexp.test( o.val() ) ) ) {
      o.addClass('ui-state-error');
      updateTipsRP(n);
      return false;
    } else {
      return true;
    }
  }    
  
  function checkRegexpNL(o,regexp,n) {
    if ( !( regexp.test( o.val() ) ) ) {
      o.addClass('ui-state-error');
      updateTipsNL(n);
      return false;
    } else {
      return true;
    }
  }   
  
  $j("#dialogcf").dialog({
    title: 'WE LOOK FORWARD TO HELPING YOU',
    width:450,
    buttons: {
      'Contact Support': function() {
        
        var bValid = true;
        
        allFields.removeClass('ui-state-error');

        bValid = bValid && checkLength(firstname,"first name",2,30);
        bValid = bValid && checkLength(lastname,"last name",2,30);
        bValid = bValid && checkLength(emailCF,"email address",6,30);
        bValid = bValid && checkLength(subject,"subject line",4,15);
        bValid = bValid && checkLength(message,"message body",10,500);
        
       //this is from jquery ui example 
       // 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, "eg. ui@jquery.com" );
       
       //http://fightingforalostcause.net/misc/2006/compare-email-regex.php
        bValid = bValid && checkRegexp(emailCF,/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i, "The email address you entered was invalid.");
        //bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");

        if (bValid) {
          HandleFormSubmition();
          //$(this).dialog('close');
          updateTips("contacting support ...");
        }
      }
      ,'Close Dialog': function() {
        $j(this).dialog("close"); 
       // location.href=cfURL;
      }
      ,'Cancel': function(){
        $j(this).dialog("close");
      }
    },
    close: 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("#dialogrp").dialog({
    title: 'RETRIEVE LOGIN CREDENTIALS',
    width:450,
    buttons: {
      'Get Login': function() {
       
        var bValid = true;

        allFields.removeClass('ui-state-error');

        bValid = bValid && checkLengthRP(emailRP,"email address",6,30);

        //http://fightingforalostcause.net/misc/2006/compare-email-regex.php
        bValid = bValid && checkRegexpRP(emailRP,/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i , "The email address you entered was invalid.");
        //bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");

        if (bValid) {
          HandleRetrievePassword();
          //$(this).dialog('close');
          updateTipsRP("validating email ...");
        }
      }
      ,'Contact Support': function() { 
        $j(this).dialog("close"); 
        $j("#dialogcf").dialog("open");
        $j('#test').text("message length: " + $j('#message').val().length);
      }
      ,'Close Dialog': function() {
        $j(this).dialog("close"); 
        window.location.replace(cfURL);
      }      
      ,'Cancel': function(){
        $j(this).dialog("close");
      }
      ,'Back to Login Screen': function(){
        $j(this).dialog("close");
      }      
    },
    close: function() {
      allFields.val('').removeClass('ui-state-error');
      var f = $j("#passwordForm");
      f.show();
      f = $j("#passwordMessage");
      f.hide();
      updateTipsRP("Your registered email address is required.");
    }
  });
  
  $j("#dialognl").dialog({
    title: 'FREE HD TRAINING',
    width:256,
    open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').show(); },
    buttons: {
      'Sign Me Up': function() {
       
        var bValid = true;

        allFields.removeClass('ui-state-error');
        
        bValid = bValid && checkLengthNL(firstnameNL,"first name",2,30);
        bValid = bValid && checkLengthNL(emailNL,"email address",6,30);

        //http://fightingforalostcause.net/misc/2006/compare-email-regex.php
        bValid = bValid && checkRegexpNL(emailNL,/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i , "The email address you entered was invalid.");
        //bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");

        if (bValid) {
          HandleSubscribe();
          //$(this).dialog('close');
          updateTipsNL("adding email ... please stand by ...");
        }
      } 
      ,'Cancel': function(){
        $j(this).dialog("close");
      }
      ,'Close Dialog': function() {
        $j(this).dialog("close"); 
       // location.href=cfURL;
      }
      ,'Contact Support': function() { 
        $j(this).dialog("close"); 
        $j("#dialogcf").dialog("open");
        $j(":button:contains('Cancel')").show();
        $j('#test').text("message length: " + $j('#message').val().length);
      }    
    },
    close: function() {
      allFields.val('').removeClass('ui-state-error');
      var f = $j("#subscribeForm");
      f.show();
      var g = $j("#privacyBlock");
      g.show();       
      f = $j("#subscribeMessage");
      f.hide();
      updateTipsNL("All form fields are required.");
    }
  }); 

  //$j(":button:contains('Get Login')").show();
  //$j(":button:contains('Contact Support')").hide();
  
  // This shows the user the current message character count in the contact support modal dialog window.
  $j('#message').keyup(function() {
    $j('#test').text("message length: " + $j('#message').val().length);
  });
  
  // This is called from the login page Get Login Details button, OR a link with an ID of submitP.
  $j("#submitP" )
    .click(function(e) {
      e.preventDefault();
      $j("#dialogrp" ).dialog( "open" );
      $j(":button:contains('Contact Support')").hide();
      $j(":button:contains('Close Dialog')").hide();
      $j(":button:contains('Get Login')").show();
      $j(":button:contains('Cancel')").show();
      $j(":button:contains('Back to Login Screen')").hide();
    }); 
    
    // This is called from a link/button with an id of contactUS.
    $j("#contactUs").click(function(e){
      e.preventDefault();
      $j("#dialogcf" ).dialog( "open" );
      $j(":button:contains('Contact Support')").show();
      $j(":button:contains('Cancel')").show();
      $j(":button:contains('Close Dialog')").hide();
      $j(":button:contains('Get Login')").hide();
    });
    
    // This is called from a link/button with a class of contactUS.
    $j(".contactUs").click(function(e){
      e.preventDefault();
      $j("#dialogcf" ).dialog( "open" );
      $j(":button:contains('Contact Support')").show();
      $j(":button:contains('Cancel')").show();
      $j(":button:contains('Close Dialog')").hide();
      $j(":button:contains('Get Login')").hide();
    });
    
    // This is called from a link/button with a class of subscribe.
    $j(".subscribe").click(function(e){
      e.preventDefault();
      $j("#dialognl" ).dialog( "open" );
      $j(":button:contains('Sign Me Up')").show();
      $j(":button:contains('Cancel')").hide();
      $j(":button:contains('Close Dialog')").hide();
      $j(":button:contains('Contact Support')").hide();
      $j('#firstnameNL').focus();
    });       

});

function HandleFormSubmition(){
  $j.getJSON(
    "/com/forms.cfc?wsdl",
    {
      method : "contactForm",
      firstname : $j( "#firstname" ).val(),
      lastname : $j( "#lastname" ).val(),
      email : $j( "#emailCF" ).val(),
      subject : $j( "#subject" ).val(),
      department: $j( "#department" ).val(),
      message : $j( "#message" ).val()
    },
    handleFormCallback

  );
}
 
function HandleRetrievePassword(){
  $j.getJSON(
    "/com/forms.cfc?wsdl",
    {
      method : "retrivePassword",
      email : $j( "#emailRP" ).val()
    },
    handleRetrievePasswordCallback
  );
}

function handleFormCallback(aResult, aState){
  var tips = $j("#validateTips");
  var t = "Server Communication Status: " + aState + ".";
  tips.text(t).effect("highlight",{},1500);
  var f = $j("#contactusForm");
  f.hide();
  var f = $j("#contactusMessage");
  if((aState == "success") && (aResult.SUCCESS)){
    t = "<strong>Thanks for contacting us "+ aResult.FIRSTNAME +"</strong>.  You should receive an email confirmation of your request shortly (we sent it to <strong>"+ aResult.EMAIL +"</strong>). We look forward to helping you.<br /><br />Best,<br /><br />Gregory Matthews, Publisher<br />HDR Phototgraphy Club";    
    f.html(t).effect("highlight",{},1500);
    $j(":button:contains('Contact Support')").hide();
    $j(":button:contains('Cancel')").hide();
    $j(":button:contains('Close Dialog')").show();    
  } else {
    t = "<strong><span style=\"color: #cc0000;\">We experienced an error communicating with the mail program</span>.</strong><br /><br />Please use the <strong>Contact Support</strong> button below and tell us what you were doing when this error occurred along with any other details that might help us.<br /><br />Chances are our ninja dudes are already on it, but just in case, please let us know.<br /><br />Thanks!<br /><br />Gregory Matthews, Publisher<br />HDR Photography Club";
    f.html(t).effect("highlight",{},1500);
    $j(":button:contains('Contact Support')").show();
    $j(":button:contains('Cancel')").show();
    $j(":button:contains('Close Dialog')").hide();
  }
  
}

function handleRetrievePasswordCallback(aResult, aState){
  var  tipsRP = $j("#validateTipsRP");
  var t = "Server Communication Status: " + aState + ".";
  tipsRP.text(t).effect("highlight",{},1500);
  var  f = $j("#passwordForm");
  f.hide();
  var  f = $j("#passwordMessage");
  if((aState == "success") && (aResult.SUCCESS)){
    if(aResult.NOEMAIL){
      t = "<strong>We were unable to locate a Member Account using the email address " + "'" + aResult.EMAIL + "'" + "</strong>.<br /><br />Please feel free to try again, or you may contact our Support Desk below for further assistance.<br /><br />Best,<br /><br />Gregory Matthews, Publisher<br />HDR Phototgraphy Club";
      $j(":button:contains('Get Login')").hide();
      $j(":button:contains('Contact Support')").show();
      $j(":button:contains('Cancel')").show();
    } else {
      t = "<strong>Thanks " + aResult.FIRSTNAME +".  We've found your account and emailed your login details to " + "'" + aResult.EMAIL + "'" + "</strong>.<br /><br />Please check your email now and use those credentials to login.<br /><br />Best,<br /><br />Gregory Matthews, Publisher<br />HDR Phototgraphy Club";
      $j(":button:contains('Get Login')").hide();
      $j(":button:contains('Cancel')").hide();
      $j(":button:contains('Close Dialog')").hide();
      $j(":button:contains('Contact Support')").hide();
      $j(":button:contains('Back to Login Screen')").show();
    }
    f.html(t).effect("highlight",{},500);
  } else {
    t = "<strong><span style=\"color: #cc0000;\">We experienced an error communicating with the mail program</span>.</strong><br /><br />Please use the <strong>Contact Support</strong> button below and tell us what you were doing when this error occurred along with any other details that might help us.<br /><br />Chances are our ninja dudes are already on it, but just in case, please let us know.<br /><br />Thanks!<br /><br />Gregory Matthews, Publisher<br />HDR Photography Club";
    $j(":button:contains('Get Login')").hide();
    $j(":button:contains('Cancel')").show();
    $j(":button:contains('Contact Support')").show();
    f.html(t).effect("highlight",{},1500);
  }
}
