// AJAX Register Form for use with jQuery
// From jQuery Forms Plugin
// Modified: CVL, WebVentures  090510

$(document).ready(function() { 
// Sign In form
    var signIn_options = { 
        target: '#output1', // replacement target
        resetForm: true
    }; 

  $('#signIn').ajaxForm(signIn_options); 

// Membership Select form
    var nmf_options = { 
        target: '#output1', // primary replacement target
        url: '/bookshop/ajax?_next_page_=MembershipMaint',
        resetForm: true
    }; 

	$("#newMemberForm").validate({
		onkeyup: false,
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'You missed 1 required field. It has been highlighted below'
					: 'You missed ' + errors + ' required fields.  They have been highlighted below';
				$("div.error span").html(message);
				$("div.error").show();
			} else {
				$("div.error").hide();
			}
		},
		submitHandler: function() {
			$("div.error").hide();
      if ($('input#this_member').val() == "Use This Member") {
        $("#newMemberForm").unbind('submit');
        $("#newMemberForm").submit();
        
      } else {
        $("#newMemberForm").ajaxSubmit({
          target: '#output1', // primary replacement target
          url: '/bookshop/ajax?_next_page_=MembershipMaint'
        });
			}
 		}
 	});
/* 	
  $(function () { // make this code initialize when DOM loads
    $('#newMemberForm').submit(function () { // optional: replace "form" with whatever CSS selector you want (ex: ID or class)
      if ($('input#this_member').val() == "Use This Member") {
  //      $("#modalMembershipSelectWindow").hide();
  //      modal('#modalMembershipSelectWindow');
        alert('NMF About to submit');
  //          $('input#this_member', this).replaceWith('<p><strong>Sending...</strong></p>'); // optional: change "Sending..." to something else
  //      modal('modalMembershipSelectWindow');
        $("#newMemberForm").unbind('submit');
        $("#newMemberForm").submit();
        return false;
      } else  {
        alert('Normal Ajax submit');
//        $('#newMemberForm').ajaxForm(nmf_options);   // used in MembershipMaint only
        $("#newMemberForm").ajaxSubmit({
          target: '#output1', // primary replacement target
          url: '/bookshop/ajax?_next_page_=MembershipMaint'
//          resetForm: true
        });
      }
    });
  });
*/  
// Sign Up form
  var email_found = '<p id="signin_greeting" class="large">This email address is on file either because you ' +
    'have registered previously or because you are a Co-op member. ' +
    'Please Sign In here or use the Forgot Password link.</p>';

  jQuery.validator.addMethod("password", function( value, element ) {
		var result = this.optional(element) || value.length >= 6 && /\d/.test(value) && /[a-z]/i.test(value);
		if (!result) {
			element.value = "";
			var validator = this;
			setTimeout(function() {
				validator.blockFocusCleanup = true;
				element.focus();
				validator.blockFocusCleanup = false;
			}, 1);
		}
		return result;
	}, "Your password must be at least 6 characters long and contain at least one number and one letter.");

  jQuery.validator.addMethod("postcode", function(postcode, element) {
    return this.optional(element) || AU_PostcodeCheck();    // checks for non-AU
  }, "Please specify a valid postcode matching the state.");
  
//  jQuery.validator.addMethod("gradyear", function(value, element) {
//    return $("input.gradyear").mask("9999");
//  }, "Your graduation year must be 4 digits");

	// a custom method making the default value for companyurl ("http://") invalid, without displaying the "invalid url" message
///	jQuery.validator.addMethod("defaultInvalid", function(value, element) {
//		return value != element.defaultValue;
//	}, "");
	
