$(document).ready(function($) {

	 var totalAmountField = $('span#totalAmount'), amount = parseFloat($('input#amount').val()),

            cardNumber  = $('input#cardNumber').val(), surcharge = 2;



	if($('.pay_fixed_true').length == 0) {



	    if (!isNaN(amount)) {

	        if (addSurcharge) {



	            if (getCardType(cardNumber) == 'amex') {

	                surcharge = 2;

	            }



	            totalAmountField.html((amount * (1 + (surcharge / 100))).toFixed(2).replace(/(\d{1,3}(?=(\d{3})+(?:\.\d|\b)))/g,"\$1,"));



	            $('.fee').html(((amount * (1 + (surcharge / 100))).toFixed(2) - amount).toFixed(2));

	            //$('input#amount').val((amount * (1 + (surcharge / 100))).toFixed(2));

	        } else {

	            totalAmountField.html(amount.toFixed(2));

	            $('.fee').html((amount.toFixed(2) - amount).toFixed(2));

	            //$('input#amount').val(amount.toFixed(2));

	        }

	    }

	}











	var creditcards = [

    {

        name: 'amex',

        pattern: /^3[47]/,

        valid_length: [15]

    },

    {

        name: 'visa_debit',

        pattern: /^(4543|4462|4462|454313|454361|454434|456726|456735|456738|465845|465858|465859|465861|465901|465904|465921|465942|465943|465944|475116|475117|475118|475126)/,

        valid_length: [16]

    },

    {

        name: 'visa_electron',

        pattern: /^(4026|417500|4508|4844|491(3|7))/,

        valid_length: [16]

    },

    {

        name: 'visa',

        pattern: /^4/,

        valid_length: [16,13]

    },

    {

        name: 'mastercard',

        pattern: /^5[1-5]/,

        valid_length: [16]

    },

    {

        name: 'maestro',

        pattern: /^(5018|5020|5038|6304|6759|676[1-3])/,

        valid_length: [12, 13, 14, 15, 16, 17, 18, 19]

    }

];



function getCardType(cardNumber)

{



    for (var i in creditcards) {

        if (cardNumber.match(creditcards[i].pattern)) {

            if ($.inArray(cardNumber.length, creditcards[i].valid_length) !== -1) {

                if (luhnCheck(cardNumber)) {

                    return creditcards[i].name;

                }

            }

        }

    }

    return null;

}



function validateCreditcard(cardNumber)

{

    for (var i in creditcards) {

        if (cardNumber.match(creditcards[i].pattern)) {

            if ($.inArray(cardNumber.length, creditcards[i].valid_length) !== -1) {

                if (luhnCheck(cardNumber)) {

                    return true;

                }

            }

        }

    }

    return true;

}

function luhnCheck(luhn)

{

    var len = luhn.length, mul = 0, prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]], sum = 0;



    while (len--) {

        sum += prodArr[mul][parseInt(luhn.charAt(len), 10)];

        mul ^= 1;

    }



    return sum % 10 === 0 && sum > 0;

}



    $('input#cardNumber').bind('keyup change', function(){



        var cardType = getCardType($(this).val().replace(/\s*/g,''));



        $('ul.creditcards img').removeClass('highlight');

        $('img.creditcard_' + cardType).addClass('highlight');

        $('#card_type_hidden').val(cardType);

        if (cardType == 'amex' || cardType == 'mastercard' || cardType == 'visa') {

            $('input#cardIssueNumber').attr('disabled', true).addClass('disabled');

        } else {

            $('input#cardIssueNumber').attr('disabled', false).removeClass('disabled');

        }

    });





    $('#frmPayment').change(function() {

    	$('#frmPayment input[type="text"]').each(function() {

    		if($(this).val() == '') {

    			//$('[name="proceedToPay"]').css({"background-color": "#ccc"});

    			$('[name="proceedToPay"]').addClass('disable');

    		} else {

    			//$('[name="proceedToPay"]').css({"background-color": "#fff"});

    			//$('[name="proceedToPay"]:hover').css({"background-color": "#777"});

    			$('[name="proceedToPay"]').removeClass('disable');

    		}

    	});

    });

    $('#frmPayment').mouseover(function() {

    	$('#frmPayment input[type="text"]').each(function() {

    		if($(this).val() == '') {

    			//$('[name="proceedToPay"]').css({"background-color": "#ccc"});

    			$('[name="proceedToPay"]').addClass('disable');

    		} else {

    			//$('[name="proceedToPay"]').css({"background-color": "#fff"});

    			//$('[name="proceedToPay"]:hover').css({"background-color": "#777"});

    			$('[name="proceedToPay"]').removeClass('disable');

    		}

    	});

    });


    $('#invoices_list').change(function() {

		var checked = $('input[type="checkbox"]:checked');
		if (checked.length > 0) {
			$('.button-invoices').removeClass('disable');
		} else {
			$('.button-invoices').addClass('disable');
            $('input[name="invoice_currency"]').val('');
		}

    });


    $('.invoices-table input[type="checkbox"]').change(function() {
        var currency = $('input[name="invoice_currency"]').val();
        if( currency != '' ) {
            if($(this).prop("checked") === true && $(this).attr('data-currency') != currency  ){
                alert('Please select invoices with same currencies');
                $(this).prop( "checked", false );
            }
        } else {
            $('input[name="invoice_currency"]').val( $(this).attr('data-currency') );
        }

    });

    $('input#amount').keyup(function() {

    	if( $('input#amount').val() != '' ) {

    		$('.pay_fixed').removeClass('disable');

    	} else {

    		$('.pay_fixed').addClass('disable');

    	}

    });

    $('input#amount').mouseout(function() {

    	if( $('input#amount').val() != '' ) {
    		$('.pay_fixed').removeClass('disable');
    	} else {
    		$('.pay_fixed').addClass('disable');
    	}

    });



   $('#pay_fixed_form').mouseover(function() {



    	if( $('input#amount').val() != '' ) {

    		//$('.pay_fixed').css({"background-color": "#fff"})

    		//$('.pay_fixed:hover').css({"background-color": "#777"});

    		$('.pay_fixed').removeClass('disable');

    	} else {

    		//$('.pay_fixed').css({"background-color": "#ccc"});

    		$('.pay_fixed').addClass('disable');

    	}

    });



    $('input#account').keyup(function() {



    	if( $('input#account').val() != '' ) {

    		//$('.button-account').css({"background-color": "#fff"})

    		//$('.button-account:hover').css({"background-color": "#777"});

    		$('.button-account').removeClass('disable');

    	} else {

    		//$('.button-account').css({"background-color": "#ccc"});

    		$('.button-account').addClass('disable');

    	}

    });

    $('input#account').mouseout(function() {



    	if( $('input#account').val() != '' ) {

    		//$('.button-account').css({"background-color": "#fff"});

    		//$('.button-account:hover').css({"background-color": "#777"});

    		$('.button-account').removeClass('disable');

    	} else {

    		//$('.button-account').css({"background-color": "#ccc"});

    		$('.button-account').addClass('disable');

    	}

    });

    $('#account_form').mouseover(function() {



    	if( $('input#account').val() != '' ) {

    		//$('.button-account').css({"background-color": "#fff"})

    		//$('.button-account:hover').css({"background-color": "#777"});

    		$('.button-account').removeClass('disable');

    	} else {

    		//$('.button-account').css({"background-color": "#ccc"});

    		$('.button-account').addClass('disable');

    	}

    });

	$('a.info').click( function(event){

		event.preventDefault();

		$('#overlay').fadeIn(400,

		 	function(){

				$('#modal_form')

					.css('display', 'block')

					.animate({opacity: 1, top: '50%'}, 200);

		});

	});


	/* Зaкрытие мoдaльнoгo oкнa, тут делaем тo же сaмoе нo в oбрaтнoм пoрядке */

	$('#modal_close, #overlay').click( function(){ // лoвим клик пo крестику или пoдлoжке

		$('#modal_form')

			.animate({opacity: 0, top: '45%'}, 200,  // плaвнo меняем прoзрaчнoсть нa 0 и oднoвременнo двигaем oкнo вверх

				function(){ // пoсле aнимaции

					$(this).css('display', 'none'); // делaем ему display: none;

					$('#overlay').fadeOut(400); // скрывaем пoдлoжку

				}

			);

	});



	$('.pay_fixed').on('click', function() {

		$.ajax({
			url : 'check_fixed',

			type : 'POST',

			dataType : 'json',

			data: $('#pay_fixed_form input'),

			success: function(data) {

				if (data['error']) {

					$('.error').css({'display': 'block'});

					errors = data['error'];

					for (var prop in errors) {

					  $('.error').append(errors[prop] + '<br>');

					}

				} else {

					success = data['success'];

					$('#pay_fixed_form').submit();

				}
			}

		});

		return false;

	});


    $('#account_form').submit(function() {

        $.ajax({

            url : 'check_account',

            beforeSend: function(){

                $('.account_wait').css({'display': 'block'});

            },

            type : 'POST',

            dataType : 'json',

            data: $('#account'),

            success: function(data) {

                $('.account_wait').css({'display': 'none'});

                if (data.error) {

                    $('.error').css({'display': 'block'});

                    return false;
                } else {

                    $('#contact_id').val(data.success);
                    $('#account_form').unbind().submit();

                }
            }
        });
        return false;
    });


    $('.button-continue-currencies').click(function() {
        $('.choose-payment-method-wrapper').show();
        $('.another-currency').hide();
        return false;
    });

	$('.button-account').click(function() {

		$.ajax({

			url : 'check_account',

	        beforeSend: function(){

            	$('.account_wait').css({'display': 'block'});

        	},

			type : 'POST',

			dataType : 'json',

			data: $('#account'),

			success: function(data) {

				$('.account_wait').css({'display': 'none'});

				if (data['error']) {

					$('.error').css({'display': 'block'});

				} else {
					$('#contact_id').val(data['success'][0]);
					$('#account_form').submit();

				}
			}
		});

		return false;

	});



	$('.button-invoices').click(function() {

		var checked = $('input[type="checkbox"]:checked');

		if (checked.length > 0) {

			$('#invoices_list').submit();

		} else {
			alert('Please, choose invoice or invoices');
		}
		return false;

	});

	$('.paypal-button').on('click', function() {

		$('#pay_paypal').submit();

		return false;

	});

	$('.disable.button-account').click(function() {

		return false;

	});



     $('.payment-success a.send_receipt').on('click', function() {

        var email = $('.payment-success input').val();

		$.ajax({

			url : 'send_receipt.php',

			type : 'POST',

			dataType : 'json',

			data: $('.payment-success input'),

			success: function(data) {

				if (data['error']) {

					console.log(data['error']);

					$('.error').css({'display': 'block'});

					errors = data['error'];

					for (var prop in errors) {

					  $('.error').append(errors[prop] + '<br>');

					}

				} else {

					alert('Check your mailbox for receipt');


				}

			}

		});

		return false;

    });

});





