//-----------------------------------------------------------------------------
// Hook onload
//-----------------------------------------------------------------------------
window.onload = onLoad;
window.onrefresh = onLoad;

//-----------------------------------------------------------------------------
// Extracts a param from a URL
//-----------------------------------------------------------------------------
function getHTTPObject(){
   if (window.ActiveXObject) 
   	return new ActiveXObject("Microsoft.XMLHTTP");
   else if (window.XMLHttpRequest) 
   	return new XMLHttpRequest();
   else {
      alert("Your browser does not support the functionality to make this request, please upgrade to a later version.");
      return null;
   }
}   

//-----------------------------------------------------------------------------
// Extracts a param from a URL
//-----------------------------------------------------------------------------
function getCaptcha() {
    var date = new Date(); 
    document.getElementById('CaptchaImage').src = "/wp-content/custom/pay/captcha.php?t=" + date.getTime();
}

//-----------------------------------------------------------------------------
// Extracts a param from a URL
//-----------------------------------------------------------------------------
function getURLParam(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if(results == null)
        return "";
    else
        return results[1];
}

//-----------------------------------------------------------------------------
// Sets values appropriately on page load.
//-----------------------------------------------------------------------------
function onLoad() {
    var invoiceNum = document.getElementById("TextInvoiceNum");
    invoiceNum.disabled = "";
    var invoiceAmount = document.getElementById("TextInvoiceAmount");
    invoiceAmount.disabled = "";
    var invoiceCurrency = document.getElementById("SelectCurrency");
    invoiceCurrency.disabled = "";
    var buttonPay = document.getElementById("ButtonPayInvoice");
    buttonPay.disabled = "disabled";
    var checkBoxChecked = document.getElementById("CheckBoxTerms");
    checkBoxChecked.disabled = "";
    var invoiceEmail = document.getElementById("TextEmailAddress");
    invoiceEmail.disabled = "";
    var statusLabel = document.getElementById("LabelStatus");
    statusLabel.innerHTML = "";
    var captchaLabel = document.getElementById("LabelCaptcha");
    captchaLabel.innerHTML = "Please enter the verification text, check the box below and click 'Make Payment' to proceed.";
    
    var urlInvoiceNum = getURLParam("num");
    var urlInvoiceAmount = getURLParam("amount");
    var urlInvoiceCurrency = getURLParam("currency");
    var urlInvoiceEmail = getURLParam("email");
    
    checkBoxChecked.checked = false;
    
    invoiceNum.value = urlInvoiceNum;
    invoiceAmount.value = urlInvoiceAmount;
    invoiceEmail.value = urlInvoiceEmail;
    
    if (urlInvoiceCurrency == null) {
        invoiceCurrency.selectedIndex = "0";
    } else {
    	if (urlInvoiceCurrency == "GBP")
    		invoiceCurrency.selectedIndex = "0";
    	else if (urlInvoiceCurrency == "USD")
    		invoiceCurrency.selectedIndex = "1";
    	else if (urlInvoiceCurrency == "EUR")
    		invoiceCurrency.selectedIndex = "2";
    }
}


//-----------------------------------------------------------------------------
// Submit the hidden form.
//-----------------------------------------------------------------------------
function submitPage() {
    var hiddenForm = document.forms["hiddenPayForm"];
    hiddenForm.submit();
}

//-----------------------------------------------------------------------------
// Provide some feedback to a user if they are just paying an invoice.
//-----------------------------------------------------------------------------
function reportInvoice() {
    var contentDiv = document.getElementById("PaymentContentDiv");
    contentDiv.innerHTML = "Thank you for submitting your invoice request.  Your order will be processed and we will contact you soon.  If you have any enquiries please contact <a href='mailto:sales@selectec.co.uk'>sales@selectec.co.uk</a>."
}

//-----------------------------------------------------------------------------
// Disable input on the form
//-----------------------------------------------------------------------------
function disableInput() {
    var invoiceNum = document.getElementById("TextInvoiceNum");
    var invoiceAmount = document.getElementById("TextInvoiceAmount");
    var invoiceCurrency = document.getElementById("SelectCurrency");
    var invoiceEmail = document.getElementById("TextEmailAddress");
    var buttonPay = document.getElementById("ButtonPayInvoice");
    var checkBoxChecked = document.getElementById("CheckBoxTerms");
    
    invoiceNum.disabled = "disabled";
    invoiceAmount.disabled = "disabled";
    invoiceCurrency.disabled = "disabled";
    invoiceEmail.disabled = "disabled";
    buttonPay.disabled = "disabled";
    checkBoxChecked.disabled = "disabled";    
}

