var aml_error = Array();
var aml_entry_elements = Array();
var aml_warning_message = Array();

if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

function aml_trim(stringToTrim) 
{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}


function aml_contact_email_validate(elem)
{
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

	if(elem.value.match(emailExp)){
		return true;
	}else{
		//alert(helperMsg);
		//elem.focus();
		return false;
	}
}

function aml_check_if_number_pressed(p_this,p_evt,p_type) 
{
    var value =  p_this.value;
    var charCode = (p_evt.which) ? p_evt.which : event.keyCode

    //alert(p_this.value);
    if(p_type == 'integer')
    {
        if(charCode < 48 || charCode > 57)
        {        
            return false;
        }        
    }
    else if(p_type == 'float')
    {
        if(charCode != 46 && (charCode < 48 || charCode > 57))
        {        
            return false;
        }
    }
    
    // Only allow one full stop.
    if(p_type == 'float')
    {
        if(charCode == 46 && value.search(/\./) >= 0)   
        {
            return false;
        }
    }
    
    return true;

}

function aml_card_luhn(num) 
{
    if(isNaN(num))
    {
        return false;
    }
    
	num = (num + '').replace(/\D+/g, '').split('').reverse();
	if (!num.length)
		return false;
	var total = 0, i;
	for (i = 0; i < num.length; i++) {
		num[i] = parseInt(num[i])
		total += i % 2 ? 2 * num[i] - (num[i] > 4 ? 9 : 0) : num[i];
	}
	return (total % 10) == 0;
}

function aml_card_cvv2(p_number)
{
    if(isNaN(p_number))
    {
        return false;
    }    
    
    if(p_number.length < 3)
    {
        return false;
    }
    
    return true;
}

function aml_card_expiry(p_value, p_group)
{
    var fields = p_group.split(',');
    var month = new Number(document.getElementById(fields[0]).value);
    var year  = new Number(document.getElementById(fields[1]).value);
    var today = new Date();
    
    //alert(month + ',' + year + ',' + today);
    
    if(month < today.getMonth() + 1 && year <= today.getFullYear())
    {
        return false;
    } 
    
    return true;
    
}


function aml_validate(p_name,p_check,p_group,p_message,p_message_id,p_toggle_validation)
{
    
    // If the Toggle Validation is set, then check if we are allowed to check.
    if(p_toggle_validation != '')
    {
        // If its false, then exit.
        if(document.getElementById(p_toggle_validation).value != 'true')
        {
            return true;
        }
    }
    

    var valid = true;
    var message = '';
    var number;
    var input_element = document.getElementById(p_name);
    var message_element;
    
    if(p_check == 'missing')
    {
        valid = (aml_trim(input_element.value) != '');
    }
    else if(p_check == 'email')
    {
        valid = aml_contact_email_validate(input_element);
    }
    else if(p_check == 'card_luhn')
    {
        valid = aml_card_luhn(input_element.value);
    }
    else if(p_check == 'card_cvv2')
    {
        valid = aml_card_cvv2(input_element.value);
    }
    else if(p_check == 'card_expiry')
    {
        valid = aml_card_expiry(input_element.value,p_group);
    }
    
    if(p_message_id == '')
    {
        message_element = document.getElementById(input_element.name + '_error');
    }
    else
    {
        message_element = document.getElementById(p_message_id);
    }
    
    if(p_group == '')
    {
        p_group = p_name;
    }
    
    
    var elements = p_group.split(',');

    // If there is something wrong, then show the warning.
    if(!valid)
    {
        
        
        for(index = 0; index < elements.length; index++)
        {
            if(aml_error.indexOf(elements[index]) == -1)
            {
                aml_error.push(elements[index],document.getElementById(elements[index]).style.backgroundColor);
            }   
            
            document.getElementById(elements[index]).style.backgroundColor = '#FFF6D5';
        }
        
        if(message_element != null)
        {
            message_element.innerHTML = p_message;
        }
        
        return false;
    }
    
    // This is a valid item.
    for(index = 0; index < elements.length; index++)
    {    
        var error_pos = aml_error.indexOf(elements[index]); 
        
        if(error_pos >= 0)
        {
            document.getElementById(elements[index]).style.backgroundColor = aml_error[error_pos + 1]; 
            aml_error.splice(error_pos,2);      
        }
    }
        
    if(message_element != null)
    {
        message_element.innerHTML = '';
    }
    
    return true;

}

function aml_post_form(p_this,p_post_response_message,p_post_to,p_url_on_success)
{
   
    //document.getElementById(aml_warning_message[0]).innerHTML = '';
    p_this.disabled = true;
 
/*
    if(!aml_validate_form())
    {
        document.getElementById(aml_warning_message[0]).innerHTML = aml_warning_message[1];
        p_this.disabled = false;           
        return;
    }
*/
    
    
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 )
        {
            // Get the response text.
            //var response = xmlhttp.responseText; 
            var response = aml_trim(xmlhttp.responseText);
            data = response.split(',');
            // Response, Contact, Invoice
            

			if(data[0] == 'free_product')
            {	
                location.href = "Thank you/?free_product&" +"&"+ data[1] +"&"+ data[2] +"&"+ data[3] +"&"+ data[4] +"&"+ data[5];
				return;
            }
				
				console.log(response);
            
            if(data[0] == '')
            {
                location.href = p_url_on_success;

                return;
            }
            else if(data[0] == 'paypal')
            {
            
            
                // Set the custom field with the contact and invoice id.
                document.getElementById('aml_paypal_custom').value += ',' + data[1] + ',' + data[2]+ "," + data[3];
                var free_guest = document.getElementById('mbs_guest_free').value; 
                //if the guest is for free do not charge them
                if(free_guest != 1){
    
    	            document.getElementById('aml_paypal_quantity').value = data[4];
	                
                }               
                
                
                //alert(document.getElementById('aml_paypal_custom').value);
                //alert(data[1] +', '+data[2] +', '+data[3]);
                
                
                // Do a form submit to paypal, so it redirects to PayPal.
                document.getElementById('aml_paypal_form').submit();
                //return false;
            }
            else 
            {
                document.getElementById(aml_warning_message[0]).innerHTML = response;
            }
            
            p_this.disabled = false;                 
        }
    }
    
    var params = 'aml_form_posted=true';

    params += '&aml_post_response_message=' + p_post_response_message;

    for(index = 0; index < aml_entry_elements.length; index++)
    {
        params += "&" + aml_entry_elements[index] + "=" + encodeURIComponent(document.getElementById(aml_entry_elements[index]).value);
    }
    
    //alert(params);

    xmlhttp.open("POST", p_post_to,true);    
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //xmlhttp.setRequestHeader("Content-length", params.length);
    //xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(params);    


}
    
