﻿var Scorett;

if (typeof Scorett === "undefined") {
    Scorett = {};
}

Scorett = function () {
    var _productXSmallImageIndex = 0;

    // OnInit
    function _init() {
    }

    return {
        // Returns alert if class exists
        ClassExists: function () {
            alert('Scorett class exists!');
        },
        // Sets empty labels to text inputs
        TextboxDefaultText: function () {
            $('.emptymessage:text').each(function () {
                this.value = $(this).attr('title'); // value for empty inputs
                $(this).addClass('text-label');

                // input on focus event
                $(this).focus(function () {
                    if (this.value == $(this).attr('title')) {
                        this.value = '';
                        $(this).removeClass('text-label');
                    }
                });

                // input on blur events
                $(this).blur(function () {
                    if (this.value == '') {
                        this.value = $(this).attr('title');
                        $(this).addClass('text-label');
                    }
                });
            });
        },

        // Set default popups
        SetDefaultPopupDialog: function () {
            // Set all with css class .popup-dialog
            if ($(".popup-dialog").is('*')) {
                $(".popup-dialog").each(function (index) {
                    $(this).dialog({
                        autoOpen: false,
                        draggable: true,
                        resizable: false,
                        width: 'auto',
                        modal: true,
                        open: function (type, data) {
                            $(this).parent().appendTo("body");
                        }
                    });
                });
            }
        },
        SetDefaultLoginPopupDialog: function () {
            // Set all with css class .popup-dialog
            if ($(".popup-dialog-login").is('*')) {
                $(".popup-dialog-login").each(function (index) {
                    $(this).dialog({
                        autoOpen: false,
                        draggable: true,
                        resizable: false,
                        width: 'auto',
                        modal: true,
                        open: function (type, data) {
                            $(this).parent().appendTo("body");
                        },
                        close: function (type, data) {
                            var url = window.location.href.replace('#');
                            window.location = url;
                        }
                    });
                });
            }
        },

        // Open dialog
        OpenDialogBox: function (element, destroyOnClose) {
            var destroy = destroyOnClose != undefined ? destroyOnClose : false;
            $(element).dialog('open');
            $('.ui-widget-overlay').click(function () {
                if (destroy) {
                    $(element).dialog('destroy');
                }
                else {
                    $(element).dialog('close');
                }
            });
        },

        // Open Ajax dialog
        OpenAjaxDialogBox: function (dialogElementId, url, destroyOnClose) {
            var destroy = destroyOnClose != undefined ? destroyOnClose : false;

            $.ajax({
                type: 'GET',
                url: url,
                success: function (data) {
                    $('#' + dialogElementId).dialog('open');
                    $('#' + dialogElementId + ' .content:first-child').html(data);
                    $('.ui-widget-overlay').click(function () {
                        if (destroy) {
                            $('#' + dialogElementId).dialog('destroy');
                        }
                        else {
                            $('#' + dialogElementId).dialog('close');
                        }
                    });
                }
            });
        },
        //Get selected shops
        GetSelectedShops: function (url) {
            $.ajax
        (
            {
                type: 'POST',
                url: url,
                data: {},
                success: function (data) {
                    $('#shopcontent').html(data);
                }
            }
        )
        },
        //Set filter
        SetFilter: function (url) {

            var display = parseInt($('#navigiation-list').data('displayed'));
            if (isNaN(display)) {
                display = 0;
            }

            $.ajax
            (
                {
                    type: 'POST',
                    url: url,
                    data: { displayed: display },
                    success: function (data) {
                        $('#productlist-products').find('ul:first').html(data);
                        $('#navigiation-list').data('displayed', display);
                        $('#navigiation-list').data('startindex', display);
                        Scorett.UpdateNavigation();
                        Scorett.UpdateNavigationVisibility();
                    }
                }
            )
        },
        //Remove filter
        UndoFilter: function (url) {

            var display = parseInt($('#navigiation-list').data('displayed'));
            if (isNaN(display)) {
                display = 0;
            }

            $.ajax
            (
                {
                    cache: false,
                    type: 'GET',
                    url: url,
                    data: { displayed: display },
                    success: function (data) {
                        var content = $('#productlist-products').find('ul:first');
                        if (content.length <= 0) {
                            $('#productlist-products').html('<ul>' + data + '</ul>');
                        }
                        else {
                            $(content).html(data);
                        }

                        Scorett.UpdateNavigation();
                        Scorett.UpdateNavigationVisibility();
                    }
                }
            )
        },
        CreateNavigation: function () {
            // Hide when total in list i less or equal to maxperpage 
            Scorett.UpdateNavigationVisibility();

            // Init navigation
            $('#navigiation-list').click(function (e) {
                $.ajax({
                    type: 'GET',
                    url: $(this).data('url'),
                    data: { startindex: $(this).data('startindex'), category: $(this).data('category') },
                    success: function (data) {
                        $('#productlist-products').find('ul:first').find('li:last').after(data);
                        startindex = $('#productlist-products').find('ul:first').find('li').length;

                        Scorett.UpdateNavigation();

                        $('#navigiation-list').data('displayed', startindex);
                        $('#navigiation-list').data('startindex', startindex);
                        $('#navigation').find('.navigation-displayed:first').text(startindex);

                        Scorett.UpdateNavigationVisibility();

                        $('#productlist-products').find('a').each(function () {
                            $(this).click(function () {
                                $.cookie('cookie-sp', $(this).attr('id'));
                            });
                        });
                    }
                });
            });

            $('#productlist-products').find('a').each(function () {
                $(this).click(function () {
                    $.cookie('cookie-sp', $(this).attr('id'));
                });
            });
        },
        UpdateNavigation: function () {
            var total = parseInt($('#hidden-navigation-total').attr('value'));
            var displayed = parseInt($('#hidden-navigation-displayed').attr('value'));
            var maxperpage = parseInt($('#navigiation-list:first').data('maxperpage'));

            if (!isNaN(total)) {
                $('#navigiation-list').data('total', total);
                $('.navigation-total:first').html(total);
            }

            if (!isNaN(displayed)) {
                $('.navigation-displayed:first').html(displayed);
            }

            if (!isNaN(total) && !isNaN(displayed) && total <= 0) {
                $('#navigation').hide();
                $('#noproductsfound').show();
            }
            else if (!isNaN(total) && !isNaN(displayed) && total > 0) {
                $('#navigation').show();
                $('#noproductsfound').hide();
            }

            if (!isNaN(total) && !isNaN(displayed) && !isNaN(maxperpage)) {
                if (maxperpage > (total - displayed)) {
                    $('.navigation-next:first').html((total - displayed));
                }
                else {
                    $('.navigation-next:first').html(maxperpage);
                }
            }

            $('#hidden-navigation-total').remove();
            $('#hidden-navigation-displayed').remove();
        },
        UpdateNavigationVisibility: function () {
            var total = parseInt($('#navigiation-list').data('total'));
            var maxperpage = parseInt($('#navigiation-list').data('maxperpage'));
            if (!isNaN(total) && !isNaN(maxperpage) && maxperpage >= total) {
                $('#navigiation-list').hide();
                return;
            }

            var displayed = parseInt($('#navigiation-list').data('displayed'));
            if (!isNaN(displayed) && !isNaN(total) && displayed >= total) {
                $('#navigiation-list').hide();
                return;
            }

            var nextpage = parseInt($('.navigation-next:first').text());
            if (!isNaN(nextpage) && nextpage <= 0) {
                $('#navigiation-list').hide();
            }
            else if (!isNaN(nextpage) && nextpage > 0) {
                $('#navigiation-list').show();
            }
        },
        //Get StartProducts
        StartProducts: function (url) {
            $.ajax
        (
            {
                type: 'POST',
                url: url,
                data: {},
                success: function (data) {
                    $('#start-products').html(data);
                }
            }
        )
        },
        //Selected paymenttype 
        Paymnettype: function (url) {
            $.ajax
        (
            {
                type: 'POST',
                url: url,
                data: {},
                success: function (data) {
                    if (data != null) {
                        $('#customer').removeClass('displaynone');
                        $('#customer').addClass('displayblock');
                        $('#confirm').css('display', 'block');
                        $('#summary').html(data);
                    }
                }
            }
        )
        },
        //Get klarnacustomer info
        KlarnaCustomer: function (url, number, email, cell) {
            $.ajax
        (
            {
                type: 'POST',
                url: url,
                data: { registrationNumber: number, email: email, cell: cell },
                success: function (data) {
                    if (!data.ok) {
                        $('#new-member').html(data);
                        $('.addressinfo').find('input').attr("readonly", "readonly")
                        $('.addressinfo').addClass('readonly');
                        $('.personnumbercheckout').css("display", "block");
                        $('#personnumbercheckout').removeAttr('disabled');

                    }
                }
            }
        )
        },
        ProductXSmallImageEvent: function (element, url, alt, destination, current, index) {
            _productXSmallImageIndex = index;
            var exists = $(destination).length;
            if ($(element).length > 0) {
                $(destination).children('img').css('display', 'none');
                $(destination).children(element).css('display', 'inline-block');
            }
            else {
                var id = element.replace("#", "");
                $(destination).append('<img id="' + id + '" style="display:none;" src="' + url + '" alt="' + alt + '" />');
                $(destination).children(element).load(function () {
                    $(destination).children('img').css('display', 'none');
                    $(destination).children(element).css('display', 'inline-block');
                });
            }
        },
        GetProductXSmallImageIndex: function () {
            return _productXSmallImageIndex;
        },
        SetProductXSmallImageIndex: function (index) {
            _productXSmallImageIndex = index;
        },
        AddToCart: function (url) {
            $.ajax
            (
                {
                    type: 'POST',
                    url: url,
                    data: {},
                    success: function (data) {
                        $('#top-minicart').html(data);
                        $('#buy-button').siblings('.alert-message').children('.alert-message-success-inner > span:first').html($('#minicart-status').attr('value'));
                        $('#buy-button').siblings('.alert-message').children('.error-message-inner').hide();
                        $('#buy-button').siblings('.alert-message').children('.error-message-notinstock-inner').hide();
                        $('#buy-button').siblings('.alert-message').children('.alert-message-success-inner').show();
                        $('#buy-button').siblings('.alert-message').fadeIn('fast').delay(1500).fadeOut('slow');
                    }
                }
            )
        },
        SortSerachList: function (url) {
            $.ajax
            (
                {
                    type: 'POST',
                    url: url,
                    data: {},
                    success: function (data) {
                        $('#search-productlist').html(data);
                    }
                }
            )
        },
        DeleteCart: function (url) {
            $.ajax
            (
                {
                    type: 'POST',
                    url: url,
                    data: {},
                    success: function (data) {
                        $('#top-minicart').html(data);
                    }
                }
            )
        },
        Logout: function (url) {
            $.ajax
            (
                {
                    type: 'POST',
                    url: url,
                    data: {},
                    success: function (data) {
                        if (data.ok)
                        { window.location = window.location }
                    }
                }
            )
        },
        NewPassword: function (url, email) {
            $.ajax
            (
                {
                    type: 'POST',
                    url: url,
                    data: { email: email },
                    success: function (data) {
                        alert(email);
                    }
                }
            )
        },
        ChangeSize: function (obj, url, addCartElement) {
            $(addCartElement).unbind("click");
            $(addCartElement).click(function (e) { Scorett.AddToCart(url); });
            $(obj).parent('.size-list').children('li').removeClass('selected');
            $(obj).addClass('selected');
        },
        SetBuyableProduct: function (url, addCartElement) {
            $(addCartElement).unbind("click");
            $(addCartElement).click(function (e) { Scorett.AddToCart(url); });
        },
        SizeNotInStock: function (obj) {
            $(obj).parent('.size-list').children('li').removeClass('selected');
            $(obj).addClass('selected');
            $('#buy-button').siblings('.alert-message').children('.error-message-inner').hide();
            $('#buy-button').siblings('.alert-message').children('.alert-message-success-inner').hide();
            $('#buy-button').siblings('.alert-message').children('.error-message-notinstock-inner').show();
            $('#buy-button').unbind("click");
            $('#buy-button').click(function (e) {
                $(this).siblings('.alert-message').fadeIn('fast');
                $(this).siblings('.alert-message').delay(1500).fadeOut('slow');
            });
        },
        CheckPersonnumber: function () {
            if ($('.personnumbercheckout').css('display') == 'none') {
                $('#solepersonnumber-checkout').removeAttr('style');
            }
            else {
                $('#solepersonnumber-checkout').css('display', 'none');
            }

        }
    };
} ();