//-----------------------------------------------------------------------------
// Enable input on the form
//-----------------------------------------------------------------------------
function enableInput() {
    var invoiceNum = document.getElementById("TextInvoiceNum");
    var invoiceAmount = document.getElementById("TextInvoiceAmount");
    var invoiceCurrency = document.getElementById("SelectCurrency");
    var invoiceEmail = document.getElementById("TextEmailAddress");
    var buttonPay = document.getElementById("ButtonPayInvoice");
    var checkBoxChecked = document.getElementById("CheckBoxTerms");
    
    invoiceNum.disabled = "";
    invoiceAmount.disabled = "";
    invoiceCurrency.disabled = "";
    invoiceEmail.disabled = "";
    buttonPay.disabled = "";
    checkBoxChecked.disabled = "";    
}

//-----------------------------------------------------------------------------
// Disable input on the form
//-----------------------------------------------------------------------------
function isOnlinePayment() {
    return true;
}


//-----------------------------------------------------------------------------
// Validates the form, using regular expressions to match possible user input.
// The validated values get stored in an array which is returned.  If any
// validation fails, null is returned (and should therefore be checked for 
// in any caller).
//-----------------------------------------------------------------------------
function isFormValidate() {
    var valid = true;
    
    var arrayValues = new Array();

    var invoiceNumLabel = document.getElementById("LabelInvoiceNum");
    var invoiceNum = document.getElementById("TextInvoiceNum");
    
    var invoiceAmountLabel = document.getElementById("LabelInvoiceAmount");
    var invoiceAmount = document.getElementById("TextInvoiceAmount");
    
    var invoiceCurrency = document.getElementById("SelectCurrency");
    
    var invoiceCurrencyLabel = document.getElementById("LabelCurrency");
    var invoiceMethodLabel = document.getElementById("LabelMethod");
    
    var invoiceEMailLabel = document.getElementById("LabelEmail");
    var invoiceEmail = document.getElementById("TextEmailAddress");
    
    var captchaText = document.getElementById("TextCaptcha");
    var captchaLabel = document.getElementById("LabelCaptcha");
    
    invoiceNumLabel.innerHTML = "";
    invoiceAmountLabel.innerHTML = "";
    invoiceCurrencyLabel.innerHTML = "";
    invoiceEMailLabel.innerHTML = "";
    
    captchaLabel.innerHTML="";
    
    if (invoiceNum.value.length == 0) {
        invoiceNumLabel.style.color = "Red";
        invoiceNumLabel.innerHTML = "* Enter your invoice number";
        valid = false;
    } else {
        var regexS = "^(31|51)\\d{4}$"; //[31|51]1234
        var regex = new RegExp(regexS);
        var results = regex.exec(invoiceNum.value);
        if (results == null) {
            invoiceNumLabel.style.color = "Red";
            invoiceNumLabel.innerHTML = "* Enter a valid reference (starts with 31 or 51)";  
            valid = false;      
        } else {
            arrayValues[0] = invoiceNum.value;
        }
    }
    
    if (invoiceCurrency.value.length == 0) {
        invoiceCurrencyLabel.style.color = "Red";
        invoiceCurrencyLabel.innerHTML = "* Enter a currency";
        valid = false;
    } else {
        if (valid == true)
            arrayValues[1] = invoiceCurrency.value;
    }
    
    if (invoiceAmount.value.length == 0) {
        invoiceAmountLabel.style.color = "Red";
        invoiceAmountLabel.innerHTML = "* Enter the amount to pay";
        valid = false;
    } else {
        var regexS = "^([0]\\.[9]{2}|[1-9]\\.\\d{2}|[1-9][0-9]{0,3}\\.\\d{2}|[1-9]\\d{0,3})$";
        var regex = new RegExp(regexS);
        var results = regex.exec(invoiceAmount.value);
        if (results == null) {
            invoiceAmountLabel.style.color = "Red";
            invoiceAmountLabel.innerHTML = "* Enter a valid amount";  
            valid = false;      
        } else {
            if (valid == true)
                arrayValues[2] = invoiceAmount.value;
        }
    }

    if (invoiceEmail.value.length == 0) {
        invoiceEMailLabel.style.color = "Red";
        invoiceEMailLabel.innerHTML = "* Enter your email address";
        valid = false;
    } else {
        var regexS = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        var regex = new RegExp(regexS);
        var results = regex.exec(invoiceEmail.value);
        if (results == null) {
            invoiceEMailLabel.style.color = "Red";
            invoiceEMailLabel.innerHTML = "* Enter a valid email address";  
            valid = false;      
        } else {
            if (valid == true)
                arrayValues[3] = invoiceEmail.value;
        }
    }
    
    if (captchaText.value.length == 0) {
        captchaLabel.style.color = "Red";
	captchaLabel.innerHTML = "* Enter the verification text";
        valid = false;
    } else {
        var regexS = "^[a-zA-Z0-9]{6}$";
	var regex = new RegExp(regexS);
        var results = regex.exec(captchaText.value);
        if (results == null) {
            captchaLabel.style.color = "Red";
            captchaLabel.innerHTML = "* Enter a valid verification string";  
            valid = false;      
        } else {
            arrayValues[4] = captchaText.value;
        }
    }    
    
    if (valid == true)
        return arrayValues;
    else
        return null;
}


