﻿$(function () {
    //Share Facebook
    $('#ShareWishlistFacebook .Submit').click(function () {
        var Message = $(this).parent().find('.Text').val();
        Wishlist.Share(Message);
    });

    //Turn notification ON/OFF
    $('#WishlistTable .AlertNotification').change(function(){
        var val = 0;
        if($(this).is(':checked')) val = 1;
        Wishlist.ChangePriority($(this).parents('tr').find('.ProductID').val(), val);   
    });
    
    //Notification ?
    $('#WishlistTable .QuestionIcon').click(function(){
        var HTML = "Se desejar ser notificado quando o produto estiver em stock, selecione esta opção.";
        MyBox.Create({
            Text: HTML,
            Action: "Ok"
        });
    });

    //Delete from table
    $('#WishlistTable .DeleteBtn').click(function(){
        Wishlist.Delete($(this).parents('tr').find('.ProductID').val(), true);   
    });

    //Show wishlist panel
    $('#ToolBar .WishList .Clickable').click(function(){
        if($(this).parent().hasClass('On')) {
            Wishlist.ShowHidePanel(false);
        }
        else {
            Wishlist.ShowHidePanel(true);
        }
        
        if($('#ToolBar .LoginPanel').hasClass('Show')){
            Authentication.ShowHidePanel(false);
        }
    });

    //Add to wishlist DetailProductID
    $('#Wishlist').click(function(){
        if (Wishlist.isUserEmail($('#ClientEmail').val())) {
            Wishlist.GetLoggedEmaill(function (email) {
                if ($('#ClientEmail').val() == email) {
                    Wishlist.Add($('#DetailProductID').val());          
                }
            });
        }else{
            MyBox.Create({
                Text: "Precisa estar autenticado!",
                Action: "Ok",
                onClick: function(){
                    $(window).scrollTo($('#ToolBar'), 850, function () {
                        if($('#ToolBar .LoginPanel').hasClass('Hide')){
                            $('#ToolBar .Login .Link').click();
                        }
                    });
                }
            });
        }
    })

    //Check client
    if (Wishlist.isUserEmail($('#ClientEmail').val())) {
        Wishlist.GetLoggedEmaill(function (email) {
            if ($('#ClientEmail').val() == email) {
                Wishlist.Get();          
            }
        });
    }else{
        $('#ToolBar .WishList').find('.ItemCount').text(0);
    }

});

