//== Class Definition
var SnippetLogin = function() {

    var login = $('#m_login');

    var showErrorMsg = function(form, type, msg) {
        var alert = $('<div class="m-alert m-alert--outline alert alert-' + type + ' alert-dismissible" role="alert">\
			<button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>\
			<span></span>\
		</div>');

        form.find('.alert').remove();
        alert.prependTo(form);
        //alert.animateClass('fadeIn animated');
        mUtil.animateClass(alert[0], 'fadeIn animated');
        alert.find('span').html(msg);
    }
    
    $.ajax({
        type: "POST",
        data: "",
        dataType: "text",
        url: DUrl + "WebServiceOsiris.asmx/Get_Version",

        cache: false,
        async: true,
        success: function (data) {
            $('.copyright').append(' v.' + $(data)[2].innerHTML.substr(0, $(data)[2].innerHTML.length - 2));
        },
        error: function (a, b, c) {
            debugger;
        }
    });
    
    GetData.SingleSqlValue('Season','OS_App_Data','1 = 1', true, true, function(ret) {
        $('[name="season"]').append(ret[0].Season.split(',').map(function(val, i) { 
            return '<option ' + (i == ret[0].Season.split(',').length - 1 ? 'selected="selected"' : '') + '>' + val + '</option>';
        }).join());
        $('[name="season"]').select2();
    })
    
    GetData.SingleSqlValue('Name','OS_Catalog','Category = 2', true, true, function(ret) {
        $('[name="site"]').append('<option> </option>');
        for(var i = 0; i < ret.length; i++) {
            $('[name="site"]').append('<option>' + ret[i].Name + '</option>');
        }
        $('[name="site"]').select2({
            placeholder: "Site",
            allowClear: true
        });
        $('[name="site"]').on('change', function() {  // when the value changes
            $(this).valid(); // trigger validation on this element
        });
    })
    
    GetData.SingleSqlValue('Name','OS_Catalog','Category = 3', true, true, function(ret) {
        $('[name="function"]').append('<option> </option>');
        for(var i = 0; i < ret.length; i++) {
            $('[name="function"]').append('<option>' + ret[i].Name + '</option>');
        }
        $('[name="function"]').select2({
            placeholder: "Function",
            allowClear: true
        });
        $('[name="function"]').on('change', function() {  // when the value changes
            $(this).valid(); // trigger validation on this element
        });
    })
    
    $('[name="environment"]').select2();
    //== Private Functions

    var displaySignUpForm = function() {
        login.removeClass('m-login--forget-password');
        login.removeClass('m-login--signin');

        login.addClass('m-login--signup');
        mUtil.animateClass(login.find('.m-login__signup')[0], 'flipInX animated');
    }

    var displaySignInForm = function() {
        login.removeClass('m-login--forget-password');
        login.removeClass('m-login--signup');

        login.addClass('m-login--signin');
        mUtil.animateClass(login.find('.m-login__signin')[0], 'flipInX animated');
        //login.find('.m-login__signin').animateClass('flipInX animated');
    }

//    var displayForgetPasswordForm = function() {
//        login.removeClass('m-login--signin');
//        login.removeClass('m-login--signup');
//
//        login.addClass('m-login--forget-password');
//        //login.find('.m-login__forget-password').animateClass('flipInX animated');
//        mUtil.animateClass(login.find('.m-login__forget-password')[0], 'flipInX animated');
//
//    }

    var handleFormSwitch = function() {
        $('#m_login_forget_password').click(function(e) {
            e.preventDefault();
            displayForgetPasswordForm();
        });

        $('#m_login_forget_password_cancel').click(function(e) {
            e.preventDefault();
            displaySignInForm();
        });

        $('#m_login_signup').click(function(e) {
            e.preventDefault();
            displaySignUpForm();
        });

        $('#m_login_signup_cancel').click(function(e) {
            e.preventDefault();
            displaySignInForm();
        });
    }

    var handleSignInFormSubmit = function() {
        $('#m_login_signin_submit').click(function(e) {
            e.preventDefault();
            var btn = $(this);
            var form = $(this).closest('form');

            form.validate({
                rules: {
                    email: {
                        required: true,
                        email: true
                    },
                    password: {
                        required: true
                    }
                }
            });

            if (!form.valid()) {
                return;
            }

            btn.addClass('m-loader m-loader--right m-loader--light').attr('disabled', true);

            form.ajaxSubmit({
                url: '',
                success: function(response, status, xhr, $form) {
                    
                    if ($('[name="environment"]').val() == 'Test') {
                        if (Functions.isLocalStorageNameSupported()) {
                            SetData.localStorage('AccessLevel', 3);
                            SetData.localStorage('ActiveLanguage', 2);
                            SetData.localStorage('Classification', 'TestEnvironment');
                            SetData.localStorage('EmpName', 'John Doe');
                            SetData.localStorage('NickName', 'John');
                            SetData.localStorage('OpenForm', 'Dashboard');
                            SetData.localStorage('Picture', '');
                            SetData.localStorage('SubClassification', 'Breeding,Supply Chain');
                            SetData.localStorage('Title', '');
                            SetData.localStorage('UserId', 'test');
                            SetData.localStorage('Phone', '');
                            SetData.localStorage('Remark', '');
                            SetData.localStorage('Supervisor', '');
                            SetData.localStorage('WorkExt', '');
                            SetData.localStorage('RO', 0);
                            SetData.localStorage('ID', 99999999);
                            SetData.localStorage('Current_Page', '');
                            SetData.StartSyncDates();
                            if (GetData.localStorage('PrevPage') != undefined && GetData.localStorage('PrevPage') != '') {
                                location.href = GetData.localStorage('PrevPage');
                            } else {
                                location.href = "app_select.html";
                            }
                        }
                    } else {
                        var UserJSON = '{"Username": "' + $('[name="username"]').val() + '", "Password": "' + escape($('[name="password"]').val().replace(/\+/g, '(PLUS)')) + '"}';
                        $.ajax({
                            type: "POST",
                            data: "IDUser=" + UserJSON,
                            dataType: "text",
                            url: DUrl + "WebServiceOsiris.asmx/LoginIn",

                            cache: false,
                            success: function (data) {

                                var xml = data,
                                xmlDoc = $.parseXML(xml),
                                $xml = $(xmlDoc),
                                $title = $xml.find("string");

                                if ($title.text() == 'Error_AD') {
                                    btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
                                    showErrorMsg(form, 'danger', 'Monsanto Password or User incorrect.  Please try again.');
                                } else if ($title.text() == '[]') {
                                    btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
                                    showErrorMsg(form, 'danger', 'User is not register in Osiris.  Please try again or Sign Up to login into Osiris.');
                                } else {
                                    var UserData = JSON.parse($title.text());
                                    if (Functions.isLocalStorageNameSupported()) {
                                        SetData.localStorage('AccessLevel', UserData[0].AccessLevel);
                                        SetData.localStorage('ActiveLanguage', UserData[0].Language);
                                        SetData.localStorage('Classification', UserData[0].Classification.split(",")[0]);
                                        SetData.localStorage('EmpName', UserData[0].Name);
                                        SetData.localStorage('NickName', UserData[0].NickName);
                                        SetData.localStorage('OpenForm', 'Dashboard');
                                        SetData.localStorage('Picture', UserData[0].Picture);
                                        SetData.localStorage('SubClassification', UserData[0].SubClassification);
                                        SetData.localStorage('Title', UserData[0].Title);
                                        SetData.localStorage('UserId', UserData[0].UserId);
                                        SetData.localStorage('Phone', UserData[0].Phone);
                                        SetData.localStorage('Remark', UserData[0].Remark);
                                        SetData.localStorage('Supervisor', UserData[0].Supervisor);
                                        SetData.localStorage('WorkExt', UserData[0].WorkExt);
                                        SetData.localStorage('RO', UserData[0].ReadOnly);
                                        SetData.localStorage('ID', UserData[0].id_User);
                                        SetData.localStorage('Season', $('[name="season"]').select2('val'));
                                        SetData.localStorage('Current_Page', '');
                                        SetData.StartSyncDates();
                                        if (GetData.localStorage('PrevPage') != undefined && GetData.localStorage('PrevPage') != '') {
                                            location.href = GetData.localStorage('PrevPage');
                                        } else {
                                            location.href = "app_select.html";
                                        }
                                    } else {
                                        btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
                                        showErrorMsg(form, 'danger', 'You probably have the browser in private mode.  Please change it before using Osiris.  Thanks.');
                                    }
                                }
                            },
                            error: function (a, b, c) {
                                btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
                                showErrorMsg(form, 'danger', 'There were some errors on the form.  Please try again.');
                            }
                        });
                    }
                }
            });
        });
    }

    var handleSignUpFormSubmit = function() {
        $('#m_login_signup_submit').click(function(e) {
            e.preventDefault();

            var btn = $(this);
            var form = $(this).closest('form');

            form.validate({
                rules: {
                    fullname: {
                        required: true
                    },
                    username: {
                        required: true
                    },
                    password: {
                        required: true
                    },
                    site: {
                        required: true
                    },
                    function: {
                        required: true
                    }
                }
            });

            if (!form.valid()) {
                return;
            }

            btn.addClass('m-loader m-loader--right m-loader--light').attr('disabled', true);

            form.ajaxSubmit({
                url: '',
                success: function(response, status, xhr, $form) {
                	var UserJSON = '{"Name": "' + $('[name="fullname"]').val() + '", "Site": "' + $('[name="site"]').select2('val') + '", "Function": "' + $('[name="function"]').select2('val') + '", "Username": "' + $('[name="username2"]').val() + '", "Password": "' + escape($('[name="password2"]').val().replace(/\+/g, '(PLUS)')) + '"}';
                        $.ajax({
                            type: "POST",
                            data: "IDUser=" + UserJSON,
                            dataType: "text",
                            url: DUrl + "WebServiceOsiris.asmx/LoginUp",

                            cache: false,
                            success: function (data) {

                                var xml = data,
                                xmlDoc = $.parseXML(xml),
                                $xml = $(xmlDoc),
                                $title = $xml.find("string");

                                if ($title.text() == 'Error_AD') {
                                    btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
                                    showErrorMsg(form, 'danger', 'Monsanto Password or User incorrect.  Please try again.');
                                } else {
                                    var UserData = JSON.parse($title.text());
                                    if (Functions.isLocalStorageNameSupported()) {
                                        SetData.localStorage('AccessLevel', UserData[0].AccessLevel);
                                        SetData.localStorage('ActiveLanguage', UserData[0].Language);
                                        SetData.localStorage('Classification', UserData[0].Classification.split(",")[0]);
                                        SetData.localStorage('EmpName', UserData[0].Name);
                                        SetData.localStorage('NickName', UserData[0].NickName);
                                        SetData.localStorage('OpenForm', 'Dashboard');
                                        SetData.localStorage('Picture', UserData[0].Picture);
                                        SetData.localStorage('SubClassification', UserData[0].SubClassification);
                                        SetData.localStorage('Title', UserData[0].Title);
                                        SetData.localStorage('UserId', UserData[0].UserId);
                                        SetData.localStorage('Phone', UserData[0].Phone);
                                        SetData.localStorage('Remark', UserData[0].Remark);
                                        SetData.localStorage('Supervisor', UserData[0].Supervisor);
                                        SetData.localStorage('WorkExt', UserData[0].WorkExt);
                                        SetData.localStorage('RO', UserData[0].ReadOnly);
                                        SetData.localStorage('ID', UserData[0].id_User);
                                        SetData.localStorage('Season', $('[name="season"]').select2('val'));
                                        SetData.localStorage('Current_Page', '');
                                        SetData.StartSyncDates();
                                        if (GetData.localStorage('PrevPage') != undefined && GetData.localStorage('PrevPage') != '') {
                                            location.href = GetData.localStorage('PrevPage');
                                        } else {
                                            location.href = "app_select.html";
                                        }
                                    } else {
                                        btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
                                        showErrorMsg(form, 'danger', 'You probably have the browser in private mode.  Please change it before using Osiris.  Thanks.');
                                    }
                                }
                            },
                            error: function (a, b, c) {
                                debugger;
                                btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
                                showErrorMsg(form, 'danger', 'There were some errors on the form.  Please try again.');
                            }
                        });
                }
            });
        });
    }

//    var handleForgetPasswordFormSubmit = function() {
//        $('#m_login_forget_password_submit').click(function(e) {
//            e.preventDefault();
//
//            var btn = $(this);
//            var form = $(this).closest('form');
//
//            form.validate({
//                rules: {
//                    email: {
//                        required: true,
//                        email: true
//                    }
//                }
//            });
//
//            if (!form.valid()) {
//                return;
//            }
//
//            btn.addClass('m-loader m-loader--right m-loader--light').attr('disabled', true);
//
//            form.ajaxSubmit({
//                url: '',
//                success: function(response, status, xhr, $form) { 
//                	// similate 2s delay
//                	setTimeout(function() {
//                		btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false); // remove 
//	                    form.clearForm(); // clear form
//	                    form.validate().resetForm(); // reset validation states
//
//	                    // display signup form
//	                    displaySignInForm();
//	                    var signInForm = login.find('.m-login__signin form');
//	                    signInForm.clearForm();
//	                    signInForm.validate().resetForm();
//
//	                    showErrorMsg(signInForm, 'success', 'Cool! Password recovery instruction has been sent to your email.');
//                	}, 2000);
//                }
//            });
//        });
//    }

    //== Public Functions
    return {
        // public functions
        init: function() {
            handleFormSwitch();
            handleSignInFormSubmit();
            handleSignUpFormSubmit();
//            handleForgetPasswordFormSubmit();
        }
    };
}();

//== Class Initialization
jQuery(document).ready(function() {
    SnippetLogin.init();
});