﻿/*
Developed by David Oliveira | david.oliveira@zenn.pt
(C) 2009 All Rights Reserved

Sections Index:      
  Global Vars > FIRSTLOAD, CONTENTMASTER, PAGETITLE, NOLOADURL, IDLANGUAGE, IDSTORE, IDCATEGORYTOP, IDCATEGORY, MENU
  Navigation  > LoadUrl, LoadUrlContent, LoadErrorPage
  Sonigate    > LoadDefaults, 
  UI          > 

  
*/

// Global Vars ////////////////////////////////////////
var AJAX = null;
var FIRSTLOAD = true;
var CONTENTMASTER = '#Content-Main';
var PAGETITLE = '#TitlePage';
var NOLOADURL = false;
var IDLANGUAGE = null;
var IDCATEGORYROOT = null;
var IDCATEGORY = null;
var MENU = null;
var SIDETABS = new Array();
var BASKETCLOSING = false;
var SIDETABON = false;
var IDCUSTOMERGROUP = 2;
var ISADMIN = false;

// Navigation /////////////////////////////////////////
jQuery.address.init(function (event) {    
    var query = jQuery.url.attr('query');
    /*query = query.substr(0, query.length - 1);
    var vars = query.split('|');    
    if (vars.length > 2) {
    switch (vars[1]) {
    case '41f79': jQuery.address.value('/9/' + vars[2] + '/'); break;
    }
    }*/
    IDLANGUAGE = query.substr(0, 2);
}).change(function (event) {
    if (jQuery.url.param("_escaped_fragment_") != undefined) return;

    if (event.pathNames[0] == '!') {
        for (var i = 0; i < event.pathNames.length; ++i) {
            event.pathNames[i] = event.pathNames[i + 1];
        }
    }

    if (FIRSTLOAD) {
        UI.Start();
    }

    if (NOLOADURL == false)
        LoadUrl(event);
    else
        NOLOADURL = false;

    if (FIRSTLOAD) {
        FIRSTLOAD = false;
    }
});

