$(document).ready(function(){

    calculate();
    
});

var timeoutId;

function process() {

    if (validate())
    {
		$("#saving").show();
		$("#processingForm input[type=button]")[0].disabled = true;
		     
		$.post(
			"../../../../ajaxProcessPayment",
			//"/projects/cityplat/companies/ajaxProcessPayment", /* для совместимости с партнёркой*/ 
			/*"/companies/ajaxProcessPayment",*/ /*для сервака*/
			$('#processingForm').serialize(),
			function(data){
				$("#saving").hide();
				$("#processingForm input[type=button]")[0].disabled = false;
				
				clearTimeout(timeoutId);
				clearValidationErrors();
				       
				if (defaultHandler(data)) {
				    $("#formContainer").html(data.form);
				    //!!!alert("sdfsfdsfsfd");
				    //alert("sdfsfs");
				   //window.location.href = "http://cityplat/companies/successWebMoneyPayment";/*---Igor: for testing---*/
				   //window.location.href = "http://cityplat/companies/failPayment";/*---Igor: for testing---*/
				    $("#formContainer form")[0].submit();
				} else {
					// подсвечиваю поля с ошибками
					for (var i=0; i<data.errorFields.length; i++)
					{
						if ($("#" + data.errorFields[i] )[0].type == "text")
			            {
			                $("#" + data.errorFields[i] )[0].className = "text-field-red";
			            }
			            $("#label" + data.errorFields[i] )[0].style.color = "red";
					}
					
					for (var i=0; i<data.error.length; i++)
					{
						alert (data.error[i]);
					}
				}    
			},
			"json"
		);
		
		timeoutFunc = function() {
			$("#saving").hide();
			$("#processingForm input[type=button]")[0].disabled = false;
			alert('Повторите запрос ещё раз.');
		};
		
		timeoutId=setTimeout(timeoutFunc, 60000);
    }
}

function calculate() {
	arrCheckoutCurrency = $("#processingForm input[name=currency]")
	
	for (var i=0; i<arrCheckoutCurrency.length; i++) {
		if (arrCheckoutCurrency[i].checked) {
			checkoutCurrency = arrCheckoutCurrency[i].value;
			break;
		}
	}
	
	sum = $("#processingForm input[name=sum]")[0].value;	
	paymentMethod = $("#paymentMethod")[0].value;
	
	paymentSum = /*Math.round*/((sum * arrCurrencies[checkoutCurrency]) / arrCurrencies[arrPaymentSystems[paymentMethod].currency_id]);
	paymentSum = paymentSum + paymentSum*arrPaymentSystems[paymentMethod].percent;
	paymentSum = paymentSum.toFixed(2);
	
	$("#paymentSum")[0].value = paymentSum;
}

function validate() {
    var bError = false;
    
    for(var i in arrRequiredId) {
        if (!validateField(i))
        {
            bError = true;
        }
    }

    if (!validateField('sum', '1', '[0-9]{0,6}.?[0-9]{1,2}')) {
    	bError = true;
    }
   
    if (!validateField('paymentMethod', '1', '[0-9]{1}')) {
    	bError = true;
    }
    
    
    if (!validateField('paymentSum', '1', '[0-9]+.?[0-9]*')) {
    	bError = true;
    }
        
    if (bError) {
    	alert ('Форма заполнена c ошибками! Обратите внимание на поля отмеченные красным цветом.');
        return false;
    } else {
    	if (!validateMinMaxSum())
    		return false;
    }
        
    return true;
}

// проверяет поле
function validateField(id, necessaryField, regularExpression) {
	var id = id;
	var value = $("#" + id)[0].value;

	var necessaryField = necessaryField?necessaryField:arrRequiredId[id].necessaryField;
	var regularExpression = regularExpression?regularExpression:arrRequiredId[id].regularExpression;
	
	if (necessaryField == '1' && value == '') {
		makeRed(id);
		return false;
	}

	if (regularExpression != '' && value != '') {
		var re = new RegExp("^" + regularExpression + "$");
		if ( value.match(re) == null) {
			makeRed(id);
			return false;
		}
	}
	//alert ('asd');
	makeWhite(id);	
	return true;
}

function validateMinMaxSum() {
	
	checkoutCurrency = $("#processingForm input[name=currency][type=radio][checked]")[0].value;
	paymentMethod = $("#paymentMethod")[0].value;
	sum = $("#processingForm input[name=sum]")[0].value;	
	
	complex = arrCurrencies[arrPaymentSystems[paymentMethod].currency_id]; // множитель для получения суммы в руб
	
	paymentSum = sum; // сумма в выбранной валюте
	
	//min = 5;/*---Igor: for testing---*/
	min = Math.round(arrPaymentSystems[paymentMethod].min_payment*complex / arrCurrencies[checkoutCurrency]); // мин в выбранной валюте
	max = Math.round(arrPaymentSystems[paymentMethod].max_payment*complex/ arrCurrencies[checkoutCurrency]); // макс в выбранной валюте

	if (paymentSum < min) {
		alert ('Минимальная сумма платежа ' + min + ' ');
		return false;
	}
	
	if (paymentSum > max) {
		alert ('Максимальная сумма платежа ' + max + ' ');
		return false;
	}
	
	return true;
	
}

// делает поле красным
function makeRed(id) {
	if ($("#" + id )[0].type == "text")
    {
        $("#" + id )[0].className = "text-field-red";
    }
    $("#label" + id )[0].style.color = "red";
}

// делает поле белым
function makeWhite(id) {
	if ($("#" + id )[0].type == "text")
    {
        $("#" + id )[0].className = "text-field";
    }
    $("#label" + id )[0].style.color = "";
}

// делает все поля белыми 
function clearValidationErrors(){
	$('label').each(function(){
		this.style.color = "";
	});
	$('input[type=text]').each(function(){
		this.className = "text-field";
	});
}