var Wishlist = new (function () {

    that = this;

    this.Bind = function(){
        $('#MasterWishList .RemoveBtn').click(function(){
            var reload = false;
            if(window.location.href.indexOf('wishlist') != -1){ reload = true; }
            Wishlist.Delete($(this).parent().find('.ProductID').val(), reload);   

        });
    }

    this.Get = function(){
        $.ajax({
            url: '/api/Account/GetWishlist',
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                if (data.error) {
                   $('#MasterWishList .Bottom').append('<div class="NoItems">Ocorreu um erro na Wishlist, contacte a Administação.</div>')
                } else {
                   Wishlist.Write($('#MasterWishList .Bottom'), data.products);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown);
            },
            complete: function () {
                ////console.clear();
            }
        });
        return true;
    }

    this.Add = function (ProductID) {
        $.ajax({
            url: '/api/Account/AddWishlistLine',
            data: 'ProductID=' + ProductID,
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                if (data.error) {
                    MyBox.Create({
                        Text: data.status,
                        Action: "Ok",
                        State: "Error"
                    });

                } else {
                    Wishlist.Get();  
                    MyBox.Create({
                        Text: data.status,
                        Action: "Ok",
                        State: "Success",
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown);
            },
            complete: function () {
                //console.clear();
            }
        });
        return true;
    };

    this.Delete = function(ProductID, Reload){
        $.ajax({
            url: '/api/Account/DeleteWishlistLine',
            data: 'ProductID=' + ProductID,
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                if (data.error) {
                    MyBox.Create({
                        Text: data.status,
                        Action: "Ok",
                        State: "Error"
                    });
                } else {
                    Wishlist.Get();  
                    MyBox.Create({
                        Text: data.status,
                        Action: "Ok",
                        State: "Success",
                        onClick: function(){
                            if(Reload){
                                window.location.reload();
                            }
                        }
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown);
            },
            complete: function () {
                //console.clear();
            }
        });
        return true;
    };

    this.ChangePriority = function(ProductID, Priority){
        $.ajax({
            url: '/api/Account/ChangePriority',
            data: 'ProductID=' + ProductID +'&Priority=' + Priority,
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                if (data.error) {
                    MyBox.Create({
                        Text: data.status,
                        Action: "Ok",
                        State: "Error"
                    });
                } else {
                    MyBox.Create({
                        Text: data.status,
                        Action: "Ok",
                        State: "Success"
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown);
            },
            complete: function () {
                //console.clear();
            }
        });
        return true;
    };

    this.Share = function(Message){

        if (Message.length > 0) {
            Wishlist.GetEncryptedIDByEmail($('#ClientEmail').val(), function (ID) {
                if (ID != -1) {

                    FB.login(function (response) {

                        if (response.status == "connected") {                            if(response.perms != null){

                                var publish = {
                                    method: 'stream.publish',
                                    message: Message,
                                    picture: 'http://' + window.location.host + '/Uploads/icon-wishlist.png',
                                    link: 'http://' + window.location.host + '/pt/wishlist/' + ID,
                                    name: 'A minha Wishlist de Brinquedos',
                                    caption: 'http://pimpumplay.pt',
                                    description: 'Dá uma vista de olhos na minha Wishlist da PimPumPlay.',
                                    actions: { name: 'PimPumPlay', link: 'http://facebook.com/pimpumplay' }
                                };
                                FB.api('/' + response.session.uid + '/feed', 'POST', publish, function (response) {
                                    console.log(response)
                                    if (response.id != undefined) {
                                        MyBox.Create({
                                            Text: 'Wishlist partilhada com sucesso!',
                                            Action: 'Ok',
                                            State: 'Success'
                                        });
                                    }
                                });
                            } else {
                                // user is not logged in                                MyBox.Create({
                                    Text: 'Precisa de dar premissões de acesso para publicar a Wishlist no seu Facebook.',
                                    Action: 'Ok'
                                });
                            }                        }else{                            // user is not logged in                            MyBox.Create({
                                Text: 'Precisa de estar logado ao Facebook para publicar a Wishlist no seu Facebook.',
                                Action: 'Ok'
                            });                        }
                    }, { perms: 'offline_access,email,publish_stream' });

                } else {
                    MyBox.Create({
                        Text: 'Precisa de estar autênticado para partihar a sua wishlist.',
                        Action: 'Ok'
                    });
                }
            });
        } else {
            MyBox.Create({
                Text: 'Insira uma mensagem.',
                Action: 'Ok',
                State: 'Error'
            });
        }
    };

    this.Write = function(el, p){
        var HTML = '<div class="List">';

        $(el).parents('.WishList').find('.ItemCount').text(p.Products.length);

        if(p.Products.length > 0){
            for(var i in p.Products){
                if(i < 6){
                    HTML += '<div class="WhislistLine">';
                    HTML += '<input class="ProductID" type="hidden" value="'+p.Products[i].ID+'" />';
                    HTML += '<a class="ProductName" href="/pt/produto/'+p.Products[i].Category+'/'+p.Products[i].Slug+'">'+p.Products[i].Name+'</a>';
                    HTML += '<span class="RemoveBtn">X</span>';
                    HTML += '</div>\n';
                }
            }
        
            HTML += '</div>';

            if(p.Products.length > 5){
                HTML += '<div class="TooMuch">...</div>';
            }

            HTML += '<a href="/pt/wishlist" class="SeeWishlist">ver Wishlist completa</a>';
        }else{
            HTML += '<div class="NoItems">Não tem nenhum produto adicionado à Wishlist</div>';
        }

        $(el).html(HTML);

        Wishlist.Bind();

    }

    this.ShowHidePanel = function(Show){
        if(Show){
            $('#ToolBar .WishList').addClass('On');
            $('#MasterWishList').show().animate({ top: 40, opacity: 1 }, { duration: 380, easing: 'easeOutBack' });
        }else{
            $('#ToolBar .WishList').removeClass('On');
            $('#MasterWishList').animate({ top: 15, opacity: 0 }, { duration: 380, easing: 'easeInBack' }).fadeOut();
        }
    }

    this.GetEncryptedIDByEmail = function(Email, callback){
        var ID;
        $.ajax({
            url: '/api/Account/GetEncryptedIDByEmail',
            data: 'Email='+Email,
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                if (data.error) {
                    ID = -1;
                } else {
                    ID = data.ID;
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown);
            },
            complete: function () {
                //console.clear();
                if (typeof callback == "function") callback(ID);
            }
        });
    }

    this.GetLoggedEmaill = function (callback) {
        var email = "";
        $.ajax({
            url: '/api/Account/GetCurrentClientEmail',
            type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {
                if (data.error) {
                    email = -1;
                } else {
                    email = data.email;
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ' ' + errorThrown);
            },
            complete: function () {
                ////console.clear();
                if (typeof callback == "function") callback(email);
            }
        });
    }

    this.isUserEmail = function (Email) {
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return filter.test(Email);
    }

})();

