﻿var SiteManagement = {
    currentLanguage: "it",
    currentWineGroupSheet: "",
    currentWineSheet: "",
    currentPage: "",
    changingPage: false,
    map: null,
    marker_map: null,

    //
    //
    //
    //
    //
    init: function () {

        var extraImages = new Array(
                "/images/loader.gif",
                "/images/menu/it_menu_01.jpg",
                "/images/menu/it_menu_02.jpg",
                "/images/menu/it_menu_03.jpg",
                "/images/menu/it_menu_04.jpg",
                "/images/menu/it_menu_05.jpg",
                "/images/menu/it_menu_06.jpg",
                "/images/menu/it_menu-on_01.jpg",
                "/images/menu/it_menu-on_02.jpg",
                "/images/menu/it_menu-on_03.jpg",
                "/images/menu/it_menu-on_04.jpg",
                "/images/menu/it_menu-on_05.jpg",
                "/images/menu/it_menu-on_06.jpg",
                "/images/menu/it_menu-over_01.jpg",
                "/images/menu/it_menu-over_02.jpg",
                "/images/menu/it_menu-over_03.jpg",
                "/images/menu/it_menu-over_04.jpg",
                "/images/menu/it_menu-over_05.jpg",
                "/images/menu/it_menu-over_06.jpg",
                "/images/menu/en_menu_01.jpg",
                "/images/menu/en_menu_02.jpg",
                "/images/menu/en_menu_03.jpg",
                "/images/menu/en_menu_04.jpg",
                "/images/menu/en_menu_05.jpg",
                "/images/menu/en_menu_06.jpg",
                "/images/menu/en_menu-on_01.jpg",
                "/images/menu/en_menu-on_02.jpg",
                "/images/menu/en_menu-on_03.jpg",
                "/images/menu/en_menu-on_04.jpg",
                "/images/menu/en_menu-on_05.jpg",
                "/images/menu/en_menu-on_06.jpg",
                "/images/menu/en_menu-over_01.jpg",
                "/images/menu/en_menu-over_02.jpg",
                "/images/menu/en_menu-over_03.jpg",
                "/images/menu/en_menu-over_04.jpg",
                "/images/menu/en_menu-over_05.jpg",
                "/images/menu/en_menu-over_06.jpg",
                "/images/download.png",
                "/images/zoom.png");

        //
        //
        //
        //
        function start() {
            function makeDynMenuLink(menuClassSelector) {

                var menuObj = $(menuClassSelector);
                if (menuObj.length == 0)
                    menuObj = $(menuClassSelector + "On");

                menuObj.replaceWith("<span id=\"" + menuClassSelector.substring(1) + "\" class=\"" + menuObj.attr("class") + "\">&nbsp;</span>");

                return $("#" + menuClassSelector.substring(1));
            }

            makeDynMenuLink(".menuItemCantina").click(function () {
                SiteManagement.openMenu('menuCantina');
            });

            makeDynMenuLink(".menuItemVini").click(function () {
                SiteManagement.openMenu('menuVini');
            });


            makeDynMenuLink(".menuItemNews").click(function () {
                SiteManagement.openMenu('menuNews');
            });

            makeDynMenuLink(".menuItemContatti").click(function () {
                SiteManagement.openMenu('menuContatti');
            });

            makeDynMenuLink(".menuItemDownload").click(function () {
                SiteManagement.openMenu('menuDownload');
            });

            makeDynMenuLink(".menuItemAltavigna").click(function () {
                SiteManagement.openMenu('menuAltavigna');
            });

            if ($("#menuCantina").length == 0)
                $("div[id$=contentArea]").append("<div id=\"menuCantina\" class=\"contentAreaPage\"></div>");
            if ($("#menuVini").length == 0)
                $("div[id$=contentArea]").append("<div id=\"menuVini\" class=\"contentAreaPage\"></div>");
            if ($("#menuNews").length == 0)
                $("div[id$=contentArea]").append("<div id=\"menuNews\" class=\"contentAreaPage\"></div>");
            if ($("#menuContatti").length == 0)
                $("div[id$=contentArea]").append("<div id=\"menuContatti\" class=\"contentAreaPage\"></div>");
            if ($("#menuDownload").length == 0)
                $("div[id$=contentArea]").append("<div id=\"menuDownload\" class=\"contentAreaPage\"></div>");
            if ($("#menuAltavigna").length == 0)
                $("div[id$=contentArea]").append("<div id=\"menuAltavigna\" class=\"contentAreaPage\"></div>");

            animatedcollapse.addDiv('menuCantina', SiteManagement.currentPage == "menuCantina" ? "" : "hide=1," + "fade=0,speed=400,group=menu");
            animatedcollapse.addDiv('menuVini', SiteManagement.currentPage == "menuVini" ? "" : "hide=1," + "fade=0,speed=400,group=menu");
            animatedcollapse.addDiv('menuNews', SiteManagement.currentPage == "menuNews" ? "" : "hide=1," + "fade=0,speed=400,group=menu");
            animatedcollapse.addDiv('menuContatti', SiteManagement.currentPage == "menuContatti" ? "" : "hide=1," + "fade=0,speed=400,group=menu");
            animatedcollapse.addDiv('menuDownload', SiteManagement.currentPage == "menuDownload" ? "" : "hide=1," + "fade=0,speed=400,group=menu");
            animatedcollapse.addDiv('menuAltavigna', SiteManagement.currentPage == "menuAltavigna" ? "" : "hide=1," + "fade=0,speed=400,group=menu");
            animatedcollapse.init();

            if ($(".newsReportContentScrollable").children().size() / 2.0 > 2.0) {
                $jScroller.add(".newsReportArea", ".newsReportContentScrollable", "up", 1);
                //$jScroller.start();
            }

            $("div[id$=sitemap] a").each(function (idx, item) {
                var obj = $(item);
                var url = obj.attr('href').toLowerCase();
                if (url.indexOf('.aspx') > 0) {
                    var menu = "";
                    if (url.indexOf('cantina.aspx') > 0)
                        menu = "menuCantina";
                    else if (url.indexOf('vini.aspx') > 0)
                        menu = 'menuVini';
                    else if (url.indexOf('newsindex.aspx') > 0)
                        menu = 'menuNews';
                    else if (url.indexOf('contatti.aspx') > 0)
                        menu = 'menuContatti';
                    else if (url.indexOf('download.aspx') > 0)
                        menu = 'menuDownload';
                    else if (url.indexOf('altavigna.aspx') > 0)
                        menu = 'menuAltavigna';
                    if (menu != "") {
                        var newObj = $('<div></div>');
                        newObj.html(obj.html()).css('cursor', 'pointer');
                        newObj.insertBefore(obj);
                        obj.remove();
                        newObj.click(function () {
                            SiteManagement.openMenu(menu);
                        });
                    } else {
                        SiteManagement.makeLinkViniDynamic(obj);
                    }
                }
            });

            $("#newsletterRegister a").fancybox({
                'width': 600,
                'height': 300,
                'autoScale': false,
                'transitionIn': 'none',
                'transitionOut': 'none',
                'type': 'iframe',
                'overlayOpacity': 0.9,
                'overlayColor': '#000000',
                'opacity': true,
                'hideOnContentClick': false
            });

            $(".newsReportArea a").each(function (index, item) {
                SiteManagement.createNewsContentViewer($(item));
            });
        }

        //
        //
        //
        //
        //
        function preLoadCatinaPage() {
            function formatTitle(title, currentArray, currentIndex, currentOpts) {
                var html

                html = '<div id="gallery-title">';
                html += '<img src="/scripts/fancybox/fancy_close.png" onclick="$.fancybox.close();"/>';
                if (currentIndex < currentArray.length - 1)
                    html += '<img src="/scripts/fancybox/fancy_nav_right.png" onclick="$.fancybox.next();"/>';
                if (currentIndex > 0)
                    html += '<img src="/scripts/fancybox/fancy_nav_left.png" onclick="$.fancybox.prev();"/>';
                html += (title && title.length ? '<b>' + title + '</b>' : '');
                if (SiteManagement.currentLanguage == "it")
                    html += 'Immagine ' + (currentIndex + 1) + ' di ' + currentArray.length;
                else
                    html += 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length;
                html += '</div>';

                return html;
            }

            if ($("#menuCantina").html() == "") {
                QueryLoader.addFunction(function () {
                    $.ajax({
                        type: "POST",
                        url: "/Cantina.aspx/Get",
                        data: "{'language':'" + SiteManagement.currentLanguage + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data, textStatus) {
                            if (data.d != null) {
                                $("#menuCantina").html(data.d);
                                $("#menuCantina a").fancybox({
                                    'transitionIn': 'elastic',
                                    'transitionOut': 'elastic',
                                    'speedIn': 600,
                                    'speedOut': 200,
                                    'overlayOpacity': 0.9,
                                    'overlayColor': '#000000',
                                    'opacity': true,
                                    'showCloseButton': false,
                                    'titlePosition': 'inside',
                                    'titleFormat': formatTitle
                                });
                            } else
                                $("#menuCantina").html("");
                            $("#menuCantina").css("display", "none");
                            QueryLoader.notifyExtraFuncComplete();
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            QueryLoader.notifyExtraFuncComplete();
                        }
                    });
                });
            } else {
                $("#menuCantina a").fancybox({
                    'transitionIn': 'elastic',
                    'transitionOut': 'elastic',
                    'easingIn': 'easeOutBack',
                    'easingOut': 'easeInBack',
                    'centerOnScroll': true,
                    'overlayOpacity': 0.9,
                    'overlayColor': '#000000',
                    'opacity': true,
                    'showCloseButton': false,
                    'titlePosition': 'inside',
                    'titleFormat': formatTitle
                });
            }
        }

        //
        //
        //
        //
        //
        function preLoadViniPage() {


            if ($("#menuVini div[id$=pageWineList]").length == 0) {
                QueryLoader.addFunction(function () {
                    var parameter = "'language':'" + SiteManagement.currentLanguage + "'";
                    if ($("#menuVini div[id$=pageWineList]").length == 0) {
                        $.ajax({
                            type: "POST",
                            url: "/Vini.aspx/GetList",
                            data: "{" + parameter + "}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data, textStatus) {
                                if ($("#menuVini div[id$=pageWineDetail]").length == 0)
                                    $("#menuVini").append(data.d);
                                else
                                    $("#menuVini div[id$=pageWineDetail]").parent().prepend(data.d);
                                if (SiteManagement.currentPage != "menuVini")
                                    $("#menuVini").css("display", "none");
                                else if (SiteManagement.currentWineSheet != "")
                                    $("#menuVini div[id$=pageWineList]").fadeOut(0);
                                SiteManagement.makeLinkViniPageToDynamic();
                                QueryLoader.notifyExtraFuncComplete();
                            },
                            error: function (XMLHttpRequest, textStatus) {
                                QueryLoader.notifyExtraFuncComplete();
                            }
                        });
                    } else {
                        //SiteManagement.currentPage = "menuVini";
                        QueryLoader.notifyExtraFuncComplete();
                    }
                });
            } else {
                $("#menuVini").css("display", "block");
                SiteManagement.makeLinkViniPageToDynamic();
            }

            //            if ($("#menuVini div[id$=pageWineDetail]").length == 0) {
            QueryLoader.addFunction(function () {
                var parameter = "'language':'" + SiteManagement.currentLanguage + "'";

                parameter += ",'group':''";
                parameter += ",'product':''";

                //                    if ($("#menuVini div[id$=pageWineDetail]").length == 0) {
                $.ajax({
                    type: "POST",
                    url: "/Vini.aspx/GetDetail",
                    data: "{" + parameter + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data, textStatus) {
                        if ($("#menuVini div[id$=pageWineList]").length == 0)
                            $("#menuVini").append(data.d);
                        else {
                            $("#menuVini div[id$=pageWineDetail]").remove();
                            $("#menuVini").append(data.d);
                        }
                        if (SiteManagement.currentPage != "menuVini") {
                            $("#menuVini").css("display", "none");
                            $("#menuVini div[id$=pageWineDetail]").css('display', 'none');
                        }
                        SiteManagement.makeLinkViniPageToDynamic();
                        QueryLoader.notifyExtraFuncComplete();
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        QueryLoader.notifyExtraFuncComplete();
                    }
                });
                //                    } else {
                //                        QueryLoader.notifyExtraFuncComplete();
                //                    }
            });
            //            } else {
            //                $("#menuVini").css("display", "block");
            //                SiteManagement.makeLinkViniPageToDynamic();
            //            }

            if ($("#menuVini div[id$=pageWineDetail]").length > 0) {
                var paths = document.location.pathname.split('/');
                var group = paths[paths.length - 2];
                var product = paths[paths.length - 1].substring(0, paths[paths.length - 1].length - 5);

                QueryLoader.addFunction(function () {
                    SiteManagement.currentWineSheet = '';
                    SiteManagement.currentWineGroupSheet = '';
                    //SiteManagement.showAccordionWineGroup(group);
                    SiteManagement.openSheet(group, product);
                    QueryLoader.notifyExtraFuncComplete();
                });
            }
        }

        //
        //
        //
        //
        //
        function preLoadContattiPage() {
            if ($("#menuContatti div[id$=contactForm]").length == 0) {

                QueryLoader.addFunction(function () {
                    $.ajax({
                        type: "POST",
                        url: "/Contatti.aspx/Get",
                        data: "{'language':'" + SiteManagement.currentLanguage + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data, textStatus) {
                            if (data.d != null) {
                                $("#menuContatti").html(data.d);
                                $("input[id$=btnSendContactEmail]").click(function () {
                                    SiteManagement.sendContactEmail();
                                    return false;
                                });
                            }
                            else
                                $("#menuContatti").html("");
                            if (SiteManagement.currentPage != "menuContatti")
                                $("#menuContatti").css("display", "none");
                            QueryLoader.notifyExtraFuncComplete();
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            QueryLoader.notifyExtraFuncComplete();
                        }
                    });
                });

            } else {

                //SiteManagement.currentPage = "menuContatti";
                //SiteManagement.openMenu("menuContatti");
            }
        }

        //
        //
        //
        //
        //
        function preLoadDownloadPage() {
            if ($("#menuDownload div[id$=pageMainDownload]").length == 0) {
                QueryLoader.addFunction(function () {
                    var parameter = "'language':'" + SiteManagement.currentLanguage + "'";
                    if ($("#menuDownload div[id$=pageMainDownload]").length == 0) {
                        $.ajax({
                            type: "POST",
                            url: "/Download.aspx/GetList",
                            data: "{" + parameter + "}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data, textStatus) {
                                if ($("#menuDownload div[id$=pageDownloadList]").length == 0)
                                    $("#menuDownload").append(data.d);
                                else
                                    $("#menuDownload div[id$=pageDownloadList]").parent().prepend(data.d);
                                if (SiteManagement.currentPage != "menuDownload")
                                    $("#menuDownload").css("display", "none");
                                else if (document.location.href.toUpperCase().indexOf("SHOW=LIST") > 0)
                                    $("#menuDownload div[id$=pageMainDownload]").fadeOut(0);
                                SiteManagement.makeLinkViniPageToDynamic();
                                QueryLoader.notifyExtraFuncComplete();
                            },
                            error: function (XMLHttpRequest, textStatus) {
                                QueryLoader.notifyExtraFuncComplete();
                            }
                        });

                    } else {
                        //SiteManagement.currentPage = "menuDownload";
                        SiteManagement.makeLinkViniPageToDynamic();
                        QueryLoader.notifyExtraFuncComplete();
                    }
                });
            } else {
                SiteManagement.makeLinkViniPageToDynamic();
                $("#menuDownload").css("display", "block");
            }

            if ($("#menuDownload div[id$=pageDownloadList]").length == 0) {
                QueryLoader.addFunction(function () {
                    var parameter = "'language':'" + SiteManagement.currentLanguage + "'";

                    if ($("#menuDownload div[id$=pageWineDetail]").length == 0) {
                        $.ajax({
                            type: "POST",
                            url: "/Download.aspx/GetDetail",
                            data: "{" + parameter + "}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data, textStatus) {
                                if ($("#menuDownload div[id$=pageMainDownload]").length == 0)
                                    $("#menuDownload").append(data.d);
                                else
                                    $("#menuDownload div[id$=pageMainDownload]").parent().append(data.d);
                                if (SiteManagement.currentPage != "menuDownload")
                                    $("#menuDownload").css("display", "none");
                                SiteManagement.makeLinkViniPageToDynamic();
                                QueryLoader.notifyExtraFuncComplete();
                            },
                            error: function (XMLHttpRequest, textStatus) {
                                QueryLoader.notifyExtraFuncComplete();
                            }
                        });
                    } else {
                        //SiteManagement.currentPage = "menuVini";
                        SiteManagement.makeLinkViniPageToDynamic();
                        QueryLoader.notifyExtraFuncComplete();
                    }
                });
            } else {
                SiteManagement.makeLinkViniPageToDynamic();
                $("#menuDownload").css("display", "block");

            }
        }


        //
        //
        //
        //
        //
        function preLoadNews() {


            function loadIndex(year) {
                $("div[id$=newsIndex]").addClass("newsLoading");
                $.ajax({
                    type: "POST",
                    url: "/NewsIndex.aspx/GetIndexContent",
                    data: "{'language':'" + SiteManagement.currentLanguage + "','year':'" + year + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data, textStatus) {
                        if (data.d != null)
                            $("div[id$=newsIndex]").html(data.d);
                        $("div[id$=newsIndex] a").each(function (index, item) {
                            SiteManagement.createNewsContentViewer($(item));
                        });
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                        $("div[id$=newsIndex]").removeClass("newsLoading");
                        if ($("div[id$=newsIndex]").outerHeight() != 0) {
                            $("div[id$=contentArea]").animate({
                                height: Math.max($("#menuNews").outerHeight(), Math.max($(".newsArchiveList").outerHeight(), $(".newsIndex").outerHeight())) + "px"
                            }, 500);
                        }
                    }
                });
            }

            if ($("#menuNews").html() == "") {
                QueryLoader.addFunction(function () {
                    $.ajax({
                        type: "POST",
                        url: "/NewsIndex.aspx/GetArchiveList",
                        data: "{'language':'" + SiteManagement.currentLanguage + "','domain':'cantine_sepe'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data, textStatus) {
                            if (data.d != null) {
                                $("#menuNews").html("<div id=\"newsArchiveList\" class=\"newsArchiveList\">" + data.d + "</div><div id=\"newsIndex\" class=\"newsIndex\"></div>");
                                $(".newsArchiveList a").each(function (index, item) {
                                    var obj = $(item);
                                    obj.mouseover(function () {
                                        if (!$(this).hasClass('newsArchiveCurrent'))
                                            $(this).addClass('newsArchiveHover');
                                    });
                                    obj.mouseout(function () {
                                        if (!$(this).hasClass('newsArchiveCurrent'))
                                            $(this).removeClass('newsArchiveHover');
                                    });
                                    obj.click(function () {
                                        $(".newsArchiveList a").removeClass('newsArchiveCurrent');
                                        $(this).addClass('newsArchiveCurrent');
                                        loadIndex($(this).html());
                                        return false;
                                    });
                                });
                            }
                            else
                                $("#menuNews").html("<div id=\"newsArchiveList\"></div>");
                            $("#menuNews").css("display", "none");
                            QueryLoader.notifyExtraFuncComplete();
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            QueryLoader.notifyExtraFuncComplete();

                        }
                    });
                });

                QueryLoader.addFunction(function () {
                    $("a.newsArchiveCurrent").trigger('click');
                    QueryLoader.notifyExtraFuncComplete();
                });

            } else {
                $(".newsArchiveList a").each(function (index, item) {
                    var obj = $(item);
                    obj.mouseover(function () {
                        if (!$(this).hasClass('newsArchiveCurrent'))
                            $(this).addClass('newsArchiveHover');
                    });
                    obj.mouseout(function () {
                        if (!$(this).hasClass('newsArchiveCurrent'))
                            $(this).removeClass('newsArchiveHover');
                    });
                    obj.click(function () {
                        $(".newsArchiveList a").removeClass('newsArchiveCurrent');
                        $(this).addClass('newsArchiveCurrent');
                        loadIndex($(this).html());
                        return false;
                    });
                });
                $("div[id$=newsIndex] a").each(function (index, item) {
                    SiteManagement.createNewsContentViewer($(item));
                });
            }
        }


        //
        //
        //
        //
        //
        function preLoadAltavignaPage() {
            if ($("#menuAltavigna").html() == "") {
                QueryLoader.addFunction(function () {
                    $.ajax({
                        type: "POST",
                        url: "/Altavigna.aspx/Get",
                        data: "{'language':'" + SiteManagement.currentLanguage + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data, textStatus) {
                            if (data.d != null)
                                $("#menuAltavigna").html(data.d);
                            else
                                $("#menuAltavigna").html("");
                            $("#menuAltavigna").css("display", "none");
                            QueryLoader.notifyExtraFuncComplete();
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            QueryLoader.notifyExtraFuncComplete();
                        }
                    });
                });
            } else {
                //SiteManagement.currentPage = "menuCantina";
            }
        }

        //
        //
        //
        //
        //
        function preLoadRotator() {
            QueryLoader.addFunction(function () {
                $.ajax({
                    type: "POST",
                    url: "/Default.aspx/GetFooterRotator",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data, textStatus) {
                        $("div[id$=rotatorImage]").html(data.d);
                        $("div[id$=rotatorImage]").innerfade({
                            speed: 3000,
                            timeout: 5000,
                            type: 'sequence',
                            containerheight: '1em'
                        });
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                        QueryLoader.notifyExtraFuncComplete();
                    }
                });
            });
        }

        function detectCurrentPage() {

            var url = document.location.href.toUpperCase();
            var urlParts = url.split('/');

            if (url.indexOf('.ASPX') < 0 || url.indexOf('DEFAULT.ASPX') > 0)
                SiteManagement.currentPage = "";
            else if (url.indexOf('CANTINA.ASPX') > 0)
                SiteManagement.currentPage = "menuCantina";
            else if (url.indexOf('VINI.ASPX') > 0)
                SiteManagement.currentPage = "menuVini";
            else if (url.indexOf('DOWNLOAD.ASPX') > 0)
                SiteManagement.currentPage = "menuDownload";
            else if (url.indexOf('CONTATTI.ASPX') > 0)
                SiteManagement.currentPage = "menuContatti";
            else if (url.indexOf('ALTAVIGNA.ASPX') > 0)
                SiteManagement.currentPage = "menuAltavigna";
            else if (url.indexOf('NEWS.ASPX') > 0)
                SiteManagement.currentPage = "menuNews";
            else {
                var urlParts = url.split("/");

                SiteManagement.currentWineGroupSheet = urlParts[urlParts.length - 2].toLowerCase();
                SiteManagement.currentWineSheet = urlParts[urlParts.length - 1].substring(0, urlParts[urlParts.length - 1].length - 5).toLowerCase();
                SiteManagement.currentPage = "menuVini";
            }

            SiteManagement.refreshNavigatorLink();
        }

        function onLoadComplete() {
            $jScroller.start();
        }

        if (document.location.href.toLowerCase().indexOf('/en/') > 0)
            SiteManagement.currentLanguage = "en";

        detectCurrentPage();

        start();

        preLoadCatinaPage();
        preLoadViniPage();
        preLoadNews();
        preLoadContattiPage();
        preLoadDownloadPage();
        preLoadAltavignaPage();
        preLoadRotator();
        QueryLoader.preloadExtraImages(extraImages);

        QueryLoader.selectorPreload = "body";
        $("#mainContainer").css('display', '');
        $("div[id$=welcomeContainer]").remove();
        QueryLoader.doneComplete = onLoadComplete;
        QueryLoader.init();
    },

    refreshNavigatorLink: function () {
        var url;

        switch (SiteManagement.currentPage.toUpperCase()) {
            case "MENUCANTINA":
                url = "cantina.aspx";
                break;
            case "MENUVINI":
                if (SiteManagement.currentWineGroupSheet != "")
                    url = SiteManagement.currentWineGroupSheet + "/" + SiteManagement.currentWineSheet + ".aspx";
                else
                    url = "vini.aspx";
                break;
            case "MENUNEWS":
                url = "news.aspx";
                break;
            case "MENUCONTATTI":
                url = "contatti.aspx";
                break;
            case "MENUDOWNLOAD":
                url = "download.aspx";
                if ($("div [id$=pageDownloadList]").css('display') != 'none')
                    url = "downloadlist.aspx";
                break;
            case "MENUALRAVIGNA":
                url = "alravigna.aspx";
                break;
            default:
                url = "default.aspx";
                break;
        }

        if (SiteManagement.currentLanguage == "it")
            $("a[id$=enLink]").attr('href', "/en/" + url);
        else
            $("a[id$=itLink]").attr('href', "/it/" + url);
    },

    //
    //
    //
    //
    //
    enter: function (codeLanguage) {
        if (codeLanguage == "en")
            $('head').append('<link rel="stylesheet" href="/styles/menu_en.css" type="text/css" />');
        SiteManagement.currentLanguage = codeLanguage;
        SiteManagement.init();
        $("#welcomeTop").remove();
    },

    //
    //
    //
    //
    //
    initEnter: function (html) {

        $("#linkIT").replaceWith($("#linkIT").html().toLowerCase().replace("<img ", "<img id=\"linkIT\" "));
        $("#linkIT").click(function () {
            $("#welcomeLinks").fadeOut('slow', function () {
                SiteManagement.enter("it");
            });
        });
        $("#linkEN").replaceWith($("#linkEN").html().toLowerCase().replace("<img ", "<img id=\"linkEN\" "));
        $("#linkEN").click(function () {
            $("#welcomeLinks").fadeOut('slow', function () {
                SiteManagement.enter("en");
            });
        });

    },

    //
    //
    //
    //
    //
    openMenu: function (id, showSubPage, complete) {

        if (SiteManagement.changingPage)
            return;

        SiteManagement.changingPage = true;

        var obj = $("#menuItem" + id.substring(4));
        var newClassName = "menuItem" + id.substring(4) + "On";
        var className = obj.attr("class");

        $("#menuItemCantina").attr("class", "menuItemCantina");
        $("#menuItemVini").attr("class", "menuItemVini");
        $("#menuItemNews").attr("class", "menuItemNews");
        $("#menuItemContatti").attr("class", "menuItemContatti");
        $("#menuItemDownload").attr("class", "menuItemDownload");
        $("#menuItemAltavigna").attr("class", "menuItemAltavigna");

        if (SiteManagement.currentPage != id)
            obj.attr("class", newClassName);

        if (SiteManagement.currentPage == "") {
            var newHeight = $("#" + id).css('height');
            if (id == "menuCantina")
                newHeight = 430;
            else if (id == "menuVini" && showSubPage)
                newHeight = $(".pageWineDetail").css('height');
            else if (id == "menuDownload" && showSubPage)
                height: $("div[id$=pageDownloadList]").css('height');
            else if (id == "menuNews")
                newHeight: Math.max($("#menuNews").outerHeight(), Math.max($(".newsArchiveList").outerHeight(), $(".newsIndex").outerHeight())) + "px"
            if (newHeight == "auto")
                newHeight = $("#" + id).outerHeight() + "px";
            $("div[id$=contentArea]").animate({
                height: newHeight
            }, 500);
            $("#" + id).fadeIn(800, function () {
                SiteManagement.currentPage = id;
                SiteManagement.changingPage = false;
                SiteManagement.refreshNavigatorLink();
                if (id == "menuContatti")
                    SiteManagement.initGoogleMap();
                if (complete != null && complete != undefined)
                    complete();
            });
        } else if (SiteManagement.currentPage == id) {
            $("#" + id).fadeOut(800);
            $("div[id$=contentArea]").animate({
                height: 0 + "px"
            }, 500, function () {
                $("#menuVini div[id$=pageWineList]").css("display", "block");
                $("#menuVini div[id$=pageWineDetail]").css("display", "none");
                $("#menuDownload div[id$=pageMainDownload]").css("display", "block");
                $("#menuDownload div[id$=pageDownloadList]").css("display", "none");
                SiteManagement.currentPage = "";
                SiteManagement.changingPage = false;
                SiteManagement.refreshNavigatorLink();
            });
        } else {
            var newHeight = $("#" + id).css('height');
            if (id == "menuCantina")
                newHeight = 430;
            else if (id == "menuVini" && showSubPage)
                newHeight = $(".pageWineDetail").css('height');
            else if (id == "menuDownload" && showSubPage)
                height: $("div[id$=pageDownloadList]").css('height');
            else if (id == "menuNews")
                newHeight: Math.max($("#menuNews").outerHeight(), Math.max($(".newsArchiveList").outerHeight(), $(".newsIndex").outerHeight())) + "px"
            if (newHeight == "auto")
                newHeight = $("#" + id).outerHeight() + "px";
            $("div[id$=contentArea]").animate({
                height: newHeight
            }, 500);
            $("#" + SiteManagement.currentPage).fadeOut('fast', function () {
                $("#menuVini div[id$=pageWineList]").css("display", showSubPage ? "none" : "block");
                $("#menuVini div[id$=pageWineDetail]").css("display", showSubPage ? "block" : "none");
                $("#menuDownload div[id$=pageMainDownload]").css("display", showSubPage ? "none" : "block");
                $("#menuDownload div[id$=pageDownloadList]").css("display", showSubPage ? "block" : "none");
                $("#" + id).fadeIn(800, function () {
                    SiteManagement.currentPage = id;
                    SiteManagement.changingPage = false;
                    SiteManagement.refreshNavigatorLink();
                    if (id == "menuContatti")
                        SiteManagement.initGoogleMap();
                    if (complete != null && complete != undefined)
                        complete();
                });
            })
        }


        SiteManagement.currentWineGroupSheet = "";
        SiteManagement.currentWineSheet = "";
        $(".pageMainDownload")[0].style.height = '';
        $(".pageMainDownload").css('opacity', '1');
    },

    //
    //
    //
    //
    //
    openSheet: function (group, product) {

        function swapSheet(from, to) {
            $("#wineSheetLoader").fadeOut();
            if (from != null && from.html() != null) {
                from.fadeOut('low', function () {
                    //from.css('display', 'none');
                    if (to != null) {
                        //to.css('display', 'block');
                        to.fadeIn('low');
                    }
                });
            } else if (to != null) {
                //to.css('display', 'block');
                to.fadeIn('low');
            }
        }

        function loadProductSheet(group, product) {

            $("div[id^=wineSheet_]").fadeOut('low');
            $("#wineSheetLoader").fadeIn('low');

            var parameter = "'language':'" + SiteManagement.currentLanguage + "'";
            parameter += ",'group':'" + group + "'";
            parameter += ",'product':'" + product + "'";

            $.ajax({
                type: "POST",
                url: "/Vini.aspx/GetDetail",
                data: "{" + parameter + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus) {
                    $("div[id$=wineSheet]").append(data.d);
                    wineSheetObject = $("#wineSheet_" + group + "_" + product);
                    wineSheetObject.fadeOut('fast', function () {
                        $("#wineSheet_" + group + "_" + product + " .wineSheetZoomLink").fancybox({
                            'titleShow': false,
                            'showCloseButton': true,
                            'autoDimensions': false,
                            'autoScale': false,
                            'overlayOpacity': 0.9,
                            'overlayColor': '#000000',
                            'opacity': true
                        });
                        $("#wineSheet_" + group + "_" + product).find(".wineSheetFormatNavigator a").click(function () {
                            if ($(this).hasClass('wineFormatNavigatorLink')) {
                                $("#wineSheet_" + group + "_" + product).find(".wineSheetFormatNavigator a").addClass('wineFormatNavigatorLink');
                                $(this).removeClass('wineFormatNavigatorLink');
                                $("#wineSheet_" + group + "_" + product).find(".wineSheetZoomLink").hide();
                                $("#wineSheet_" + group + "_" + product).find("a." + $(this).attr('class')).show();
                                $("#wineSheet_" + group + "_" + product).find(".wineSheetRight img").hide();
                                $("#wineSheet_" + group + "_" + product).find("img." + $(this).attr('class')).fadeIn('low');
                            }
                            return false;

                        });
                        swapSheet($("#wineSheet_" + SiteManagement.currentWineGroupSheet + "_" + SiteManagement.currentWineSheet), wineSheetObject);
                    });
                },
                error: function (data, textStatus) {
                    $("#wineSheetLoader").hide();
                    swapSheet($("#wineSheet_" + SiteManagement.currentWineGroupSheet + "_" + SiteManagement.currentWineSheet), null);
                },
                complete: function (data, textStatus) {
                    //$("div[id$=wineSheet]").show();
                    SiteManagement.currentWineGroupSheet = group;
                    SiteManagement.currentWineSheet = product;
                    SiteManagement.refreshNavigatorLink();
                }
            });
        }

        if (SiteManagement.currentWineGroupSheet == group && SiteManagement.currentWineSheet == product)
            return;

        if (SiteManagement.currentPage != "menuVini") {
            SiteManagement.openMenu("menuVini", true, function () { SiteManagement.openSheet(group, product) });
            return;
        }

        var detailObject = $("div[id$=pageWineDetail]");
        if (detailObject.css('display') == 'none') {
            $("div[id$=pageWineList]").slideUp('fast');
            $("div[id$=contentArea]").animate({
                height: $(".pageWineDetail").css('height')
            }, 500);
            detailObject.slideDown('fast');
        }

        SiteManagement.showAccordionWineGroup(group);

        var productObject = $("#wineSheet_" + group + "_" + product);
        if (productObject.length == 0)
            loadProductSheet(group, product);
        else {
            if (SiteManagement.currentWineGroupSheet == '')
                swapSheet(null, productObject);
            else
                swapSheet(
                    $("#wineSheet_" + SiteManagement.currentWineGroupSheet + "_" + SiteManagement.currentWineSheet),
                    productObject);
            SiteManagement.currentWineGroupSheet = group;
            SiteManagement.currentWineSheet = product;
            SiteManagement.refreshNavigatorLink();
        }
    },

    //
    //
    //
    //
    //
    openingAccordionGroup: false,
    showAccordionWineGroup: function (group) {

        if (SiteManagement.openingAccordionGroup)
            return;

        var toShow = $("div[id$=wineSheet_" + group + "]");
        if (toShow.attr('menuAccordionOpened') == 'listWineAccordion')
            return;

        SiteManagement.openingAccordionGroup = true;

        var toHide = $("div[menuAccordionOpened=listWineAccordion]");

        toHide.animate({
            height: 0,
            opacity: 0
        }, 500);

        toShow.animate({
            height: (toShow.children().length + 0) * toShow.children().height() + "px", //((toShow.children().length + 0) * toShow.children().css('height').replace('px', '')) + "px" ,
            opacity: 1
        }, 500, function () {
            toHide.attr('menuAccordionOpened', 'none');
            toShow.attr('menuAccordionOpened', 'listWineAccordion');
            SiteManagement.openingAccordionGroup = false;
        });


        /*        
        if (toHide.length == 0) {
        toShow.css('height', '352px').fadeIn('fast');
        toShow.attr('menuAccordionOpened', 'listWineAccordion');
        SiteManagement.openingAccordionGroup = false;
        }
        else {
        toShow.css('height', '0px').css('opacity', '0')
        toHide.animate(
        {
        height: 0,
        opacity: 0
        },
        {
        duration: 'fast',
        easing: 'linear',
        step: function(currentValue, data) {
        if (data.prop == "height")
        toShow.css('height', (352 - currentValue) + "px");
        else if (data.prop == "opacity")
        toShow.css('opacity', 1 - currentValue);
        },
        complete: function() {
        toHide.attr('menuAccordionOpened', 'none');
        toShow.attr('menuAccordionOpened', 'listWineAccordion');
        SiteManagement.openingAccordionGroup = false;
        }
        }
        );
        }
        */
    },

    //
    //
    //
    //
    //
    showAccordionCurrentWineGroup: function () {
        SiteManagement.showAccordionWineGroup(SiteManagement.currentWineGroupSheet);
    },

    makeLinkViniDynamic: function (obj, addProductAttribute) {

        function WineData(url) {

            var lastIdx = url.lastIndexOf('/', url.length - 1);
            var firstIdx = url.lastIndexOf('/', lastIdx - 1);

            this.group = url.substring(firstIdx + 1, lastIdx);
            this.name = url.substring(lastIdx + 1, url.length - 5);
        }

        function createOnClickHandler(data) {
            return "onclick=\"SiteManagement.openSheet('" + data.group + "','" + data.name + "');\"";
        }

        var data = new WineData(obj.attr('href'));
        var newObj = $("<span></span>");
        newObj.insertBefore(obj);
        newObj.html(obj.html());
        newObj.click(function () {
            SiteManagement.openSheet(data.group, data.name);
        });
        obj.remove();

        if (addProductAttribute)
            newObj.attr("product", data.group + "," + data.name);

        return newObj;
    },

    //
    //
    //
    //
    //
    makeLinkViniPageToDynamic: function () {



        $("div[id$=pageWineList] a").each(function (idx, item) {
            var obj = $(item);
            //var data = new WineData(obj.attr('href'));
            //obj.replaceWith("<span " + createOnClickHandler(data) + ">" + obj.html() + "</span>");
            SiteManagement.makeLinkViniDynamic(obj);
        });

        //$(".accordionWineGroup").attr("menuAccordionOpened", "none");
        $(".accordionWineGroup").each(function (idx, item) {
            if (!$(item).attr("menuAccordionOpened"))
                $(item).attr("menuAccordionOpened", "none");
        });

        $(".accordionWineGroup > a").each(function (idx, item) {
            var obj = $(item);
            //var data = new WineData(obj.attr('href'));
            //obj.replaceWith("<span " + createOnClickHandler(data) + " product=\"" + data.group + "," + data.name + "\">" + obj.html() + "</span>");
            SiteManagement.makeLinkViniDynamic(obj, true);
        });

        $("div[id$=pageWineDetail] span > a").each(function (idx, item) {
            var obj = $(item);
            obj.replaceWith("<span>" + obj.html() + "</span>");
        });

        $("div[id$=pageMainDownload] a").each(function (idx, item) {
            var obj = $(item);
            if (obj.attr('href').toLowerCase().indexOf('downloadlist.aspx') >= 0) {
                obj.click(function () {
                    $("div[id$=pageMainDownload]").animate({
                        height: 0,
                        opacity: 0
                    });
                    $("div[id$=pageDownloadList]").fadeIn('slow', function () {
                        SiteManagement.refreshNavigatorLink();
                    });
                    $("div[id$=contentArea]").animate({
                        height: $("div[id$=pageDownloadList]").outerHeight() + "px"
                    }, 500);
                    return false;
                });
            }
        });

        $("div[id$=pageDownloadList] a").each(function (idx, item) {

            function WineData(url) {

                var lastIdx = url.lastIndexOf('/', url.length - 1);
                var firstIdx = url.lastIndexOf('/', lastIdx - 1);

                this.group = url.substring(firstIdx + 1, lastIdx);
                this.name = url.substring(lastIdx + 1, url.length - 5);
            }

            var obj = $(item);
            var data = new WineData(obj.attr('href'));
            obj.replaceWith("<span onclick=\"window.open('" + obj.attr('href') + "','" + data.group + "_" + data.name + "');\">" + obj.html() + "</span>");
        });
    },

    //
    //
    //
    //
    //
    sendContactEmail: function () {

        var name = $.trim($("#inputName").attr("value"));
        var email = $.trim($("#inputEmail").attr("value"));
        var obj = $.trim($("#inputObject").attr("value"));
        var msg = $.trim($("#inputMessage").attr("value"));
        var parameter;

        if (name.length == 0)
            return false;
        parameter = "'name':'" + name + "'";

        if (email.length == 0)
            return false;
        parameter += ",'email':'" + email + "'";

        if (obj.length == 0)
            return false;
        parameter += ",'obj':'" + obj + "'";

        if (msg.length == 0)
            return false;
        parameter += ",'msg':'" + msg + "'";

        parameter += ",'codeLanguage':'" + SiteManagement.currentLanguage + "'";

        $.ajax({
            type: "POST",
            url: "/Contatti.aspx/SendEmail",
            data: "{" + parameter + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data, textStatus) {
                $.fancybox(data.d);
            },
            error: function (XMLHttpRequest, textStatus) {
                alert("Attenzione. Per motivi tecnici non è stato possibile inviare i dati per contattarLa");
            }
        });
    },

    initGoogleMap: function () {
        if (SiteManagement.map == null) {
            var latlng = new google.maps.LatLng(40.878914, 14.509048);
            var myOptions = {
                zoom: 8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            SiteManagement.map = map;
            SiteManagement.marker_map = new google.maps.Marker({
                position: latlng,
                map: map,
                title: "Cantine Sepe",
                visible: true
            });
            google.maps.event.addListener(SiteManagement.marker_map, 'click', function () {
                window.open("http://maps.google.it/maps?q=40.878914,14.509048&num=1&sll=40.878904,14.509058&sspn=0.001424,0.003181&hl=it&ie=UTF8&ll=40.878904,14.509058&spn=0.001424,0.003181&z=19");
            });
        }
    },

    createNewsContentViewer: function (obj) {

        function formatNewsGalleryTitle(title, currentArray, currentIndex, currentOpts) {
            var html

            html = '<div id="gallery-title">';
            html += '<img src="/scripts/fancybox/fancy_close.png" onclick="$.fancybox.close();"/>';
            if (currentIndex < currentArray.length - 1)
                html += '<img src="/scripts/fancybox/fancy_nav_right.png" onclick="$.fancybox.next();"/>';
            if (currentIndex > 0)
                html += '<img src="/scripts/fancybox/fancy_nav_left.png" onclick="$.fancybox.prev();"/>';
            html += (title && title.length ? '<b>' + title + '</b>' : '');
            if (SiteManagement.currentLanguage == "it")
                html += 'Immagine ' + (currentIndex + 1) + ' di ' + currentArray.length;
            else
                html += 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length;
            html += '</div>';

            return html;
        }

        var urlRequest = '/news.aspx/GetContent';
        var id = obj.attr('href').substr(obj.attr('href').toLowerCase().indexOf('/news_') + 6).replace('.aspx', '');
        var lang = obj.attr('href').toLowerCase().indexOf('/en/') > 0 ? "en" : "it";
        obj.fancybox({
            'ajax': {
                type: 'POST',
                url: urlRequest,
                data: "{'lang':'" + lang + "','id':'" + id + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            },
            'type': 'ajax',
            'autoSize': 'false',
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'easingIn': 'easeOutBack',
            'easingOut': 'easeInBack',
            'overlayOpacity': 0.9,
            'overlayColor': '#000000',
            'opacity': true,
            'hideOnContentClick': false,
            'onLoaded': function () {
                $(".newsGallery a").each(function (index, item) {
                    SiteManagement.makeImageThumb($(item).find('img'));
                });
            },
            'onComplete': function () {

                $(".newsGallery a").attr('rel', 'prettyPhoto[pp_gal]');
                $(/*"a[rel^='prettyPhoto']"*/".newsGallery a").prettyPhoto({
                    animationSpeed: 'fast',
                    allowresize: true,
                    opacity: 0.90,
                    showTitle: true,
                    theme: 'light_square'
                });
            }
            ,
            'onClosed': function () {
                $(".pp_pic_holder").remove();
                $(".pp_top").remove();
                $(".pp_content_container").remove();
                $(".pp_bottom").remove();
                $(".pp_overlay").remove();
                $(".ppt").remove();
            }
        })
    },

    makeImageThumb: function (imgObj) {
        var src = imgObj.attr('src');
        var container = imgObj.parent();
        imgObj.hide();
        container.addClass('newsLoading')
        var img = new Image();
        $(img).load(function () {
            $(this).hide();
            var maxHeight = container.height();
            var maxWidth = container.width();
            var imgHeight = this.height;
            var imgWidth = this.width;
            if (maxWidth == 0 && container.css('width') != "auto")
                maxWidth = container.css('width').replace('px', '');
            if (maxHeight == 0 && container.css('height') != "auto")
                maxHeight = container.css('height').replace('px', '');
            if (maxWidth != 0 && maxHeight != 0) {
                if (imgWidth > maxWidth && imgWidth > imgHeight) {
                    imgObj.css('width', maxWidth + 'px');
                    imgObj.css('margin-top', Math.floor(((maxHeight - (imgHeight * (maxWidth / imgWidth))) / 2)) + 'px');
                } else if (imgHeight > maxHeight && imgWidth < imgHeight) {
                    imgObj.css('height', maxHeight + 'px');
                    imgObj.css('margin-left', Math.floor(((maxWidth - (imgWidth * (maxHeight / imgHeight))) / 2)) + 'px');
                } else {
                    imgObj.css('margin-top', Math.floor((maxHeight - imgHeight) / 2) + 'px');
                    imgObj.css('margin-left', Math.floor((maxWidth - imgWidth) / 2) + 'px');
                }
            }
            container.removeClass('newsLoading');
            imgObj.fadeIn('slow');
        }).error(function () {
            container.removeClass('newsLoading');
        }).attr('src', src);
    }
}
