﻿//verify login
$(function () {
    ResizeHeight();
    $(window).resize(ResizeHeight);  
    $(window).scroll(ResizeHeight);  

    //class On
    var location = window.location.toString();
    var routes = location.split('/');
   
    var comp = '/'+routes[3];
    if(routes.length > 4) comp += '/'+routes[4];

    $('#ToolBar .CompanyMenu a').each(function(){
        if($(this).attr('href') == comp)
            $(this).addClass('On');
    });

    //login panel
    if (window.location.hash == "#login") { 
        if($('#ToolBar .LoginPanel').hasClass('Hide')){
            Authentication.ShowHidePanel(true);
        }
    }

    $('#ToolBar .Link').click(function () {
        if($('#ToolBar .LoginPanel').hasClass('Hide')){
            Wishlist.ShowHidePanel(false);
            Authentication.ShowHidePanel(true);
        }else{
            Authentication.ShowHidePanel(false);
        }
    });

    //logout
    $('#ToolBar .Logout .Link').click(function () {
        Authentication.Logout();
    });

    //required validate
    $.extend($.validator.messages, {
        required: "Campo Obrigatório!"
    });

    $('#RecoverPassword').validate({
        messages: {
            Email: "E-mail Inválido!"
        },
        errorPlacement: function (error, element) {
            error.appendTo('#StatusRecover');
        },
        submitHandler: function (form) {
            Authentication.RecoverPassword($('#EmailRecoverPassword'), $('#StatusRecover'));
        }
    });

    $('#AccountCreateForm').validate({
        rules: {
            AccountCreateNIF: { minlength: 9 },
            AccountCreatePassword: { minlength: 6 },
            AccountCreateConfirmPassword: { equalTo: "#AccountCreatePassword" }
        },
        messages: {
            AccountCreateNIF: "NIF Inválido!",
            AccountCreateEmail: "E-mail Inválido!",
            AccountCreatePassword: "Password inválida, mínimo 6 caracteres!",
            AccountCreateConfirmPassword: "Passwords não coincidem!",
        },
        errorPlacement: function (error, element) {
            error.appendTo(element.prev());
        }
    });

    $('#Login').validate({
        messages: {
            Email: "E-mail Inválido!"
        },
        errorPlacement: function (error, element) {
            $('#ToolBar .LoginPanel').effect("shake", { times: 3 }, 50);
            error.appendTo('#Status');
        },
        submitHandler: function (form) {
            Authentication.Login($('#Username'), $('#Password'), $('#Status'));
        }
    });

});

function ResizeHeight() {
    $('#MyBoxWrapper').height($('body').height() + 'px');
    $('#MyBoxWrapper').css('line-height', $('body').height() + 'px');
}

function getFeaturedProduct(CategoryID, LanguageID, Status, Callback) {
    var FeatProduct;
    $(Status).show().addClass('Loading');
    $.ajax({
            url: '/api/Product/getFeaturedProduct',
            data: 'a=getFeaturedProduct&CategoryID=' + CategoryID + '&LanguageID='+LanguageID,
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                FeatProduct = data.product;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown); 
            },
            complete: function(){
                $(Status).removeClass('Loading').hide();
                if (typeof Callback == "function") Callback(FeatProduct);
                //console.clear();
            }
        });
        return false;
}

//Authentication
var Authentication = new (function () {

    that = this;

    this.RecoverPassword = function (Email, Status) {
        $.ajax({
            url: '/api/Account/RecoverPassword',
            data: 'a=RecoverPassword&Email=' + $(Email).val(),
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                $(Status).html('').removeClass('Loading');
                if (data.error) {
                    $(Status).html(data.status);
                }else{
                    MyBox.Create({
                        Text: data.status,
                        Action: "Ok",
                        State: "Success",
                        onClick: function(){
                            window.location.reload();
                        }
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown); 
                $(Status).html('').removeClass('Loading');
            },
            complete: function(){
                //console.clear();
            }
        });
        return false;
    };

    this.Login = function (Username, Password, Status) {
        $(Status).addClass('Loading');
        $.ajax({
            url: '/api/Account/Login',
            data: 'a=Login&Email=' + $(Username).val() + '&Password=' + $.md5($(Password).val()),
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                $(Status).html('').removeClass('Loading');
                if (data.error) {
                    $('#ToolBar .LoginPanel').effect("shake", { times: 3 }, 50);
                    $(Status).html(data.status).fadeIn().delay(1500).fadeOut();
                }else{
                    window.location.reload(true);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown); 
                $(Status).html('').removeClass('Loading');
            },
            complete: function(){
                //console.clear();
            }
        });
        return false;
    };

    this.Logout = function (Status) {
        $.ajax({
            url: '/api/Account/LogOut',
            data: 'a=Logout',
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                if (!data.error) {
                    window.location = "/";
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown); 
                $(Status).empty();
            },
            complete: function(){
                //console.clear();
            }
        });
        return false;
    };

    that.ShowHidePanel = function(ShowHide){
        if(ShowHide){
            $('#ToolBar .LoginPanel').show().animate({ top: 30, opacity: 1 }, { duration: 380, easing: 'easeOutBack' });
            $('#ToolBar .LoginPanel').removeClass('Hide').addClass('Show');
        }else{
            $('#ToolBar .LoginPanel').animate({ top: -160, opacity: 0 }, { duration: 380, easing: 'easeInBack' }).fadeOut();
            $('#ToolBar .LoginPanel').removeClass('Show').addClass('Hide');
        }
    }

})();

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();
