var Login;
(function ($) { 
    "use strict";
    $(document).ready(function () {
        var closeModal = function(){
            $('.modal, body').removeClass('active');
        }
        var openModal = function(modalID){
            $('.modalMsg').text('');
            $('body').find('#'+modalID).addClass('active');
        }
        var enterClick = function(btnID,inputID){
            $('#'+inputID).keypress(function (e) {
                var key = e.which;
                if(key == 13)  // the enter key code
                {
                    $('#'+btnID).click();
                    return false;  
                }
            });
        }
        Login = {
            initialized: false,

            init: function () {
                var $tis = this;

                if ($tis.initialized) {
                    return;
                }

                $tis.initialized = true;
                $tis.events();
            },
            events: function () {

                var $tis = this;
                
                /**
                 * Activate login modal
                 */
                $tis.loginAcc();  
                $tis.loginEmail(); 
                $tis.loginPass();  
                $tis.logout(); 
                $tis.passwordReset(); 
                $tis.setNewPassword(); 
                $tis.registerNewUser();
                $tis.verifyUserModal();
                $tis.passwordResetModal();
                $tis.passwordChange();
                $tis.updateMyProfile();
                $tis.sideBar();
            },
            
            //activate login modal
            loginAcc: function(){
                $('body').on('click','.loggInBtn', function(e){
                    e.preventDefault();
                    //set starting position we need for redirect
                    var startingPage = $(this).attr('href');
                    $('#login-email').attr('data-page', startingPage);
                    $('body').find('#subscribe-email').val('');
                    closeModal();
                    openModal('login-email');
                })
            },
            //login -> enter email
            loginEmail: function(){
                $('body').on('click','#btnLoginEmail', function(){ 
                    var email = $( "#subscribe-email" ).val();

                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/login.php',
                        dataType: 'json',
                        data: {
                            'action':'checkLoginEmail', 
                            'customer_email':email
                        },
                        success: function (response) {
                            if(response.status == 'error'){
                                $('.modalMsg').text(response['msg']).fadeIn();
                            }
                            if(response.hasOwnProperty('modal')){
                                closeModal();
                                $('.modalMsg').text('');
                                openModal(response.modal); 
                            }                    
                        },
                        error: function (response) {
                            console.log(response);
                        }
                    });
                })
                enterClick('btnLoginEmail','subscribe-email');
            },
            //login-> enter pass
            loginPass: function(){                 
                $('body').on('click','#btnLoginPass', function(){ 
                    var pass = $( "#customer-pass" ).val();
                    var email = $( "#subscribe-email").val();
                    var startingPage = $( "body").attr("data-route");
                    var myacc = $( "body").attr("data-myacc");
                    var lang = $("body").attr("data-lang")
                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/login.php',
                        dataType: 'json',
                        data: {
                            'action':'login', 
                            'user_email':email,
                            'user_pass':pass
                        },
                        success: function (response) {
                            if (response['status'] == 'ok'){
                                closeModal();
                                $('.my-account').load(document.URL +  ' .my-account');
                                var loc;
                                if($.isEmptyObject(response.customer.first_name) || $.isEmptyObject(response.customer.last_name)){
                                    loc = myacc;
                                } else {
                                    loc = startingPage;
                                }
                                window.location.href = '/'+lang+'/'+loc+'/';
                            } else {
                                $('.modalMsg').text(response['msg']).fadeIn();                   
                            }                               
                        },
                        error: function (response) {
                            console.log(response['msg']);
                        }
                    });
                })
                enterClick('btnLoginPass','customer-pass');
            },
            //login->entered mail, register new user, enter password
            registerNewUser: function(){
                $(".modalMsg").hide();
                $('body').on('click', '#btnNewUser', function(){    
                    var email = $("#subscribe-email").val();
                    var password = $("#subscribe-pass").val();
                    var password_confirm = $("#subscribe-pass-confirm").val(); 
                    $('.modalMsg').text('Processing...');
                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/login.php',
                        dataType: 'json',
                        data: {
                            'action':'register',
                            'subscribe_email':email,
                            'subscribe_password':password,
                            'subscribe_password_confirm':password_confirm
                        },
                        success: function (response) {
                            $('.modalMsg').text(response['msg']).fadeIn(); 
                            if(response.status == 'ok'){
                                setTimeout(function(){
                                    closeModal();
                                    $('.modalMsg').text('').fadeOut();
                                    openModal('login-email');
                                },2000)
                            }                            
                        },
                        error: function (response) {
                            alert(response);
                        }
                    });
                    return false;
                })
            },
            //send verification code using email     
            passwordReset: function(){ 
                $('body').on('click','#forgotPass',function(){
                    $(".modalMsg").text('Processing...').fadeIn('slow');                
                    var password_reset_email = $("#subscribe-email").val();     
                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/login.php',
                        dataType: 'json',
                        data: {
                            'action':'passwordReset',
                            'customer_email':password_reset_email
                        },
                        success: function (response) {
                            $(".modalMsg").text(response.msg).fadeIn('slow');                                               
                        },
                        error: function (response) {
                            alert(response);
                        }
                    });
                })
                return false;
            },
            //forgot password - change password
            setNewPassword: function(){ 
                $('body').on('click','#btnForgotPassChange', function(){       
                    var new_password = $("#passwordReset").val();
                    var new_password_again = $("#passwordResetAgain").val();   

                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/login.php',
                        data: {
                            'action':'setNewPassword',
                            'user_password':new_password,
                            'user_password_repeat': new_password_again
                        },
                        success: function (response) {
                            if (response.indexOf("changed!") >= 0)
                            {                                  
                                response = response.replace('changed!', '');
                                $(".modalMsg").text(response).fadeIn('fast').delay(5000).fadeOut('fast');
                                setTimeout(function(){
                                    closeModal()
                                    openModal('login-email');
                                },2000) // 2 seconds.
                                
                            }
                            else    
                            {
                                $(".modalMsg").text(response).fadeIn('slow');
                            }                                                
                        },
                        error: function (response) {
                            alert(response);
                        }
                    });
                    return false;
                })
            }, 
            //when logged in, change password
            passwordChange: function(){
                //open modal for new pass
                $('body').on('click','.myAccChangePass', function(){
                    openModal('currentPass');
                })
                //check old pass
                $('body').on('click','#btnPassReset', function(){
                    var current_password = $("#current_password").val();
                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/login.php',
                        dataType: 'json',
                        data: {
                            'action':'passwordCheckCurrent',
                            'current_password': current_password
                        },
                        success: function (response) {
                            if (response['status'] == "ok")
                            {                                                                     
                                closeModal();
                                openModal('changeYourPassword');                                  
                            }
                            else    
                            {  
                                $(".modalMsg").html(response['msg']).fadeIn();
                                setTimeout(function(){
                                    $(".modalMsg").fadeOut();
                                },3000) // 1 second.
                                return false;   
                            }                                                
                        },
                        error: function (response) {
                            alert(response);
                        }
                    });
                })
                enterClick('btnPassReset','current_password');
                //replace pass
                $('body').on('click','#btnNewPass', function(){
                    var new_password = $("#new_password").val();
                    var new_password_repeat = $("#new_password_repeat").val(); 
                    var current_password = $("#current_password").val();
                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/login.php',
                        dataType: 'json',
                        data: {
                            'action':'passwordChange',
                            'new_password': new_password,
                            'new_password_repeat': new_password_repeat,
                            'current_password': current_password
                        },
                        success: function (response) {  
                            $(".modalMsg").html(response['msg']).fadeIn();
                            setTimeout(function(){
                                $(".modalMsg").fadeOut();
                            },3000) // 1 second.
                            if(response['msg'] == 'Your password has been changed!')
                            {
                                setTimeout(function(){
                                    closeModal();
                                },3000) // 1 second.
                            }
                            return false;                                                                                 
                        },
                        error: function (response) {
                            alert(response);
                        }
                    });
                    return false;
                }); 
                enterClick('btnNewPass','new_password_repeat');             
            }, 
            verifyUserModal: function(){
                var target = document.location.hash.replace("#", "");
                if(target == "verify"){
                    openModal('verification');
                    setTimeout(function(){
                        closeModal();
                        openModal('login-email');
                    },3500)
                }
            },                               
            passwordResetModal: function(){
                var target = document.location.hash.replace("#", "");
                if(target === "prm"){
                    openModal('password-verification');
                }
            },
            logout: function(){
                //when div refresh, we can click logout
                $('body').on('click', '#logout', function (){
                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/login.php',
                        data: {
                            'action':'logout'
                        },
                        success: function (response) {
                            if (response == 'logged out!')
                            {
                                $('.my-account').load(document.URL +  ' .my-account');
                                window.location.href = '/'+$('body').attr('data-lang')+'/'; 
                            }                            
                        },
                        error: function (response) {
                            alert('error');
                        }
                    }); 
                })               
            },
            sideBar: function(){
                $('body').on('click', 'ul.sidebar-list li', function(){
                    var page = $(this).attr('data-page');
                    if(page !== undefined)
                    {
                        $('.my-acount-main-section').removeClass('active');
                        $('#'+page).addClass('active');
                        $('ul.sidebar-list li').removeClass('active');
                        $(this).addClass('active');
                    }
                })
                $('body').on('click','#btnTst', function(){
                    sessionStorage.setItem("reloading", "true");
                    document.location.reload();  
                })
            },
            updateMyProfile: function(){
                $('body').on('focus', 'input, select, textarea', function(){
                    $(this).removeClass('error');
                    var errorMsg = $(this).closest('.form-item').find('.errorMsg');
                    if(errorMsg.length){
                        $(this).closest('.form-item').find('.errorMsg').remove();
                    }
                })
                $('body').on('click','#btnMyProfile', function(){

                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: '/ajax.php',
                        dataType: 'json',
                        data: {
                            action: 'myProfile',
                            first_name: $('#first_name').val(),
                            last_name: $('#last_name').val(),
                            email: $('#customer_email').val(),
                            phone: $('#phone').val(),
                            company: $('#company').val(),
                            company_vat: $('#company_vat').val(),
                            country: $('#country').val(),
                            city: $('#city').val(),
                            address: $('#address').val(),
                            zip: $('#zip').val(),
                            terms_services: $('#terms_services').is(":checked"),
                            receive_newsletters: $('#receive_newsletters').is(":checked") ? 1 : 0,
                            type: $("input[name='companyData']:checked").val()
                        },
                        success: function (response) {
                            if(response.fieldError)
                            {
                                $('.errorMsg').remove();
                                var anim;
                                $.each(response.fieldError, function(i, obj) {
                                    $('#'+obj.field).addClass('error');
                                    //check box field : set span after label
                                    var attribute = $('#'+obj.field).attr('type');                                    
                                    if( attribute == 'checkbox'){
                                       $('#'+obj.field).parent().after('<span class="errorMsg">'+obj.msg+'</span>'); 
                                       anim = ".form-item.checkbox";
                                    } else {
                                        $('#'+obj.field).after('<span class="errorMsg">'+obj.msg+'</span>');  
                                        anim = "input.error";  
                                    }                                
                                });
                                $('html, body').animate({
                                    scrollTop: $(anim).offset().top-50
                                }, 1000);

                            }
                            else
                            {
                                $(".msgs").html(response.msg).fadeIn();
                                setTimeout(function(){
                                    $(".msgs").text('').fadeOut();
                                },3000) // 3 second.
                            }                              
                        },
                        error: function (response) {
                            alert(response);
                        }
                    });
                })
            }                                        
        };

        Login.init();

        //close session if inactive
        var inactivityTime = function () {
            var t;
            window.onload = resetTimer;
            // DOM Events

            document.onmousemove = resetTimer;
            document.onkeypress = resetTimer;

            function logout() {
                //after logout go to some page
                var url = window.location.href;
                var arg = url.split('/').pop();
                var lang = $('body').attr('data-lang');
                if(arg == 'tz-checkout' || arg == 'tz-students')
                {
                    var gotopage = '/tumble-zone/';
                }
                else
                { 
                    var gotopage = '/'+lang+'/';
                }
                $.ajax({
                    async: false,                     
                    type: "POST",
                    url: '/login.php',
                    data: {
                        action: 'logout'
                    },
                    success:function(data) {

                        if(data == 'logged out!')
                        {
                            window.location.href = gotopage;
                        }
                    },
                    error: function (response) {
                        console.log(response);
                    }                     
                });                
                //location.href = 'logout.php'
            }

            function resetTimer() {
                clearTimeout(t);
                t = setTimeout(logout, 900000)
                // 1000 milisec = 1 sec
            }
        };
        inactivityTime();        
    });
}(jQuery));