/****************************************
| ** MCLAREN | LEWIS HAMILTON FORMS **
|
| Created by: Adam Foster
| Date Created: 2008-24-06
| Copyright 2008 Lightmaker Manchester
|
****************************************/

$(document).ready(function(){
	
	if($('.titleh4')[0]) { $(".titleh4").append("<p id='formerrorjs'>Please fill in the following fields correctly:</p>") }
	else { $("h2").after("<p id='formerrorjs'>Please fill in the following fields correctly:</p>") }

	$("#formerrorjs").css({height: '0px', opacity: '0', marginTop: '0px', padding: "0 20px"});
	
	jQuery.validator.addMethod("dateofbirth", function( value, element ) {
		var result = this.optional(element) || value.length == 10 && !/Invalid|NaN/.test(new Date(value));
		return result;
	}, "Please enter a valid date (mm/dd/yyyy)");
	
	jQuery.validator.addMethod("expiry", function( value, element ) {
		var result = this.optional(element) || value.length == 5;
		return result;
	}, "Please enter a valid date (mm/yy)");
	
	jQuery.validator.addMethod("password", function( value, element ) {
		var result = this.optional(element) || value.length > 3;
		return result;
	}, "Password must be 4 or more characters");
	
	jQuery.validator.addMethod("ccnum", function( value, element ) {
	    var result = this.optional(element) || getdigits(value).length > 12 && getdigits(value).length < 19 && regIsNumber(value)  && luhn(getdigits(value));
	    return result;
	}, "Credit Card number is not valid");
	
	jQuery.validator.addMethod("phone", function( value, element) {
        var digits = "0123456789";
        var phoneNumberDelimiters = "()- ext.";
        var validWorldPhoneChars = phoneNumberDelimiters + "+";
        var minDigitsInIPhoneNumber = 10;
        s=stripCharsInBag(value, validWorldPhoneChars);
        return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
    }, "Please enter a valid phone number");
    
    
    jQuery.validator.addMethod("phone2", function( value, element) {
        return this.optional(element) || /^[0-9|\s]+$/.test(value);;
    }, "Please enter a valid phone number2");
    
    
    function isInteger(s)
    {   
        var i;
        for (i = 0; i < s.length; i++)
        {
            // Check that current character is number.
            var c = s.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
        }
        // All characters are numbers.
        return true;
    }
    
    function stripCharsInBag(s, bag)
    { 
        var i;
        var returnString = "";
        // Search through string's characters one by one.
        // If character is not in bag, append to returnString.
        for (i = 0; i < s.length; i++)
        {
            // Check that current character isn't whitespace.
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1) returnString += c;
        }
        return returnString;
    }
		
	function luhn (cc) {
       var sum = 0;
       var i;
     
       for (i = cc.length - 2; i >= 0; i -= 2) {
          sum += Array (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) [parseInt (cc.charAt (i), 10)];
       }
       for (i = cc.length - 1; i >= 0; i -= 2) {
          sum += parseInt (cc.charAt (i), 10);
       }
       return (sum % 10) == 0;
    }
    
    function getdigits (s) {
        return s.replace (/[^\d]/g, "");
    }
		
	function regIsNumber(fData)
    {
        var reg = new RegExp("^[0-9]+$");
        return reg.test(fData)
    }
		
	jQuery.validator.messages.required = "";
	jQuery.validator.messages.email = "Please enter a valid email address (you@domain.com)";
	
	$("#membershipform1").bind("invalid-form.validate", function(e, validator) {
		var errors = validator.numberOfInvalids();
		if (errors) {
			var message = errors == 1
				? '<strong>Error in 1 field</strong> - It has been highlighted below'
				: '<strong>Error in ' + errors + ' fields</strong> -  They have been highlighted below';
			$("#formerrorjs").html(message);
			if( $('#formerror')[0] ){
				$('#formerror').css({display: 'none'})
			}
			$("#formerrorjs").stop().animate({height: '16px', opacity: 1, marginTop: '10px', paddingTop: '5px', paddingBottom: '5px'},600, "easeInOutQuad")
		}
	}).validate();
	
	$("#membershipform2").bind("invalid-form.validate", function(e, validator) {
		var errors = validator.numberOfInvalids();
		if (errors) {
			var message = errors == 1
				? '<strong>Error in 1 field</strong> - Please see below and ensure you tick the check-box to accept the terms and conditions'
				: '<strong>Error in ' + errors + ' fields</strong> -  They have been highlighted below';
			$("#formerrorjs").html(message);
			if( $('#formerror')[0] ){
				$('#formerror').css({display: 'none'})
			}
			$("#formerrorjs").stop().animate({height: '16px', opacity: 1, marginTop: '10px', paddingTop: '5px', paddingBottom: '5px'},600, "easeInOutQuad")
		}
	}).validate();
	
	/*CUSTOM SELECTS*/
	var selectWrapper = '<div class="selectback smallselect dobselect"></div>';
	$("#DobSelects select").wrap(selectWrapper);
	
	$("#membershipcontent select").css({"opacity":0});
	$("#membershipcontent select").each(function() {
		currentSelection = $(this).val();
		$(this).after("<span></span>");
		if($(this).parent().hasClass('dobselect') == false ){
		    $(this).parent().css({backgroundPosition: '0 0'});
		}
		$(this).css({backgroundColor: '#333'});
		$(this).next().text(currentSelection);
	});
	$("#membershipcontent select").change(function() { 
		currentSelection = $(this).val();
		$(this).next().text(currentSelection);
	});
	
	/*BLUR INPUTS*/
	
	$(".inputbox").focus(function () {if($(this).val() == $(this)[0].defaultValue){$(this).val("");}});
	$(".inputbox").blur(function () {if($(this).val() == ""){$(this).val($(this)[0].defaultValue)}	});
	
	/*HIDDEN FIELDS?*/
	
	$("#hiddenformelement").css({ height: '0px', opacity: '0'});
	$("#addnewaddress").click(function () { 
		$("#hiddenformelement").stop().animate({height: 245, opacity: 1},600, "easeInOutQuad")
	})
	
});