function LoadUrl(url) {    
    Sonigate.LoadDefaults(url);

    if (url.pathNames.length == 0) {
        window.location = '#!/1/Home/';
        return;
    }
    var section = url.pathNames[0].toLowerCase();

    if (section == '1' || section == 'home') {   //Home
        LoadUrlContent('frontoffice/Home.aspx', { IdLanguage: IDLANGUAGE }, 'POST', true, true, null);
        //jQuery('.Menu-Main-SubOptions').hide();
        //MENU.Active(null, null);
        UI.NewsLoad();
    }
    if (section == '2') {   //Category
        var order = jQuery.address.parameter('OrderBy'); 
        if (order == undefined) order = '';
        var brand = jQuery.address.parameter('IdBrand');
        if (brand == undefined) brand = '';        
        var price = jQuery.address.parameter('PriceFilter');
        if (price == undefined) price = '';
        var page = jQuery.address.parameter('IdPage');
        if (page == undefined) page = '';
        var isstar = jQuery.address.parameter('IsStar');
        if (isstar == undefined) isstar = '';
        var isnew = jQuery.address.parameter('IsNew');
        if (isnew == undefined) isnew = '';
        var IsBestseller = jQuery.address.parameter('IsBestseller');
        if (IsBestseller == undefined) IsBestseller = '';
        var IsOutlet = jQuery.address.parameter('IsOutlet');
        if (IsOutlet == undefined) IsOutlet = '';

        LoadUrlContent('frontoffice/Category.aspx?IdCustomerGroup=' + IDCUSTOMERGROUP, { IdLanguage: IDLANGUAGE, IdCategory: url.pathNames[1], OrderBy: order, IdBrand: brand, PriceFilter: price, IdPage: page, IsNew: isnew, IsStar: isstar, IsBestseller: IsBestseller, IsOutlet: IsOutlet }, 'POST', true, true, null);
    }
    if (section == '3') {   //Product
        LoadUrlContent('frontoffice/Product.aspx', { IdLanguage: IDLANGUAGE, IdProduct: url.pathNames[1] }, 'POST', true, true, null);
    }
    if (section != '2' && section != '3' && section != '4') {
        $.cookie('SonigateProductSelected', null);
    }
    if (section == '4') {   //Search        
        var order = jQuery.address.parameter('OrderBy'); 
        if (order == undefined) order = '';
        var brand = jQuery.address.parameter('IdBrand');
        if (brand == undefined) brand = '';
        var idcategory = jQuery.address.parameter('IdCategory');
        if (idcategory == undefined) idcategory = '';
        var price = jQuery.address.parameter('PriceFilter');
        if (price == undefined) price = '';
        var page = jQuery.address.parameter('IdPage');
        if (page == undefined) page = '';
        var isstar = jQuery.address.parameter('IsStar');
        if (isstar == undefined) isstar = '';
        var isnew = jQuery.address.parameter('IsNew');
        if (isnew == undefined) isnew = '';

        LoadUrlContent('frontoffice/Search.aspx', { IdLanguage: IDLANGUAGE, Value: url.pathNames[1], OrderBy: order, IdBrand: brand, PriceFilter: price, IdCategory: idcategory, IdPage: page, IsNew: isnew, IsStar: isstar }, 'POST', true, true, function () {
            jQuery('#SearchMenu').empty();
            jQuery('#SearchSideOptions').appendTo('#SearchMenu');
            jQuery('#SearchMenu').show();

            var items = jQuery('.CategoryMenu-Item-Selected');
            for (var i = 0; i != items.length; ++i) {
                var item = items[i];
                if (jQuery(item).attr('id') != null && jQuery(item).attr('id') != undefined) {
                    while (jQuery(item).attr('class') != 'CategoryMenu') {
                        item = jQuery(item).parent();
                        if (jQuery(item).hasClass('CategoryMenu-Section-Sub')) {
                            jQuery(item).show();
                        }
                    }
                }

            }
        });
    }
    if (section == '5') {   //Basket Shopping        
        LoadUrlContent('frontoffice/Basket-Step1.aspx', { IdLanguage: IDLANGUAGE }, 'POST', true, true, null);
    }
    if (section == '6') {   //Product Compare
        var p1 = null;
        if (url.pathNames[2] != undefined) p1 = url.pathNames[2];
        var p2 = null;
        if (url.pathNames[3] != undefined) p2 = url.pathNames[3];
        var p3 = null;
        if (url.pathNames[4] != undefined) p3 = url.pathNames[4];

        LoadUrlContent('frontoffice/ProductCompare.aspx', { IdLanguage: IDLANGUAGE, IdProduct1: p1, IdProduct2: p2, IdProduct3: p3 }, 'POST', true, true, null);        
    }
    if (section == '7') {   //Register
        LoadUrlContent('frontoffice/Register.aspx', { IdLanguage: IDLANGUAGE }, 'POST', true, true, null);
    }
    
    if (section == '9') {   //Content
        LoadUrlContent('frontoffice/Content.aspx', { IdLanguage: IDLANGUAGE, IdContent: url.pathNames[1] }, 'POST', true, true, null);        
    }
    if (section == '10') {   //Customer        
        var FirstLogin = $.address.parameter('FirstLogin') == undefined ? false : $.address.parameter('FirstLogin');        
        LoadUrlContent('frontoffice/Customer.aspx', { IdLanguage: IDLANGUAGE, IdSection: url.pathNames[1], FirstLogin: FirstLogin }, 'POST', true, true, null);
    }
    if (section == '11') {   //Contact
        LoadUrlContent('frontoffice/Contact.aspx', { IdLanguage: IDLANGUAGE, IdContact: url.pathNames[1] }, 'POST', true, true, null);
    }
    if (section == '12') {   //FAQs
        var IdFaq = url.pathNames[2] != undefined ? url.pathNames[2] : '';
        LoadUrlContent('frontoffice/FAQs.aspx', { IdLanguage: IDLANGUAGE, IdFaq: IdFaq }, 'POST', true, true, null);
    }
    if (section == '20') {
        var IdPage = $.address.parameter('IdPage') == undefined ? '1' : $.address.parameter('IdPage');        
        LoadUrlContent('frontoffice/backoffice/CustomerSearch.aspx?IdPage=' + IdPage + '&q=' + url.pathNames[1], {}, 'POST', true, true, null);        
    }
}