//	jQuery.validator.addMethod("billingRequired", function(value, element) {
//		if ($("#bill_to_co").is(":checked"))
//			return $(element).parents(".subTable").length;
//		return !this.optional(element);
//	}, "");
	
	jQuery.validator.messages.required = "";
	
	$("#profileForm").validate({
		onkeyup: false,
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'You missed 1 required field. It has been highlighted below'
					: 'You missed ' + errors + ' required fields.  They have been highlighted below';
				$("div.error span").html(message);
				$("div.error").show();
			} else {
				$("div.error").hide();
			}
		},
		submitHandler: function() {
			$("div.error").hide();
      if ($("#step").val() == "complete") {
        $("#profileForm").unbind('submit');
        if (!$("#profileForm").beenSubmitted) {
          $("#profileForm").beenSubmitted = true;
          $("#profileForm").submit();
        }
//        $("#profileForm").submit();
        
      } else {
        $("#profileForm").ajaxSubmit({
          target: "#output2",       // form extension replacement
          url: "/bookshop/ajax?_next_page_=CustomerAjaxRegister"
        });
			}
 		},

 		rules: {
      new_user_home_phone: {
        required: "#home_pref:checked"
      },
      new_user_work_phone: {
        required: "#work_pref:checked"
      },
      new_user_mobile_phone: {
        required: "#mobile_pref:checked"
      }
    }, 

		messages: {
      new_user_home_phone: {
        required: "Preferred Contact Number Required."
      },
      new_user_work_phone: {
        required: "Preferred Contact Number Required."
      },
      new_user_mobile_phone: {
        required: "Preferred Contact Number Required."
      },
			password2: {
				required: " ",
				equalTo: "Please enter the same password as above"	
			},
			new_user_email: {
          required: " ",
          email: "Please enter a valid email address"
      },
      new_user_email2: {
        required: " ",
        email: "Please enter a valid email address",
        equalTo: "Please enter the same email as above",
        remote: function() {
          $("#signin_greeting").replaceWith(email_found);
          $("#cust_email").val($("input[name=new_user_email2]").val()); // prefill modal form
          $("#modalSigninWindow").show();
          // need to set next page as a home page or checkout
        }
      },
			member_number: {
          remote: jQuery.validator.format('<div class="clear"></div><div id="member_claimed" class="emailerror">' +
          '<br /><br /><img src="/page_images/warning_exclaim_mild.gif" alt="Warning!" width="24" height="24" style="float:left; margin: -5px 10px 0px 0px;" />' +
          'We don’t have a record of this member number.  Please check your Membership Card and if this is the number please contact the Webhelp department for assistance.' +
          '<div class="clear"></div><br />'),
          maxlength: "Your member number is 7 or fewer digits long"
      } 
		}
	});

  $("#home_pref").click(function() {
    $("#home_phone").valid();
  });
  $("#work_pref").click(function() {
    $("#work_phone").valid();
  });
  $("#mobile_pref").click(function() {
    $("#mobile_phone").valid();
  });
	
  $(".resize").vjustify();
  $("div.buttonSubmit").hoverClass("buttonSubmitHover");

  if ($.browser.safari) {
    $("body").addClass("safari");
  }
  
  // state select listbox
  var AU_state = 
    '<select class="formbox short flL" id="state" name="new_user_state" tabindex="12">' +
    '<option value="ACT">Australian Capital Territory</option>' +
    '<option selected="selected" value="NSW">New South Wales</option>' +
    '<option value="NT">Northern Territory</option>' +
    '<option value="QLD">Queensland</option>' +
    '<option value="SA">South Australia</option>' +
    '<option value="TAS">Tasmania</option>' +
    '<option value="VIC">Victoria</option>' +
    '<option value="WA">Western Australia</option>' +
    '</select>';
  var INT_state = 
  '<input class="formbox short flL" id="state" type="text" name="new_user_state" value="" tabindex="12" onkeyup="checkLength(this, 20);" />';
	var AU_phone_msg = '<span class="phone_msg">&nbsp;<small>Please include Area Code</small></span>';
	var INT_phone_msg = '<span class="phone_msg">&nbsp;<small>Please include Country and Area Codes</small></span>';

  /* set a default of AU */
  if ($('select#country_code').val() == "AU") {
    $("input.phone").mask("(99) 9999 9999");  /* AU style */
    $(".phone_msg").replaceWith(AU_phone_msg);
    $("input.mobile").mask("9999 999 999");  /* AU style */
    $("input.postcode").mask("9999");         /* AU style */
    $("input.postcode").rules("add", {required: true});
    $("#state").replaceWith(AU_state);
  }

  /* change mask formats and required fields if International */
  $('select#country_code').change( function() {
    if ($('select#country_code').val() == "AU") {
      $("input.phone").mask("(99) 9999 9999");  /* AU style */
      $(".phone_msg").replaceWith(AU_phone_msg);
      $("input.mobile").mask("9999 999 999");   /* AU style */
      $("input.postcode").mask("9999");         /* AU style */
      $("input.postcode").rules("add", {required: true});
      $("#state").replaceWith(AU_state);
    } else {
      $("input.phone").unmask();            /* no style */
      $(".phone_msg").replaceWith(INT_phone_msg);
      $("input.mobile").unmask();           /* no style */
      $("input.postcode").unmask();         /* no style */
      $("input.postcode").rules("add", {required: false});
      $("#state").replaceWith(INT_state);
    }
  });


    function AU_PostcodeCheck() {
      if ($('select#country_code').val() != "AU") return true;
    // Note the leading zero [e.g. 0299] was removed and values are couplets of min and max
    var NSW = [1000, 1999, 2000, 2599, 2619, 2898, 2921, 2999];
    var ACT = [200, 299, 2600, 2618, 2900, 2920];
    var VIC = [3000, 3999, 8000, 8999];
    var TAS = [7000, 7799, 7800, 7999];
    var QLD = [4000, 4999, 9000, 9999];
    var SA  = [5000, 5799, 5800, 5999];
    var WA  = [6000, 6797, 6800, 6999];
    var NT  = [800, 899, 900, 999];
    var states = [NSW, ACT, VIC, TAS, QLD, SA, WA, NT];
    var state_abrev = ["NSW", "ACT", "VIC", "TAS", "QLD", "SA", "WA", "NT"];   // NB not alphabetical
    var postcode;
    
    if ($("#postcode").val().charAt(0) == '0') {
      postcode = parseInt($("#postcode").val().substring(1,4));    // drops first leading zeros
    } else {
      postcode = parseInt($("#postcode").val());
    }
    for (i = 0; i < states.length; i++) {
      for (j = 0; j < (states[i].length-1); j++) {
        if (postcode >= states[i][j] && postcode <= states[i][j+1]) {
          if ($("#state").val().toUpperCase() == state_abrev[i]) {
            postcode_state =state_abrev[i];
            return true;
          }
        }
        j++;  // work in pairs of range values so double increment
      }
    }
    return false;
  };
