﻿$(document).ready(function () {
    
});

function SubmitForm(form) {
    $(form).find('.Status').html('<img src="/Content/images/ajax-loader.gif" alt="" />');
    $.post($(form).attr('action'), $(form).serialize(), function (data) {
        $(form).find('.Status').html(data.Status);
    }, 'json');
    return false;
}             


var Backoffice = {
    Load: function (Title, Url, Width, Height) { ZennWindow(Url, Width, Height); },
    Close: function () { ZennWindowClose(); },
    CloseAndRefresh: function () { ZennWindowCloseAndRefresh(); },
    CloseAndRedirect: function (Url) { ZennWindowCloseAndRedirect(Url); },
    NoticeDelete: function (IdNotice) {
        if (confirm('Tem a certeza que deseja eliminar este item?')) {
            $.ajax({
                url: 'API.ashx', data: 'a=NoticeDelete&IdNotice=' + IdNotice, type: 'POST', cache: false, dataType: 'json',
                success: function (data, textStatus) {
                    window.location = ResolveUrl;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ' ' + errorThrown); }
            });
        }
    },
    ContentDelete: function (IdContent) {
        if (confirm('Tem a certeza que deseja eliminar este item?')) {
            $.ajax({
                url: 'API.ashx', data: 'a=ContentDelete&IdContent=' + IdContent, type: 'POST', cache: false, dataType: 'json',
                success: function (data, textStatus) {
                    window.location = ResolveUrl;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ' ' + errorThrown); }
            });
        }
    },
    ContentOrderUpdate: function (E, IdContent, OrderDirection) {
        var options = $('#SidebarLeft .MenuOption');

        if (OrderDirection == 'UP' && $(E).parent().prev().length > 0) {
            var after = $($(E).parent().prev()[0]);
            if ($(after).hasClass('Admin')) return;
            $(E).parent().remove().insertBefore(after);
        }
        if (OrderDirection == 'DOWN' && $(E).parent().next().length > 0) {
            var after = $($(E).parent().next()[0]);
            $(E).parent().remove().insertAfter(after);
        }

        $.ajax({
            url: 'API.ashx', data: 'a=ContentOrderUpdate&IdContent=' + IdContent + '&OrderDirection=' + OrderDirection, type: 'POST', cache: false, dataType: 'json',
            success: function (data, textStatus) {

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ' ' + errorThrown); }
        });
    },

    Customers: new (function () {
        var that = this;
        that.Login = function (EmailElement, PasswordElement, StatusElement) {
            $(StatusElement).html('<img src="' + ResolveUrl + 'css/images/backoffice/loading-white.gif" alt="" />');
            $.ajax({
                url: 'Authentication.ashx', data: 'a=Login&Email=' + $(EmailElement).val() + '&Password=' + $.md5($.trim($(PasswordElement).val())), type: 'POST', cache: false, dataType: 'json',
                success: function (data, textStatus) {
                    $(StatusElement).html('');
                    if (data.error)
                        $(StatusElement).html(data.status);
                    else {
                        window.location.reload(true);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ' ' + errorThrown); $(StatusElement).empty(); }
            });
            return false;
        };

        that.Logout = function () {
            $.ajax({
                url: 'Authentication.ashx', data: 'a=Logout', type: 'POST', cache: false, dataType: 'json',
                success: function (data, textStatus) {
                    window.location = ResolveUrl + 'Default.aspx';
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ' ' + errorThrown); }
            });
        };

        that.NewsletterSubscribe = function (EmailElement, StatusElement) {

        };
    })(),

    Basket: new (function () {
        var that = this;


        that.Update = function (IdProduct, Quantity) {
            if (Quantity == '') return;
            jQuery.ajax({
                url: 'API.ashx', data: 'a=BasketUpdate&IdProduct=' + IdProduct + '&Quantity=' + Quantity, type: 'POST', cache: false, dataType: 'json',
                success: function (data, textStatus) {
                    that.Reload();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { }
            });
        };
        that.Remove = function (IdProduct) {
            if (confirm('Tem a certeza que deseja eliminar o item do seu carrinho de compras?')) {
                $.ajax({
                    url: 'API.ashx', data: 'a=BasketRemove&IdProduct=' + IdProduct, type: 'POST', cache: false, dataType: 'json',
                    success: function (data, textStatus) {
                        that.Reload();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) { }
                });
            }
        };

        that.Reload = function () {
            var url = $.url.attr('anchor') != null ? $.url.attr('anchor') : $.url.attr('source');
            url = url[url.length - 1] == '#' ? url.substr(0, url.length - 1) : url;
            Backoffice.Basket.UpdateStatus();
            Address.Load(url, '');
        };

        that.Start = function (OrderAmountElement, OrderDeliverOptionsElement, OrderPaymentOptionsElement, InvoiceSectionElement, DeliverSectionElement, DeliverAddressCopyBtn) {
            $(OrderDeliverOptionsElement).find('input').click(function () { that.AmountBudget(OrderAmountElement, OrderDeliverOptionsElement, OrderPaymentOptionsElement); });
            $(OrderPaymentOptionsElement).find('input').click(function () { that.AmountBudget(OrderAmountElement, OrderDeliverOptionsElement, OrderPaymentOptionsElement); });

            that.AddressCopy(DeliverAddressCopyBtn, InvoiceSectionElement, DeliverSectionElement);
            $(DeliverAddressCopyBtn).click(function () { that.AddressCopy(DeliverAddressCopyBtn, InvoiceSectionElement, DeliverSectionElement) });
            $(InvoiceSectionElement).find('input').keyup(function () { that.AddressCopy(DeliverAddressCopyBtn, InvoiceSectionElement, DeliverSectionElement) });
            $(InvoiceSectionElement).find('textarea').keyup(function () { that.AddressCopy(DeliverAddressCopyBtn, InvoiceSectionElement, DeliverSectionElement) });
        };

        that.AddressCopy = function (DeliverAddressCopyBtn, InvoiceSectionElement, DeliverSectionElement) {
            if ($(DeliverAddressCopyBtn).is(':checked')) {
                var inputs = $(InvoiceSectionElement).find('.copy');
                for (var i = 0; i != inputs.length; ++i) {
                    var id = $(inputs[i]).attr('id');
                    id = id.replace('Invoice', 'Deliver');
                    $('#' + id).val($(inputs[i]).val());
                }
                $(DeliverSectionElement).find('.copy').attr('readonly', 'readonly');
                $(DeliverSectionElement).find('.copy').addClass('readonly');
            }
            else {
                $(DeliverSectionElement).find('.copy').attr('readonly', '');
                $(DeliverSectionElement).find('.copy').removeClass('readonly');
            }
        };

        that.AmountBudget = function (OrderAmountElement, OrderDeliverOptionsElement, OrderPaymentOptionsElement) {
            var IdOrderDeliver = $(OrderDeliverOptionsElement).find('input:checked').val() != undefined ? $(OrderDeliverOptionsElement).find('input:checked').val() : '';
            var IdOrderPayment = $(OrderPaymentOptionsElement).find('input:checked').val() != undefined ? $(OrderPaymentOptionsElement).find('input:checked').val() : '';
            $.ajax({ url: 'API.ashx', data: 'a=OrderCalcAmount&IdOrderDeliver=' + IdOrderDeliver + '&IdOrderPayment=' + IdOrderPayment, type: 'POST', cache: false, dataType: 'text',
                success: function (data, textStatus) {
                    $(OrderAmountElement).html(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { }
            });
        };

        that.Submit = function (NavigationElement, StatusElement, InputsElements, OrderDeliverOptionsElement, OrderPaymentOptionsElement) {
            var inputs = $(InputsElements);
            $(NavigationElement).hide();
            $(StatusElement).html('A processar...');

            var IdOrderDeliver = $(OrderDeliverOptionsElement).find('input:checked').val() != undefined ? $(OrderDeliverOptionsElement).find('input:checked').val() : '';
            var IdOrderPayment = $(OrderPaymentOptionsElement).find('input:checked').val() != undefined ? $(OrderPaymentOptionsElement).find('input:checked').val() : '';

            var vars = 'a=OrderDo&IdLanguage=pt&IdOrderDeliver=' + IdOrderDeliver + '&IdOrderPayment=' + IdOrderPayment + '&Notes=' + encodeURI($('#PaymentObs').val());

            for (var i = inputs.length - 1; i >= 0; --i) {
                vars += '&' + $(inputs[i]).attr('id') + '=' + encodeURI($(inputs[i]).val());
            }

            $.ajax({ url: 'API.ashx', data: vars, type: 'POST', cache: false, dataType: 'json',
                success: function (data, textStatus) {
                    if (data.error) {
                        if (data.login != undefined) {
                            that.Reload();
                        }
                        $(NavigationElement).show();
                        $(StatusElement).html(data.status);
                    }
                    else {
                        that.UpdateStatus();
                        TabsBasket.Disable();
                        $(OrderDeliverOptionsElement).find('input').attr('disabled', 'disabled');
                        $(OrderPaymentOptionsElement).find('input').attr('disabled', 'disabled');
                    }
                    $(StatusElement).html(data.status);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { $(NavigationElement).show(); $(StatusElement).html(textStatus + ' ' + errorThrown); }
            });
        };

        that.UpdateStatus = function () {
            $.ajax({
                url: 'API.ashx', data: 'a=BasketStatusUpdate', type: 'POST', cache: false, dataType: 'json',
                success: function (data, textStatus) {                    
                    $('#BasketStatus').html(data.Quantity);
                    /*if (Number(data.Quantity) == 1)
                    $('#BasketStatus').html('<span class="CartIcon"></span> ver carrinho de compras (1 item) <span>|</span> finalizar compras');
                    else
                    $('#BasketStatus').html('<span class="CartIcon"></span> ver carrinho de compras (' + data.Quantity + ' items) <span>|</span> finalizar compras');*/
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ' ' + errorThrown); }
            });
        };

        that.Add = function (IdProduct, QuantityElement, StatusElement) {
            var Quantity = $(QuantityElement).val();
            if (isNaN(Quantity) || Number(Quantity) < 1) {
                Utilities.PopupMessage('<span class="Icon Icon-False">&nbsp;</span> Quantidade Inválida!', null);
                return;
            }
            $(StatusElement).html('<img src="' + ResolveUrl + 'css/images/backoffice/loading-white.gif" alt="" />');
            $.ajax({
                url: 'API.ashx', data: 'a=BasketAdd&IdProduct=' + IdProduct + '&Quantity=' + Quantity, type: 'POST', cache: false, dataType: 'json',
                success: function (data, textStatus) {
                    if (!data.error) {
                        that.UpdateStatus();
                        $(StatusElement).html('<span class="Icon Icon-True">&nbsp;</span>');
                        window.setTimeout(function () { $(StatusElement).find('.Icon').fadeOut().remove(); }, 1500);
                    }
                    else {
                        Utilities.PopupMessage('<span class="Icon Icon-False">&nbsp;</span> ' + data.status, null);
                        $(StatusElement).html('');
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ' ' + errorThrown); $('#Product-' + IdProduct + ' .Status').html(''); }
            });
        };
    })()
}

var Utilities = {
    PopupMessage: function (Message, TimeOut) {
        jQuery.facebox('<div class="PopUpMsg">' + Message + '</div>');
        if (TimeOut != null)
            window.setTimeout(function () { jQuery(document).trigger('close.facebox'); }, TimeOut);
    },
    PopupQuestion: function (Title, Question, YesFunction, NoFunction) {
        jQuery.facebox('<div class="PopUpMsg">' + Question + '</div>&nbsp;&nbsp;&nbsp;<span id="PopUpQuestionYes">Sim</span>&nbsp;&nbsp;<span id="PopUpQuestionNo">Não</span>');
        jQuery('#PopUpQuestionYes').click(function () { jQuery(document).trigger('close.facebox'); window.setTimeout(YesFunction, 500); });
        jQuery('#PopUpQuestionNo').click(function () { jQuery(document).trigger('close.facebox'); });
    },
    PopUpUrl: function (url, width, height, scrolling) {
        if (scrolling == undefined || scrolling == null) scrolling = 'auto';
        jQuery.facebox('<iframe src="' + url + '" width="' + width + '" height="' + height + '" scrolling="' + scrolling + '" frameborder="0"></iframe>');
    },
    getRandomInt: function (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
}


/*
* Validation Class
*
* Copyright (c) 2009-12-11   
* David Oliveira | david.oliveira@zenn.pt
* 
* Depends:
*	jQuery v1.3
*
* Example: Validation.IsEmail(email@email.com);
*
*/

var Validation = {
    IsNumberKey: function (evt) {
        try {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
        }
        catch (Error) { }
        return true;
    },
    IsEmail: function (str) {
        if (str.length == 0) return false;
        var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
        return re.test(str);
    }
}

/*
* Zenn Window
*
* Copyright (c) 2009-01-24   
* David Oliveira | david.oliveira@zenn.pt
* 
* Depends:
*	jQuery v1.3
*
* Notes: To Close Window from URL target, call parent.ZennWindowClose();
*
*/

function ZennWindow(/*String*/URL, /*Number*/Width, /*Number*/Height) {
    var fwImagesPath = '/Content/images/backoffice/';
    var modalWidth = Number(Width) + 20;
    var modalHeight = Number(Height);
    var modalPositionTop = (Number(jQuery(window).height()) - Number(modalHeight)) / 2;
    if (modalPositionTop < 0) modalPositionTop = 0;
    var modalPositionLeft = (Number(jQuery(window).width()) - Number(modalWidth)) / 2;
    if (modalPositionLeft < 0) modalPositionLeft = 0;

    jQuery('body').append('<div id="fwOverlay" style="position: absolute; top:0px; left:0px; z-index: 5; width: 100%; height:100%; filter: Alpha(Opacity=50); -moz-opacity:0.5; opacity: 0.5; background-color:#000000;"></div>');
    if (modalHeight > jQuery('#fwOverlay').height())
        jQuery('#fwOverlay').height(modalHeight + 45);

    var ie = jQuery.browser.msie;
    var version = jQuery.browser.version;

    var border = '';
    if (ie && Number(version) < 8) {
        border = 'border:1px solid transparent;';
    }


    var html = '<div id="fwModal" style="display:none; position:absolute; top:' + modalPositionTop + 'px; left:' + modalPositionLeft + 'px; z-index:1000; width:' + modalWidth + 'px;">';
    html += '<div style="position:relative; display:block; height:25px;">';
    html += '<div style="position:absolute; left:0px; top:0px;"><img src="' + fwImagesPath + 'fw-left-top.gif" /></div>';
    html += '<div style="margin:0px 10px 0px 10px; ' + border + ' background:url(' + fwImagesPath + 'fw-right-middle.gif); text-align:right;"><span id="fwBtnClose" style="cursor:pointer;"><img src="' + fwImagesPath + 'fw-btn-close.gif" alt=""></span></div>';
    html += '<div style="position:absolute; right:0px; top:0px;"><img src="' + fwImagesPath + 'fw-right-top.gif" /></div>';
    html += '</div>';


    html += '<div style="position:relative; display:block; margin-top:-2px;">';
    html += '<div style="position:absolute; left:0px; top:0px; width:7px; height:' + modalHeight + 'px; background-image:url(' + fwImagesPath + 'fw-frame-left.gif);"></div>';
    html += '<div style="margin:-2px 7px 0px 7px; height:' + modalHeight + 'px; background-color:#FFFFFF;">';
    html += '<iframe width="' + Width + '" height="' + Height + '"  frameborder="0" marginwidth="0" marginheight="0" scrolling="NO" src="' + URL + '"></iframe>';
    html += '</div>';
    html += '<div style="position:absolute; right:0px; top:0px; width:7px; height:' + modalHeight + 'px; background-image:url(' + fwImagesPath + 'fw-frame-right.gif);"></div>';
    html += '</div>';

    html += '<div style="position:relative; display:block; height:7px;">';
    html += '<div style="position:absolute; left:0px; top:0px;"><img src="' + fwImagesPath + 'fw-bottom-left-c.gif" style="vertical-align:top;" /></div>';
    html += '<div style="margin:0px 7px 0px 7px; background-image:url(' + fwImagesPath + 'fw-bottom-middle.gif); height:7px;">&nbsp;</div>';
    html += '<div style="position:absolute; right:0px; top:0px;"><img src="' + fwImagesPath + 'fw-bottom-right-c.gif" style="vertical-align:top;" /></div>';
    html += '</div>';

    html += '</div>';
    jQuery('body').append(html);

    jQuery('#fwBtnClose').click(ZennWindowCloseAndRefresh);
    scroll(0, 0);
    document.documentElement.style.overflow = "hidden";
    jQuery('#fwModal').toggle('slow');

}

function ZennWindowClose() {
    jQuery('#fwOverlay').remove();
    jQuery('#fwModal').toggle('slow', function () {
        jQuery('#fwModal').remove();
        document.documentElement.style.overflow = "auto";
    });
}

function ZennWindowCloseAndRedirect(/*String*/URL) {
    ZennWindowClose();
    window.location = URL;
}

function ZennWindowCloseAndRefresh() {
    //ZennWindowClose();
    window.location.reload(true);
}