function LoadUrlContent(URL, Vars, Method, PreLoading, ScrollTop, onLoaded, Attempt) {    
    if (Attempt == null || Attempt == undefined) Attempt = 1;
    /*jQuery.ajax({
        url: 'frontoffice/Loading.htm',
        type: 'GET',
        cache: true,
        dataType: 'html',
        success: function(data, textStatus) {*/
            
            if (PreLoading) {
                jQuery(CONTENTMASTER).html('<div class="Loading"><img src="images/default/loading1.gif" alt="" class="Icone" /></div>');
            }

            if (AJAX != null) AJAX.abort();
            AJAX = jQuery.ajax({
                url: URL,
                type: Method,
                data: Vars,
                cache: true,
                dataType: 'html',
                success: function(data, textStatus) {
                    AJAX = null;
                    jQuery(CONTENTMASTER).html(data).show(/*'slide', { direction: 'up' }, 200*/);
                    var title = jQuery(PAGETITLE);
                    if (jQuery(title).html() != null && jQuery(title).html().length > 0) {
                        jQuery.address.title(jQuery(title).html());
                    }
                    if (onLoaded != undefined && onLoaded != null) onLoaded();
                    if (ScrollTop) scroll(0, 0);
                    if (NOLOADURL == true) NOLOADURL = false;

                    var url = jQuery.url.attr('anchor');
                    if (url == null || url == undefined) url = '!/1/Home/';
                    _gaq.push(['_trackPageview', url]);                    
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    AJAX = null;
                    if (Attempt < 4)
                        window.setTimeout(function() { LoadUrlContent(URL, Vars, Method, PreLoading, ScrollTop, onLoaded, Number(Attempt) + 1); }, 1000);
                    else {
                        LoadErrorPage('Infelizmente ocorreu um erro! Lamentamos o incómodo. Dentro de alguns segundos (<span id="SecondsToRefresh">20</span>) esta página será reiniciada.<br/>Se o erro persistir, por favor, contacte-nos através do e-mail <strong>website@sonigate.com</strong> e se possível descreva-nos os últimos passos efectuados por si na navegação do nosso website para que possamos tentar identificar e corrigir o problema.<br/>Desde já agradecemos imenso a sua colaboração. :)',
                        function() { jQuery('#SecondsToRefresh').countdown({ seconds: 20, callback: 'ReloadWindow();' }); });
                    }
                }
            });
        
        /*},
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            LoadErrorPage(textStatus + ' ' + errorThrown);
        }
    });*/
}

function ReloadWindow() { window.location.reload(true); }