/*
  function nmf_display_new_member() {
      alert('NMF About to submit');
      modal("#modalMembershipSelectWindow");
      window.location.href='/bookshop/action_so/MembershipMaint';
    }
    return false;
  };
*/  

   
  var creditcard = $("#creditcard").mask("9999 9999 9999 9999");

  $("#cc_type").change(
    function() {
      switch ($(this).val()){
        case 'amex':
          creditcard.unmask().mask("9999 999999 99999");
          break;
        default:
          creditcard.unmask().mask("9999 9999 9999 9999");
          break;
      }
    }
  );

  // toggle optional billing address
  var subTableDiv = $("div.subTableDiv");
  var toggleCheck = $("input.toggleCheck");
  toggleCheck.is(":checked")
  	? subTableDiv.hide()
	: subTableDiv.show();
  $("input.toggleCheck").click(function() {
      if (this.checked == true) {
        subTableDiv.slideUp("medium");
        $("form").valid();
      } else {
        subTableDiv.slideDown("medium");
      }
  });


// start accordian if specified
//	$(function() {
//		$("#accordion").accordion();
//	});

});


$.fn.vjustify = function() {
    var maxHeight=0;
    $(".resize").css("height","auto");
    this.each(function(){
        if (this.offsetHeight > maxHeight) {
          maxHeight = this.offsetHeight;
        }
    });
    this.each(function(){
        $(this).height(maxHeight);
        if (this.offsetHeight > maxHeight) {
            $(this).height((maxHeight-(this.offsetHeight-maxHeight)));
        }
    });
};

$.fn.hoverClass = function(classname) {
	return this.hover(function() {
		$(this).addClass(classname);
	}, function() {
		$(this).removeClass(classname);
	});
};

 