// Document Ready functions
$(document).ready(function () {

    if ($("ul.subnav").is('*')) {
        //Dropdownlist
        $("ul.subnav").parent().append("<span></span>");
        $("ul.topnav li span").click(function () {
            var sub = $(this).parent().find("ul.subnav").css('display')
            if (sub == 'none') {
                $(this).parent().find("ul.subnav").slideDown('fast').show();
            }
            else {
                $(this).parent().find("ul.subnav").slideUp('fast');
            }
        }).hover(function () {
            $(this).children('ul').children('li').addClass("subhover");
        }, function () {
            $(this).children('ul').children('li').removeClass("subhover");
        });
    }

    // Load default text to textboxes
    if (typeof Scorett != "undefined") {
        // Set empty labels to text inputs
        Scorett.TextboxDefaultText();
        // Create dialogs
        Scorett.SetDefaultPopupDialog();
        //Create login dialog
        Scorett.SetDefaultLoginPopupDialog();
    }

    // Ajax
    $(document).ajaxStart(function () {
        if ($('#ajax-preloaderbox').is('*')) {
            $('#ajax-preloader').removeClass('error');
            $('#ajax-error').hide();
            $('#ajax-preloaderbox').show();
            $('#ajax-preloaderbox').css('z-index', '999999999');

            $('.ajax-button').each(function (e) {
                $(this).hide();
            });
            $('.ajax-preloader-button').each(function (e) {
                $(this).show();
            });
        }
    });

    $(document).ajaxSuccess(function () {
        if ($('#ajax-preloaderbox').is('*')) {
            $('#ajax-error').hide();
            $('#ajax-preloaderbox').hide();
        }

        $('.ajax-button').each(function (e) {
            $(this).show();
        });
        $('.ajax-preloader-button').each(function (e) {
            $(this).hide();
        });

    });

    $(document).ajaxError(function (e, xhr, settings, exception) {
        if ($('#ajax-error').is('*')) {
            $('#ajax-preloader').addClass('error');
            $('#ajax-error').show();
        }

        $('.ajax-button').each(function (e) {
            $(this).show();
        });
        $('.ajax-preloader-button').each(function (e) {
            $(this).hide();
        });
    });
});