function LoadErrorPage(Description, Callback) {
    jQuery.ajax({
        url: 'frontoffice/Error.htm', type: 'GET', cache: true, dataType: 'html',
        success: function(data, textStatus) {
            jQuery(CONTENTMASTER).html(data);
            jQuery('#ErrorPage-Content-Status').html(Description);
            if (Callback != null && Callback != undefined) Callback();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { }
    });
}

// SONIGATE /////////////////////////////////////////
var Sonigate = {
    LoadDefaults: function (Url) {
        IDCATEGORYROOT = null;
        IDCATEGORY = null;
        var bg = null;

        UI.SideTabClose();

        //Search
        if (Url.pathNames[0] != '4') {
            jQuery('#SearchMenu').hide();
            jQuery('#txbSearch').val('Pesquisar...');
        }

        if (Url.pathNames[0] != 'Home' && Url.pathNames[0] != '1')
            jQuery('#NewsSidebar').hide();

        //Categories & Products                            
        if (Url.pathNames[0] == '2' || Url.pathNames[0] == '3') {
            jQuery.ajax({
                data: 'action=LoadDefaultVars&Section=' + Url.pathNames[0] + '&Id=' + Url.pathNames[1], url: 'Sonigate.ashx', type: 'POST', cache: false, async: true, dataType: 'json',
                success: function (data, textStatus) {
                    IDCATEGORYROOT = data.IdCategoryRoot;
                    IDCATEGORY = data.IdCategory;
                    IDCUSTOMERGROUP = data.IdCustomerGroup;
                    bg = data.Background;

                    UI.LoadBackground(bg);

                    UI.MenuMainCategorySelected(IDCATEGORYROOT);

                    if (FIRSTLOAD || jQuery('#MenuCurrentIdCategoryRoot').html() != IDCATEGORYROOT)
                        UI.MenuCategoriesLoad(IDCATEGORY, IDLANGUAGE);

                    jQuery('.CategoryMenu-Item-Selected').removeClass('CategoryMenu-Item-Selected');
                    jQuery('#CategoryMenu-Item-' + IDCATEGORY).addClass('CategoryMenu-Item-Selected');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { LoadErrorPage(textStatus + ' ' + errorThrown); }
            });
        }
        else {
            UI.MenuMainCategorySelected(null);
            UI.MenuCategoriesHide();
            UI.LoadBackground(bg);
        }
    },
    Search: function (value) {
        //jQuery('#txbSearch').val('');        
        window.location = '#!/4/' + value + '/';
    },
    BasketLoad: function () {
        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', dataType: 'html', data: 'action=BasketLoad&IdLanguage=' + IDLANGUAGE,
            success: function (data, textStatus) {
                jQuery('#Basket-Middle').html(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    BasketOpen: function () {
        BASKETCLOSING = false;
        jQuery('#Basket-Data').show();
    },
    BasketClose: function () {
        BASKETCLOSING = true;
        window.setTimeout(function () {
            if (BASKETCLOSING)
                jQuery('#Basket-Data').hide();
        }, 100);
    },
    BasketAdd: function (IdProduct, Quantity) {

        if (isNaN(Quantity) || Number(Quantity) < 1) {
            Utilities.PopUp('<img src="images/default/icon-error.png" alt="" /> Quantidade Inválida!', null);
            return;
        }

        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', dataType: 'json', data: 'action=BasketProductAdd&IdProduct=' + IdProduct + '&Quantity=' + Quantity,
            success: function (data, textStatus) {
                if (data.error) {
                    Utilities.PopUp(data.status, null);
                }
                else {
                    Sonigate.BasketLoad();
                    Utilities.PopUp('<img src="images/default/icon-true.gif" alt="" /> Produto Adicionado ao seu Carrinho de Compras!', 1500);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    Compare: function () {
        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', data: 'action=CompareProductUrl&IdLanguage=' + IDLANGUAGE, dataType: 'json',
            success: function (data, textStatus) {
                if (!data.error)
                    window.location = '#' + data.url;
                else
                    Utilities.PopUp('<img src="images/default/icon-error.png" alt="" /> Não tem produtos suficientes para comparar!', null);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    CompareLoad: function () {
        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', data: 'action=CompareLoad&IdLanguage=' + IDLANGUAGE, dataType: 'html',
            success: function (data, textStatus) {
                jQuery('#Tab-Compare-Products').html(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    CompareAdd: function (IdProduct, Name) {
        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', data: 'action=CompareProductAdd&IdProduct=' + IdProduct + '&Name=' + Name, dataType: 'json',
            success: function (data, textStatus) {
                if (data.error) {
                    Utilities.PopUp('<img src="images/default/icon-error.png" alt="" /> Só pode comparar até 3 Produtos!', null);
                }
                else {
                    Sonigate.CompareLoad();
                    Utilities.PopUp('<img src="images/default/icon-true.gif" alt="" /> Produto Adicionado ao Comparador!', 1500);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    CompareRemove: function (IdProduct) {
        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', data: 'action=CompareProductRemove&IdProduct=' + IdProduct, dataType: 'json',
            success: function (data, textStatus) {
                Sonigate.CompareLoad();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    NewsletterSubscribe: function () {
        var Name = jQuery.trim(jQuery('#NewsletterName').val());
        var Email = jQuery.trim(jQuery('#NewsletterEmail').val());

        if (Name.length == 0) {
            jQuery('#NewsletterName').css('border', '1px solid red');
            jQuery('#NewsletterName').focus();
            return;
        }
        jQuery('#NewsletterName').css('border', '1px solid black');
        if (Email.length == 0 || !Utilities.isEmail(Email)) {
            jQuery('#NewsletterEmail').css('border', '1px solid red');
            jQuery('#NewsletterEmail').focus();
            return;
        }
        jQuery('#NewsletterEmail').css('border', '1px solid black');

        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', dataType: 'json', async: true, data: 'action=NewsletterSubscribe&Name=' + Name + '&Email=' + Email,
            success: function (data, textStatus) {
                jQuery('#NewsletterStatus').html('Ok!');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    Login: function () {
        var email = jQuery.trim(jQuery('#LoginEmail').val());
        var password = jQuery.trim(jQuery('#LoginPassword').val()).toLowerCase();
        jQuery('#LoginPassword').val('');

        if (isNaN(email) || email.length == 0) {
            if (email.length == 0 || !Utilities.isEmail(email)) {
                jQuery('#LoginEmail').css('border', '1px solid red');
                jQuery('#LoginEmail').focus();
                window.setTimeout(function () { jQuery('#LoginEmail').css('border', '1px solid black'); }, 3000)
                return;
            }
        }


        if (password.length == 0) {
            jQuery('#LoginPassword').css('border', '1px solid red');
            jQuery('#LoginPassword').focus();
            window.setTimeout(function () { jQuery('#LoginPassword').css('border', '1px solid black'); }, 3000)
            return;
        }

        jQuery('#LoginEmail').css('border', '1px solid black');
        jQuery('#LoginPassword').css('border', '1px solid black');
        jQuery('#LoginStatus').html('<img src="images/default/loading2.gif" alt="" class="Icone" />');
        jQuery('.Side-Tab-Btn-Login').unbind('click', Sonigate.Login);
        password = jQuery.md5(password);

        var remember = jQuery('#LoginRemember:checked').val();
        if (remember == undefined)
            remember = false;
        else
            remember = remember.replace('on', 'true');

        jQuery.ajax({
            url: 'Security.ashx', type: 'POST', dataType: 'json', data: 'action=Login&Idlanguage=' + IDLANGUAGE + '&email=' + email + '&password=' + password + '&remember=' + remember,
            success: function (data, textStatus) {
                if (data.error)
                    Utilities.PopUp(data.status, null);
                else {
                    if (data.FirstLogin) {
                        Sonigate.BasketLoad();
                        UI.UpdateCustomer();
                        window.location = '#!/10/3/Alterar-Password/?FirstLogin=true';
                    }
                    else
                        window.location.reload(true);
                }
                jQuery('#LoginStatus').html('');
                jQuery('.Side-Tab-Btn-Login').click(Sonigate.Login);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { jQuery('.Side-Tab-Btn-Login').click(Sonigate.Login); jQuery('#LoginStatus').html(''); }
        });
    },
    Logout: function (admin) {
        jQuery.ajax({
            url: 'Security.ashx', type: 'POST', data: 'action=Logout&admin=' + admin, dataType: 'json',
            success: function (data, textStatus) {
                window.location = '#!/1/Home/';
                window.location.reload(true);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    NoticeLoad: function (IdNotice) {
        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', data: 'action=NoticeLoad&IdNotice=' + IdNotice + '&IdLanguage=' + IDLANGUAGE, dataType: 'html',
            success: function (data, textStatus) {
                Utilities.PopUp(data, null);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    RecoverPassword: function () {
        var email = jQuery.trim(jQuery('#LoginEmail').val());
        if (isNaN(email)) {
            if (email.length == 0 || !Utilities.isEmail(email)) {
                jQuery('#LoginEmail').css('border', '1px solid red');
                jQuery('#LoginEmail').focus();
                window.setTimeout(function () { jQuery('#LoginEmail').css('border', '1px solid black'); }, 3000)
                return;
            }
        }
        else {
            if (email.length < 4) {
                jQuery('#LoginEmail').css('border', '1px solid red');
                jQuery('#LoginEmail').focus();
                window.setTimeout(function () { jQuery('#LoginEmail').css('border', '1px solid black'); }, 3000)
                return;
            }
        }

        jQuery('#LoginEmail').css('border', '1px solid black');
        jQuery('#LoginStatus').html('<img src="images/default/loading2.gif" alt="" class="Icone" />');
        jQuery('.Side-Tab-Btn-Login').unbind('click', Sonigate.Login);
        jQuery('#Recover-Passsword-Btn').unbind('click', Sonigate.RecoverPassword);
        jQuery.ajax({
            url: 'Sonigate.ashx', type: 'POST', data: 'action=RecoverPassword&Email=' + email + '&IdLanguage=' + IDLANGUAGE, dataType: 'html',
            success: function (data, textStatus) {
                Utilities.PopUp(data, null);
                jQuery('#LoginStatus').html('');
                jQuery('.Side-Tab-Btn-Login').click(Sonigate.Login);
                jQuery('#Recover-Passsword-Btn').click(Sonigate.RecoverPassword);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { jQuery('#LoginStatus').html(''); jQuery('.Side-Tab-Btn-Login').click(Sonigate.Login); jQuery('#Recover-Passsword-Btn').click(Sonigate.RecoverPassword); }
        });
    },
    PasswordRecoverFirstTime: function () {
        jQuery(document).trigger('close.facebox');
        window.setTimeout(function () { Sonigate.RecoverPassword(); }, 1000);
    },
    ShareToFriend: function (IdProduct) {
        Utilities.PopUp('<iframe src="frontoffice/ProductShareFriend.aspx?IdLanguage=' + IDLANGUAGE + '&IdProduct=' + IdProduct + '" frameborder="0" scrolling="no" width="400px" height="100px" ></iframe>', null);
    },
    SessionEnd: function () {
        jQuery.address.value('/Home/');
        UI.UpdateCustomer();
        Utilities.PopUp('A sua Sessão expirou! Terá de voltar a efectuar o seu Login!', null);
    },
    AdminAsCustomer: function (IdCustomer) {
        jQuery.ajax({
            url: 'Backoffice.ashx', type: 'POST', data: 'action=AdminAsCustomer&IdCustomer=' + IdCustomer, dataType: 'json',
            success: function (data, textStatus) {
                if (data.error)
                    Utilities.PopUp(data.status, null);
                else {
                    window.location = '#!/10/0/Estatisticas/'; window.location.reload(true);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    }
}

// UI ///////////////////////////////////////////////
var UI = {
    Start: function () {
        if (jQuery.browser.msie && jQuery.browser.version == '7.0') {
            jQuery('#Mapsite-Container').css('margin-top', '0px');
            jQuery('#Page-Main').css('margin-bottom', '0px');
        }
        UI.MenuMainStart();
        UI.MenuMainCategorySelected(null);

        Sonigate.BasketLoad();
        Sonigate.CompareLoad();
        UI.UpdateCustomer();
        UI.SideTabLoad();

        if (jQuery.browser.opera) {
            Utilities.PopUp('<img src="images/default/icon-error.png" alt="" /> Lamentamos imenso, mas para poder usufruir do nosso website correctamente terá de utilizar outro browser (Firefox, Internet Explorer, Chrome ou Safari) que não o Opera.<br/>Contamos resolver este problema com o Opera assim que possível.', null);
        }
        if (jQuery.browser.msie && Number(BrowserDetect.version) < 7) {
            Utilities.PopUp('<img src="images/default/icon-error.png" alt="" /> Lamentamos imenso, mas para poder usufruir do nosso website correctamente terá de actualizar a versão do seu Internet Explorer para uma mais recente. Poderá fazê-lo através deste link: <a href="http://www.microsoft.com/portugal/windows/internet-explorer/default.aspx">www.microsoft.com/portugal/windows/internet-explorer/default.aspx</a>', null);
        }

        jQuery.jCookie('cookietest', 'value');
        if (jQuery.jCookie('cookietest') != 'value') {
            Utilities.PopUp('<img src="images/default/icon-error.png" alt="" /> Lamentamos imenso, mas para poder usufruir do nosso website correctamente terá de permitir a utilização de Cookies no seu browser que de momento se encontra inibida.', null);
        }
        jQuery.jCookie('cookietest', null);

        UI.SearchValue = jQuery('#txbSearch').val();
        jQuery('#txbSearch').blur(function () {
            if (jQuery('#txbSearch').val().length == 0) jQuery('#txbSearch').val(UI.SearchValue);
        });
        jQuery('#txbSearch').focus(function () { jQuery('#txbSearch').val(''); });
    },
    MenuMainStart: function () {
        var options = jQuery('.Menu-Main-Option div');
        for (var i = 0; i != options.length; ++i) {
            jQuery(options[i]).css('top', Math.ceil((Number(44) - Number(jQuery(options[i]).height())) / 2) + 'px')
        }
        options = jQuery('.Menu-Main-Option');
        for (var i = 0; i != options.length; ++i) {
            jQuery(options[i]).mouseover(function () {
                jQuery(this).addClass('Menu-Main-Option-Over-' + jQuery(this).attr('rel'));
            });
            jQuery(options[i]).mouseout(function () {
                jQuery(this).removeClass('Menu-Main-Option-Over-' + jQuery(this).attr('rel'));
            });
        }
    },
    MenuMainCategorySelected: function (IdCategory) {
        jQuery('.Menu-Main-Option').attr('class', 'Menu-Main-Option');
        if (IdCategory != null) {
            jQuery('#Menu-Main-Option-' + IdCategory).addClass('Menu-Main-Option-Selected-' + jQuery('#Menu-Main-Option-' + IdCategory).attr('rel'));
        }
    },
    UpdateCustomer: function () {
        jQuery.ajax({
            url: 'Security.ashx', type: 'POST', dataType: 'json', data: 'action=GetUserStatus',
            success: function (data, textStatus) {
                if (data.IsAuthenticated) {
                    if (data.IsAdmin) {
                        jQuery('#Tab-Account-On').hide();
                        jQuery('#Tab-Account-Off').show();
                        ISADMIN = true;
                    }
                    else {
                        jQuery('#Tab-Account-On').show();
                        jQuery('#Tab-Account-Off').hide();
                        ISADMIN = false;
                    }

                    var bg = jQuery('#SideBtn-Account').css('background-image');
                    jQuery('#SideBtn-Account').css('background-image', bg.replace(/login/i, 'clients'));
                    if (data.AdminAsClient) {
                        jQuery('#ctl00_AdminAsClient').show();
                    }
                    else {
                        jQuery('#ctl00_AdminAsClient').hide();
                    }
                    if (data.IsAdmin) {
                        //$('#Basket').hide();
                        //$('#Tab-Account-On').hide();
                        $('#Bartool').show();
                    }
                    else {
                        $('#Bartool').hide();
                        //$('#Basket').show();
                        //$('#Tab-Account-On').show();
                    }
                }
                else {
                    jQuery('#Tab-Account-Off').show();
                    jQuery('#Tab-Account-On').hide();
                    var bg = jQuery('#SideBtn-Account').css('background-image');
                    jQuery('#SideBtn-Account').css('background-image', bg.replace(/clients/i, 'login'));
                }
                jQuery('#Header-Welcome').html(data.WelcomeMessage);

                if (data.IsAdmin)
                    jQuery('#SideBtn-Backoffice').show();
                else
                    jQuery('#SideBtn-Backoffice').hide();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    NewsLoad: function () {
        jQuery.ajax({
            url: 'frontoffice/Notices.aspx', type: 'POST', dataType: 'html', data: 'IdLanguage=' + IDLANGUAGE,
            success: function (data, textStatus) {
                jQuery("#NewsSidebar").html(data);
                jQuery("#NewsSidebar").show();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    },
    SideTabLoad: function () {
        SIDETABS[0] = new UI.SideTab('SideBtn-Account', 'Tab-Account');
        SIDETABS[1] = new UI.SideTab('SideBtn-Compare', 'Tab-Compare');
        SIDETABS[2] = new UI.SideTab('SideBtn-Newsletter', 'Tab-Newsletter');
        SIDETABS[3] = new UI.SideTab('SideBtn-Backoffice', 'Tab-Backoffice');
    },
    SideTab: function (BtnId, TabId) {
        this.Btn = jQuery('#' + BtnId);
        this.Tab = jQuery('#' + TabId); ;
        this.running = false;
        this.Open = false;

        var Me = this;
        jQuery(Me.Btn).mousedown(function () { Me.Show(); Me.BtnOver(); });
        jQuery(Me.Btn).mouseover(function () { Me.BtnOver(); });
        jQuery(Me.Btn).mouseout(function () { Me.BtnOut(); });

        this.BtnOver = function () {
            if (!Me.Open) {
                var bg = jQuery(Me.Btn).css('background-image');
                jQuery(Me.Btn).css('background-image', bg.replace(/-off/i, '-on'));
            }
        }
        this.BtnOut = function () {
            if (!Me.Open) {
                var bg = jQuery(Me.Btn).css('background-image');
                jQuery(Me.Btn).css('background-image', bg.replace(/-on/i, '-off'));
            }
        }
        this.Show = function () {
            UI.SideTabClose();
            window.setTimeout(function () {
                Me.Open = true;
                SIDETABON = true;
                Me.running = false;
                jQuery('#TabsNotActive').hide();
                jQuery(Me.Tab).show();
            }, 0);
        }
        this.Hide = function () {
            Me.running = true;
            SIDETABON = false;
            window.setTimeout(function () {
                Me.Open = false;
                if (Me.running) {
                    if (!SIDETABON == true)
                        jQuery('#TabsNotActive').show();
                    jQuery(Me.Tab).hide();

                    Me.BtnOut();
                }
            }, 0);
        }
    },
    SideTabClose: function () {
        for (var i = 0; i != SIDETABS.length; ++i) {
            if (SIDETABS[i].Open)
                SIDETABS[i].Hide();
        }
    },
    MenuCategoryClicked: function (IdCategory) {
        jQuery('.Section-Sub-Selected').removeClass('Section-Sub-Selected');
        jQuery('.CategoryMenu-Item-Selected').removeClass('CategoryMenu-Item-Selected');
        jQuery('#CategoryMenu-Item-' + IdCategory).addClass('CategoryMenu-Item-Selected');

        var item = jQuery('#CategoryMenu-Item-' + IdCategory);
        if (jQuery(item).attr('id') != null && jQuery(item).attr('id') != undefined) {
            while (jQuery(item).attr('class') != 'CategoryMenu') {
                item = jQuery(item).parent();
                if (jQuery(item).hasClass('CategoryMenu-Section-Sub')) {
                    jQuery(item).addClass('Section-Sub-Selected');
                    var id = jQuery(item).attr('id');
                    id = id.substr(id.lastIndexOf('-') + 1)
                    jQuery('#CategoryMenu-Item-' + id).addClass('Section-Sub-Selected');
                    break;
                }
            }
        }
    },
    MenuCategoriesToggle: function (IdCategory) {
        jQuery('.Section-Sub-Selected').removeClass('Section-Sub-Selected');
        jQuery('#CategoryMenu-Section-Sub-' + IdCategory).slideToggle('slow');
        jQuery('#CategoryMenu-Section-Sub-' + IdCategory).addClass('Section-Sub-Selected');
    },
    MenuCategoriesOpen: function (IdCategory) {
        jQuery('.Section-Sub-Selected').removeClass('Section-Sub-Selected');
        jQuery('#CategoryMenu-Section-Sub-' + IdCategory).addClass('Section-Sub-Selected');
        jQuery('#CategoryMenu-Section-Sub-' + IdCategory).slideDown('slow');
        var item = jQuery('#CategoryMenu-Item-' + IdCategory);
        while (jQuery(item).attr('class') != 'CategoryMenu') {
            item = jQuery(item).parent();
            if (jQuery(item).hasClass('CategoryMenu-Section-Sub') && jQuery(item).css('display') == 'none')
                jQuery(item).slideToggle('slow');
            if (jQuery(item).hasClass('CategoryMenu-Section-Sub')) {
                jQuery(item).addClass('Section-Sub-Selected');
                var id = jQuery(item).attr('id');
                id = id.substr(id.lastIndexOf('-') + 1)
                jQuery('#CategoryMenu-Item-' + id).addClass('Section-Sub-Selected');
            }
            break;
        }
    },
    MenuCategoriesCloseAll: function () {
        jQuery('.Section-Sub-Selected').removeClass('Section-Sub-Selected');
        jQuery('.CategoryMenu-Item-Selected').removeClass('CategoryMenu-Item-Selected');
    },
    MenuCategoriesLoad: function (IdCategory, IdLanguage) {
        jQuery('#CategoryMenu').html('<div style="margin-top:50px; margin-left:75px;"><img src="images/default/loading1.gif" alt="" /></div>');
        jQuery.ajax({
            url: 'frontoffice/CategoryMenu.aspx',
            type: 'POST',
            data: 'IdLanguage=' + IdLanguage + '&IdCategory=' + IdCategory,
            dataType: 'html',
            success: function (data, textStatus) {
                jQuery('#CategoryMenu').hide();
                jQuery('#CategoryMenu').html(data);
                UI.MenuCategoryClicked(IdCategory);
                var first = true;
                var item = jQuery('#CategoryMenu-Item-' + IdCategory);
                if (jQuery(item).attr('id') != null && jQuery(item).attr('id') != undefined) {
                    while (jQuery(item).attr('class') != 'CategoryMenu') {
                        item = jQuery(item).parent();
                        if (jQuery(item).hasClass('CategoryMenu-Section-Sub')) {
                            if (first) {
                                jQuery(item).addClass('Section-Sub-Selected');
                                first = false;
                            }
                            jQuery(item).show();
                            //var title = jQuery('#CategoryMenu-Item-' + jQuery(item).attr('id').substr(jQuery(item).attr('id').lastIndexOf('-') + 1));

                            /*if (jQuery(title).hasClass('CategoryMenu-Item-Parent'))
                            jQuery(title).addClass('CategoryMenu-Item-Selected');*/
                        }
                    }
                }

                jQuery('#CategoryMenu').slideToggle('slow');
                jQuery('#CategoryMenu').show();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { LoadErrorPage(textStatus + ' ' + errorThrown); }
        });
    },
    MenuCategoriesHide: function () {
        jQuery('#CategoryMenu').empty();
    },
    LoadBackground: function (bg) {
        if (bg == null)
            jQuery('body').css('background-image', 'none');
        else
            if (jQuery('body').css('background-image') != bg)
                jQuery('body').css('background-image', 'url(' + bg + ')');
    },
    RegisterSuccess: function (Message, Email) {
        jQuery.address.value('/1/Home/');
        scroll(0, 0);
        jQuery('#LoginEmail').val(Email);
        SIDETABS[0].Show();
        Utilities.PopUp(Message, null);
    }
}

// Utilities ////////////////////////////////////////
var Utilities = {
    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);
    },
    PopUp: function (Message, TimeOut) {
        jQuery.facebox('<div class="PopUpMsg">' + Message + '</div>');
        if (TimeOut != null)
            window.setTimeout(function () { jQuery(document).trigger('close.facebox'); }, TimeOut);
    },
    PopUpUrl: function (url) {
        jQuery.facebox('<iframe src="' + url + '" width="650" height="500" scrolling="auto" frameborder="0"></iframe>');
    },
    PopUpQuestion: function (Message, callback) {
        jQuery.facebox('<div class="PopUpMsg">' + Message + '</div>&nbsp;<span id="PopUpQuestionYes" class="Button2">Sim</span>&nbsp;&nbsp;<span id="PopUpQuestionNo" class="Button2">Não</span>');
        jQuery('#PopUpQuestionYes').click(function () { jQuery(document).trigger('close.facebox'); window.setTimeout(callback, 800); });
        jQuery('#PopUpQuestionNo').click(function () { jQuery(document).trigger('close.facebox'); });
    }
}