﻿String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

$(function() {
    $('.numeric').numeric();
    $('.decimal').numeric({allow:"."});
});

function SubmitForm() {
    var form = $('form').get(0);
    form.action = "https://ssl.selectpayment.com/HPP/Pages/SecureCheckGateway.aspx";
    $('#__VIEWSTATE').remove();
}

function ValidateForm() {
    var validation      = $("#validationResults");
    var validationList  = $("#validationList");
    validationList.html('');
    
    var valid = CheckForm();
    
    if(valid)
    {
        validation.hide();
        SubmitForm();
    }
    else
        validation.show();
        
    return valid;
}

function CheckForm() {
    var valid = true;
    
    //Check required
    $("div#payform table .required").each(function () {
        var item = $(this);
        if(item.val().trim() == "") {
            InvalidateItem(item, item.attr('title') + " is required.");
            valid = false;
        }
        else 
            item.removeClass("invalid");
    });
    
    var customerAccountNumber = $('#CustomerNumber'); //Check account number
    if(customerAccountNumber.val().length < 4) {
        InvalidateItem(customerAccountNumber, "Customer Account Number must be at least 4 numbers in length.");
    }
    
    var phone = $('#DayPhone'); //Check phone number
    if(phone.length > 0 && phone.val() != "") {
        if(!(/\(?\d{3}\)?(-| )?\d{3}-?\d{4}( .+)?/).test(phone.val())) {
            InvalidateItem(phone, "Phone number is not valid. ex) 555-234-2444 ext 23");
            valid = false;
        }
    }
    
    var amount = $('#Amount'); //Check amount
    if(amount.val() != "") {
        if(!(/^\d+?(\.\d{2})?$/).test(amount.val()) || amount <= 0) {
            InvalidateItem(amount, "Amount entered is not valid.");
            valid = false;
        }
    }
    
    return valid;
}

function checkPhone(sender, e) {
	if(e.keyCode == 8) return;
	var value = sender.value, newValue = '';
	if(value.match(/\d{3}-\d{3}-\d{4}/)) return;
	if(value.length >= 1 && !value.charAt(value.length - 1).match(/[\d-]+/)) return;
	for(var i = 0; i < value.length && i < 12; i++) {
		if(i != 3 && i != 7 && value.charAt(i).match(/\d/)) newValue += value.charAt(i);
		else if((i == 3 || i == 7) && value.charAt(i) != '-') newValue += '-' + value.charAt(i);
		else newValue += value.charAt(i);
	}
	sender.value = newValue;
}

function InvalidateItem(element, message) {
    element.addClass("invalid");
    addListItem($("#validationList"), message);
}

function addListItem(parent, message) {
    parent.append("<li>" + message + "</li>");
}