//-----------------------------------------------------------------------------
// Enable the 'Make Payment' button when the T&C's check box is ticked.
//-----------------------------------------------------------------------------
function checkBoxTermsChanged() {
    var checkBoxChecked = document.getElementById("CheckBoxTerms");
    var buttonPayInvoice = document.getElementById("ButtonPayInvoice");
    if (checkBoxChecked.checked == true) {
        buttonPayInvoice.disabled = "";
    } else {
        buttonPayInvoice.disabled = "disabled";
    }
}

//-----------------------------------------------------------------------------
// The main function to start the pay process
//-----------------------------------------------------------------------------
function payInvoiceClicked() {
    var arrayValues = isFormValidate();
    var statusLabel = document.getElementById("LabelStatus");
    if (arrayValues != null) {
        statusLabel.style.color = "Gray";
        statusLabel.innerHTML = "Processing, please wait...";
        var hiddenForm = document.forms["hiddenPayForm"];
        hiddenForm.cartId.value = arrayValues[0];
        hiddenForm.currency.value = arrayValues[1];
        hiddenForm.amount.value = arrayValues[2];
        hiddenForm.email.value = arrayValues[3];
        hiddenForm.desc.value = "Payment for Selectec document ref: " + arrayValues[0];
        
        var queryString = "?num=" + arrayValues[0] + "&curr=" + arrayValues[1] + "&amount=" + arrayValues[2] + "&email=" + arrayValues[3] + "&captcha=" + arrayValues[4];
        if (sendEmail(queryString)) {
           disableInput();
        }
 
    } else {
        statusLabel.style.color = "Red";
        statusLabel.innerHTML = "* Please correct the form where indicated";
    }
}

//-----------------------------------------------------------------------------
// Send the email
//-----------------------------------------------------------------------------
function sendEmail(queryString){  
    httpObject = getHTTPObject();
    if (httpObject != null) {
        httpObject.open("GET", "/wp-content/custom/pay/email.php" + queryString, true);
        httpObject.send(null);
        httpObject.onreadystatechange = setReturn;
        return true;
    } else {
    	return false;
    }
}

//-----------------------------------------------------------------------------
// The return value from the email process
//-----------------------------------------------------------------------------
function setReturn(){
    if(httpObject.readyState == 4) {
    	var statusLabel = document.getElementById("LabelStatus");	
    	var captchaLabel = document.getElementById("LabelCaptcha");
        if (httpObject.responseText == "SUCCESS") {
      	    submitPage();
        } else if (httpObject.responseText == "CAPTCHA") {
            statusLabel.innerHTML = "";
            captchaLabel.style.color = "Red";
	    captchaLabel.innerHTML = "* Incorrect verification text, please try again or get a new image.";
	    enableInput();
        } else if (httpObject.responseText == "ERROR") {
            statusLabel.innerHTML = "";
            captchaLabel.style.color = "Red";
	    captchaLabel.innerHTML = "* Unable to send confirmation email.";
	    enableInput();
        }
    }
 
}