﻿// js to handle validation and submitting of ask question form and report listing pop up
var sendingSellerQuestion = false;

$(document).ready(function() {

    $("#contactForm").validate({
        errorElement: "p",
        errorPlacement: function(error, element) {
            error.insertAfter(element);
        },
        onkeyup: false,
        onsubmit: true,
        submitHandler: function(form) {
            $('.error').hide();
            var email = $("input#q_email").val();
            var phone = $("input#q_phone").val();
            var text = $("textarea#q_text").val();
            var advertid = $("input#q_advertid").val();
            
            /* to stop double clicks on IE coming through, never want to send more than one per details page anyway */
           if (sendingSellerQuestion == true) return;
           sendingSellerQuestion = true;

            if (email == "") {
                $("label#q_email_error").show();
                $("label#q_email").focus();
                return false;
            }

            var dataString = 'advertid=' + advertid + '&email=' + email + '&phone=' + phone + '&text=' + text;
            //alert(dataString); return false;

            $.ajax({
                type: "POST",
                url: form.action,
                data: dataString,
                success: function() {
                    $('#contactForm').html("<div class='contactSeller' id='message'></div>");
                    $('#message').html("<h3>Your question has been sent!</h3>")
                  .append("<p>The seller will be in touch soon.</p><img id='checkmark' src='../../Content/images/check.png' />");
                },
                error: function() {
                    // add whatever debug you want here.
                $('#contactForm').html("<div class='contactSeller' id='message'><p class='error'>Your email could not be sent. Please try again.</p></div>");
                 }
            });
            return false;
        },
        rules: {
            q_email: {
                required: true,
                email: true,
                maxlength: 50
            },
            q_text: {
                required: true,
                validQuestion: true,
                maxlength: 2000
            }
        },
        messages: {
            q_email: {
                required: "email address is required so the seller can contact you about your question.",
                email: "email address must be valid.",
                maxlength: jQuery.format("email address can not exceed {0} characters in length.")
            },
            q_text: {
                required: "question is required",
                maxlength: jQuery.format("question can not exceed {0} characters in length."),
                validQuestion: "Invalid characters in the question. Please exclude <, > and \\"
            }
        }
    });

    $("#reportLink").click(function() { openReportListingModal("reportListingBox", function() { sendReportListingEmail(); }); return false; });
    
});

  // check for unwanted characters
  $.validator.addMethod('validQuestion', function(value) {
      var result = true;

      // unwanted characters
      var iChars = "\\<>";
      for (var i = 0; i < value.length; i++) {
          if (iChars.indexOf(value.charAt(i)) != -1) {
              return false;
          }
      }
      return result;
  }, '');


  //
  // report listing popup logic
  //
  var sendingReportListingEmail = false;

  // Opens up the report listing modal popup
  var openReportListingModal = function(id, submitEvent) {
    $('#' + id + ' form').validate({
        errorContainer: "#" + id + " .validation",
        errorLabelContainer: "#" + id + " .validation ul",
        wrapper: "li",
        submitHandler: submitEvent
    });
      
    $("#" + id + " .cancel").unbind().click(function() { closeReportListingModal(); return false; });
    
    $.nyroModalManual({
        modal: true,
        type: '#' + id,
        from: document
    });
  }
  
  // Closes the repost listing modal popup and clears the validation errors
  var closeReportListingModal = function(empty) {
      $("#rtlMyName").val('');
      $("#rtlMyEmail").val('');
      $("#rtlComments").val('');
      $("#reportListingValidation").hide();
      if (empty) $("#nyroModalContent").empty();
      $.nyroModalRemove();
  }
  
  // Sends the email if not already doing so
  var sendReportListingEmail = function() {
      if (sendingReportListingEmail == true) {
          return;
      }

      sendingReportListingEmail = true;
      
      $.ajax({
          data: "rtlMyName=" + $("#rtlMyName").val() + "&rtlMyEmail=" + $("#rtlMyEmail").val() + "&rtlComments=" + $("#rtlComments").val(),
          url: $("#reportListingForm").attr("action"),
          type: "post",
          success: reportListingEmailSuccess,
          error: reportListingEmailError
      });
  }

  var reportListingEmailSuccess = function() {
      showModalMessage("reportListingBox", "Email Sent!", "Your email has been sent.", "sent");
      sendingReportListingEmail = false;
  }

  var reportListingEmailError = function() {
      showModalMessage("reportListingBox", "Error!", "Your email could not be sent. Please try again.", "error");
      sendingReportListingEmail = false;
  }

  var showReportListingModalMessage = function(id, title, message, titleClass) {
      var modal = $("#nyroModalContent");
      var box = $('#' + id).append($(modal.find("form")));
      box.find(":text").val("");
      box.find(":input:not(select):not(:button):not(:reset):not(:submit)").val("");
      var feedback = $("<div id=\"modalFeedback\"></div>").append($("<h4></h4>").text(title).addClass(titleClass)).append($("<p></p>").text(message));
      feedback.append($("<a href=\"#\" title=\"Close This Window\"></a>").text("Close This Window.").addClass("close").click(function() { closeModal(true); return false; }));
      modal.empty().append(feedback);
  }


