$(function(){
	$baseUrl = $('#base').attr('data-orig');
    $width = $(window).width();
	$height = $(window).height();

	$(document).click(function() {
		/* clear modal contents */
		$('body').on('hidden.bs.modal', '.modal', function (e) {
			$(e.target).removeData("bs.modal").find(".modal-content").empty();
		});
		/* clear modal contents */
	});


	$(document).keyup(function(e) {
 		if (e.keyCode == 27) {
 			/* clear modal contents */
 			$('body').on('hidden.bs.modal', '.modal', function (e) {
 				$(e.target).removeData("bs.modal").find(".modal-content").empty();
			});
			/* clear modal contents */
			preloaderRemove();
 		}
 	});

	$(document).ready(function () {	
        
        if ($('.wow').hasClass('animated')) {
            $(this).removeClass('animated');
            $(this).removeAttr('style');
            //new WOW().init();
        }

        $('.refresh').on('click',function(){
            location.reload();
        });

		//new WOW().init();

		$(window).stellar();

		/* clear modal contents */
		$('body').on('hidden.bs.modal', '.modal', function (e) {
			$(e.target).removeData("bs.modal").find(".modal-content").empty();
		});
		/* clear modal contents */

		$('.numbersOnly').keyup(function(){
			this.value = this.value.replace(/[^0-9\.]/g,'');
		});

        $('button, li, div, i, img').on('click',function(){
            if($(this).attr('data-target') == '_parent'){
                window.open($(this).attr('data-url'),'_parent');
            }else if($(this).attr('data-target') == '_blank'){
                window.open($(this).attr('data-url'),'_blank');
            }else{
                if($(this).attr('data-url')){
                    window.location.href = $(this).attr('data-url');
                }
            }
        });

        $('.modal-body .medical .button-group button').on('click',function(){
            var Key = $(this).attr('data-key');
            var Txt = Key;
            if(Key == 'Travel History'){
                $('#medical .country').show();
            }
            if(Key == 'Operation'){
                $('#medical .operation').show();
                Txt = 'Diagnosis';
            }
            if(Key == 'Medication'){
                $('#medical .medication').show();
            }
            if(Key == 'Diabetes'){
                $('#medical .diabetes').show();
                Txt = 'Diagnosis';
            }
            if(Key == 'Epilepsy'){
                $('#medical .epilepsy').show();
                $('#medical .medication').show();
                Txt = 'Last Episode';
            }
            if(Key == 'Asthma'){
                $('#medical .asthma').show();
                $('#medical .medication').show();
                Txt = 'Diagnosis';
            }
            if(Key == 'Chronic Illness'){
                Txt = 'Diagnosis';
            }
            if(Key == 'High Blood Pressure'){
                Txt = 'Diagnosis';
            }
            $('#medical #Key').val(Key);
            $('#medical #Key_Txt').html(Txt);
            $('#medical, .outro').show().css({'opacity':0}).animate({'opacity':1});
            $('.modal-body .medical .button-group, .intro').css({'opacity':1}).animate({'opacity':0}).hide();
        });

        
		/* top menu bar */
                /*
		var top = $('body').offset().top - parseFloat($('body').css('marginTop').replace(/auto/, 0));
		if(top >= 100 && $(window).width() > 250 && $('section').height() > 1000){
			$('body').addClass('slided');
		}
		*/
		$(window).scroll(function (event) {		
                  /*
			var y = $(this).scrollTop();
			if (y >= 100 && $(window).width() > 250 && $('section').height() > 1000) {
				$('body').addClass('slided');
			} else {
				$('body').removeClass('slided');
			}
			*/
                    if( $('section').height() > 1000 )
                    {
                      $('body').addClass('slided');
                    }
                    
                    if($(this).scrollTop() ==0)
                    {
                      $('body').removeClass('slided');
                    }
		});

                
		/* top menu bar */

        $('#join button').on('click',function(e){
            e.preventDefault();
            e.stopImmediatePropagation();
            var formname = $(this).closest("form").attr('id');
            if(validation(formname)){
                preloader('', 'body');
                if($('#g-recaptcha-response').length > 0){
                    /* Check Captcha */
                    $.ajax({
                        type: "POST",
                        url : $baseUrl + "/captcha",
                        data : "g-recaptcha-response=" + $('#g-recaptcha-response').val() + "&_token=" + $('input[name="_token"]').val(),
                        success : function(data){
                            if(data == '1'){
                                $('#' + formname).attr('action', "register").submit();
                                return false;
                            }else{
                                preloaderRemove();
                                $('.captcha-warning').remove();
                                $('#' + formname).before('<div class="captcha-warning"><i class="fas fa-bell"></i> Please check the reCAPTCHA box</div>');
                                return false;
                            }
                        },
                        error : function(data){
                        }
                    },"json");
                    /* Check Captcha */
                }else{
                    $('#' + formname).attr('action', "register").submit();
                }
            }
            return false;
        });

        $('#contact button').on('click',function(e){
            e.preventDefault();
            e.stopImmediatePropagation();
            var formname = $(this).closest("form").attr('id');
            if(validation(formname)){
                preloader('', 'body');
                if($('#g-recaptcha-response').length > 0){
                    /* Check Captcha */
                    $.ajax({
                        type: "POST",
                        url : $baseUrl + "/captcha",
                        data : "g-recaptcha-response=" + $('#g-recaptcha-response').val() + "&_token=" + $('input[name="_token"]').val(),
                        success : function(data){
                            if(data == '1'){
                                $('#' + formname).submit();
                                return false;
                            }else{
                                preloaderRemove();
                                $('.captcha-warning').remove();
                                $('#' + formname).before('<div class="captcha-warning"><i class="fas fa-bell"></i> Please check the reCAPTCHA box</div>');
                                return false;
                            }
                        },
                        error : function(data){
                        }
                    },"json");
                    /* Check Captcha */
                }else{
                    $('#' + formname).attr('action', "contact").submit();
                }
            }
            return false;
        });

        $('#signin button').on('click',function(e){
            var formname = $(this).closest("form").attr('id');
            if(validation(formname)){
                preloader('', 'body');
                $('#' + formname).attr('action', "signin").submit();
            }
            return false;
        });

        $('#profile button').on('click',function(e){
            var formname = $(this).closest("form").attr('id');
            if(validation(formname)){
                preloader('', 'body');
                $('#' + formname).attr('action', $('#base').attr('data-orig') + "/member/profile/edit").submit();
            }
            return false;
        });

        $('#forgotten button').on('click',function(e){
            var formname = $(this).closest("form").attr('id');
            if(validation(formname)){
                preloader('', 'body');
                $('#' + formname).attr('action', "forgotten-password").submit();
            }
            return false;
        });

        $('form.validate button').on('click',function(e){
            var formname = $(this).closest("form").attr('id');
            if(validation(formname)){
                preloader('', 'body');
                $('#' + formname).submit();
            }
            return false;
        });

        $('#google-sign-in').on('click', function(e) {
            var provider = new firebase.auth.GoogleAuthProvider();
            firebase.auth().signInWithRedirect(provider).then(function(result) {
            preloader('', 'body');  
              var token = result.credential.accessToken;
              console.log('Token: ' + token);
              var FireBaseUser = result.user;
              window.user = FireBaseUser;
              console.log('User: ' + FireBaseUser);
            }).catch(function(error) {
              var errorCode = error.code;
              var errorMessage = error.message;
              var email = error.email;
              var credential = error.credential;
              console.log('Error: ' + errorCode + ' ' + errorMessage + ' ' + email + ' ' + credential);
            });
        });
        
        $('#google-sign-out').on('click', function(e) {
            firebase.auth().signOut().then(function() {
            // Sign-out successful.
            }).catch(function(error) {
            // An error happened.
            });
        });

        /* search */
        $('.search_input').typeahead({
            minLength: 3,
            dynamic: true,
            hint: true,
            highlight: true,
            delay: 50,
            template: function (query, item) {
                return '<div class="' + item.Type + '">' + 
                        '<h4>' + item.Symptom + '</h4>' + 
                        '<p class="diagnosis"><strong>Diagnosis:</strong> ' + item.Diagnosis + '</p>' + 
                        '<p class="specialisation"><strong>Specialists:</strong> ' + item.Specialisation + '</p>' + 
                        '<p class="link"><a href="' + item.Link + '">' + item.Button + '</a></p>' + 
                    '</div>';
            },
            emptyTemplate: "Sorry, there's no results for <strong>{{query}}</strong>...",
            source: {
                symptoms: {
                    display: "Symptom",
                    href: '{{Link}}',
                    data: function () {
                        var deferred = $.Deferred(),
                            query = this.query;
                        $.getJSON(
                            $('#base').attr('data-orig') + '/symptoms/keyword',
                            {
                                q: query,
                                t: 'symptoms'
                            },
                            function (data) {
                                console.log(data);
                                deferred.resolve(data);
                            }
                        )
                        return deferred;
                    }
                }
            },
            callback: {
                onClick: function (node, a, item, event) {
                    window.location.href = $('#base').attr('data-orig') + '/library/' + item.id + '/' + item.slug;
                    return false;
                },
                onSendRequest: function (node, query) {
                    $('.typeahead__query .icofont').hide();                    
                },
                onReceiveRequest: function (node, query) {
                    $('.typeahead__query .icofont').hide();
                },
                onShowLayout: function (node, query) {
                    //var ResultsHeight = Math.round($height-($('.search .close').position().top))-120;
                    //$('.typeahead__list').css('max-height',ResultsHeight+'px');
                },
                onCancel: function (node, query) {
                    $('.typeahead__query .icofont').show();
                }

            },
            debug: true
        });

        $('.search .typeahead__query i').on('click',function(){
            window.location.replace($baseUrl + "/symptoms/search/" + $(".search_input").val());
        });     
        /* search */

        // Redeem Airtime
        $('.redeem_airtime').on('click', function (e) {
            $('.alert').remove();
            preloader("Please wait while we process your airtime.", 'body');
            e.preventDefault();
            $.ajax({
                method: 'GET',
                url: $baseUrl + "/redeem_airtime",
                success: function (data) {
                    $('.alert').remove();
                    console.log("Success:", data);
                    $('footer').prepend('<div class="alert alert-' + data.status + '">Airtime Redemption: ' + data.message + '</div>');
                    if(data.status == "success"){
                      $('.redeem_airtime').remove();
                    }
                    else
                    {
                      $('.redeem_airtime').removeClass('disabled');
                    }
                    preloaderRemove();
                },
                error: function (xhr) {
                    $('.alert').remove();
                    $('.redeem_airtime').removeClass('disabled');
                    preloaderRemove();
                    console.log("Error:", xhr.responseText);
                    $('footer').prepend('<div class="alert alert-danger">Airtime Redemption: ' + xhr.responseText + '</div>');
                }
            });
        });
        // Redeem Airtime

	});
});

