/*
	Author: Haim Knokh
*/
initializeOnlinePayment = function(isAlwaysShowOnlinePaymentSection, updateCardTokenCallback, createCardTokenCallback, deleteTokenCallback ){

	var isServerErrorExists = false;
	var lastSelectedCardId;

	var inputsSelector = 'input[required],select[required],.select';
	var inputContainerSelector  = '.field,.InputContainer,.checkbox-conditions,.Checkbox-conditions';
	var formAddCardSelector = '#formAddCard';
	var btnAddCardSelector = '#btAddCard';
	var formsToValidateSelector = formAddCardSelector + ':visible,.Checkbox-conditions,.checkbox-conditions';

	// Switches the view between new the card tab and the car list
	function showCardsList(show){
		
		// Hide all update credit card forms in the credit card list
		$('[data-form]').addClass('is-hidden2');
		
		// Hide all errors
		if (!isServerErrorExists)
			hideErrors();

		if (show){
			// Must show the list
			$('.card-list-rows').removeClass('is-hidden2');
			$('.CardList_title').removeClass('is-hidden2');
			$(formAddCardSelector).addClass('is-hidden2');
			$('[data-bt-cancel]').removeClass('is-hidden2');
		} else {
			// Must show new credit card form
			$('.card-list-rows').addClass('is-hidden2');
			$('.CardList_title').addClass('is-hidden2');
			$(formAddCardSelector).removeClass('is-hidden2');
			$('[data-bt-cancel]').addClass('is-hidden2');
		}

	};
	
	// Returns true if online payment option was selected
	function isOnlinePaymentOptionSelected(){
		return $('input[type=radio][name=payment][id=creditOnline]').is(':checked');
	}

	// Validates card expiration date against the current date
	function checkExpirationDate(year, month){
		month = String(month);
		if (month.length == 1)
			month = '0' + month;
		var exp = new Date(year + '-' + month + '-01');
		exp.setMonth(exp.getMonth() + 1);
		return exp.getTime() > new Date().getTime();
	}
	
	// Hides all error messages and red borders
	function hideErrors(){
		$('.error-message').addClass('is-hidden2');
		$(inputsSelector).removeClass('is-danger').parent()
				.removeClass('InputText-error')
				.removeClass('InputSelect-error');
	}

	// Clear all inputs including error color and all error messages
	function resetInputs(){
		$(inputsSelector).each(function(){
			$(this).val('');
			$(this).siblings('.currentChoice').text($(this).data('default'));
		});
	}

	// Validates card inputs, diplays errors and call callback func
	function validateCreditCardInputs($formElement, errorMessageSelector, successCallback, e, errorCallback){
			
			
			// Change clicked button caption to 'Wait'
			var $target = $(!!e ? e.target : '<a/>');
			var targetCaption = $target.text();
			$target.css('pointer-events', 'none').text('Please, wait...');
			var $btDiscardNewCard = $('#btDiscardNewCard').css('pointer-events', 'none');

			// Hide all error messages and red borders
			hideErrors();

			var expMonthValue = '';

			// The filter to get all invalid input
			var $invalidElements = $formElement.find(inputsSelector).map(function(){
			
				if (!$(this).is('input,select')) return null;

			
				var $field = $(this).closest(inputContainerSelector);
				var $element = $field.find(inputsSelector);
			
				var minLength = +($(this).data('min-length') || '0');

				if ($(this).attr('name') == 'newCardDateMonth'){
					expMonthValue = this.value;
				}

				// Hide error message
				$field.find('.mesage-required,.mesage-invalid').addClass('is-hidden2');

				// Set value to be used in server side
				$('[data-input=' + $(this).attr('name') + ']').val(this.value);

				// Validate required
				var isValid = $(this).is('[type=checkbox]') ? $(this).is(':checked') : !!this.value;

				if (!isValid){
					var output = {
						label:    $field.find('.mesage-required').removeClass('is-hidden2'),
						element:  $element
					};
					output.element.addClass('is-danger').parent().addClass('InputText-error'); 
					return output;

				} else {

					// Validate invalid
					if (this.value.length < minLength){
						var output = {
							label:    $field.find('.mesage-invalid').removeClass('is-hidden2'),
							element:  $element
						};
						output.element.addClass('is-danger').parent().addClass('InputText-error');
						return output;
					} else {
						// validate date
						if ($(this).attr('name') == 'newCardDateYear'){
							if (!checkExpirationDate(this.value, expMonthValue)){
								var output = {
									label:    $field.find('.mesage-invalid').removeClass('is-hidden2'),
									element:  $element
								};
								output.element.addClass('is-danger').parent().addClass('InputSelect-error'); 
								return output;
							}
						} else 
							return null;
					}
				}
			});

		
			// Check if any invalid input does exist and submit order if the validation has been passed
			if ($invalidElements.length > 0) {

				// Get first invalid element
				$invalidElements = $invalidElements.get(0);

				// Display error from the first invalid input near button
				$(errorMessageSelector).removeClass('is-hidden2').text($invalidElements.label.text());

				// Focus to the first invalid input
				$invalidElements.element.focus();

				// Restore button text
				$target.css('pointer-events', '').text(targetCaption);
				$btDiscardNewCard.css('pointer-events', '');

				if (errorCallback)
					errorCallback();

			} else {
				// Submit
				successCallback();
			}
	}

	// Check the radio button of the online payment option
	function checkOnlinePaymentRadio(){
		$('input[type=radio][name=payment][id=creditOnline]')
			.prop('checked', true)
			.change();	
	}


	// -- Global functions ----
	// This callback must be called after the token has updated on the Server
	window.onUpdateTokenComplete = function onUpdateTokenComplete(){ 
		initializeOnlinePayment();
		checkOnlinePaymentRadio();
		isServerErrorExists = false;
	};

	// Runs validation of the new token form input controls
	window.validateNewTokenInputs = function validateNewTokenInputs(e, callback){
		validateCreditCardInputs($(formsToValidateSelector), '.confirm-error',
			function () {
				if (!callback)
					createCardTokenCallback(isOnlinePaymentOptionSelected());
				else
					callback(true);
			},
			e, function(){
			if (callback)
				callback(false);
		});
	}

	// Displays server error messages
	window.showHiPayServerError = function showHiPayServerError(){
		
		// Show server error message if exists
		var $confirmErrorLabel = $('.confirm-error');
		isServerErrorExists = !!$confirmErrorLabel.text().trim();

		var $CheckoutError = $('.CheckoutError');
	

		if (!isServerErrorExists){
			// No server error - hide server error messages
			$confirmErrorLabel.addClass('is-hidden2');
			$CheckoutError.length && $CheckoutError.addClass('is-hidden2');
		} else{
			// Server error - show server error messages
			$confirmErrorLabel.removeClass('is-hidden2');
			if ($CheckoutError.length) {
				$CheckoutError.removeClass('is-hidden2');
				$('html,body').animate({scrollTop: $CheckoutError.offset().top - 120}, 'slow');
			}
		}		
			
	}



	return function(){

		// Init dropdowns
		$(window).trigger('SELECT_INIT'); 
		
		// Init selects
		if ($.Select) $.Select();

		// Init tooltips
		if ($.fn.tooltipster) $('.tooltipstered').tooltipster();
		
		// Init colorbox
		if ($.colorbox) {
			$("[data-popin-delete]").colorbox({
				transition: "none",
				initialWidth: 800,
				initialHeight: 200,
				inline: true,
				href: $("[data-popin-delete]").data("popin-delete"),
				overlayClose: true,
				closeButton: false
			});
		}
		
		

		// Init popin controllers
		if (window.rebindpopinListeners)
			window.rebindpopinListeners();


		// Makes entire credit card section visible
		function showOnlinePaymentSection(){

				// Select the first card from the card list by default
				if (!lastSelectedCardId)
					$('input[name=card]').first().prop('checked', true).click();
				else
					$('input[name=card][data-id="' +  lastSelectedCardId  +  '"]').prop('checked', true).click();

			
				// Enable showing for entire hipay section
				$('.online-card-payment').removeClass('is-hidden');

				// Checking if any card exists for the user
				var isCardsExist = $('.CardList > table > tbody > tr').length > 0;

				// Cancel update credit card clicked
				$('[data-bt-cancel]').off('click').on('click', function(){
					$('[data-form],' + formAddCardSelector).addClass('is-hidden2');			
					$(btnAddCardSelector).removeClass('is-hidden2');
					resetInputs();
					hideErrors();
				});

				// Save update credit card clicked
				$('[data-bt-save]').off('click').on('click', function(e){
					validateCreditCardInputs($(this).closest('[data-form]'), '.dummy', updateCardTokenCallback, e);
				});


				// Showing the the card list or the new card form
				showCardsList(isCardsExist);
		}
		
		
		// Toggle card section in accordance with selected option
		$('input[type=radio][name=payment]').off('change.online_payment').on('change.online_payment', function(){

			// Online payment option was selected
			if ($(this).attr('id') == 'creditOnline'){

				showOnlinePaymentSection();

			} else {

				// Hide antire hipay section
				$('.online-card-payment').addClass('is-hidden');
			}		

		});

		

		// Toggle add new card form
		$(btnAddCardSelector).off('click').on('click', function(){
			$(formAddCardSelector).removeClass('is-hidden2');
			$(this).addClass('is-hidden2');
			$('[name=card]').prop('checked', false);
			lastSelectedCardId = undefined;
			$('[data-form]').addClass('is-hidden2');
			$('[id$=selectedCardId]').val('');
			hideErrors();
		});


		// Toggle update card forms && prepare card for deleting
		$('[data-bt-update],[data-bt-delete]').off('click.online_payment').on('click.online_payment', function(){

			var index = $(this).data('bt-id');
			var $form = $('[data-form=' + index + ']');

			// Make the credit card current
			$form.closest('[data-card-id]').find('input[type=radio]').click();

			// Update func
			if ($(this).is('[data-bt-update]'))
				$form.removeClass('is-hidden2');

			resetInputs();
			hideErrors();
			
		});


		// The deleted button of the confirm popin
		$(window).off('POPIN_OPEN_DONE.online_payment').on('POPIN_OPEN_DONE.online_payment', function(){
			$('[data-bt-delete-apply]:visible').off('click.online_payment').on('click.online_payment',  function(){
				if (deleteTokenCallback) deleteTokenCallback();
			});
		});


		// Validate keypress events on numeric inputs
		$('[data-numeric]').off('keypress').on('keypress', function(event){
			var l = +($(this).data('length') || '100');
			return event.charCode >= 48 && event.charCode <= 57 && this.value.length < l;	
		});
	

		// Prepare sending selected card to the server
		$('input[id^=card][type=radio]').off('click').on('click', function(){
		
			lastSelectedCardId = $(this).data('id');

			// Update hidden field
			$('[id$=selectedCardId]').val(lastSelectedCardId);
		
			// Hide new card form
			showCardsList(true);
		});
	

		if (isAlwaysShowOnlinePaymentSection)  
			showOnlinePaymentSection();


		// Show server error message if exists
		window.showHiPayServerError();


		// New card input validation on submit button click
		$('.confirm_order_button,.save_credit_card_button').off('click.online_payment').on('click.online_payment', validateNewTokenInputs);
	};

};




