/// <reference path="/JS/jquery-vsdoc.js" />

/* - - - - - - - - - - - - - - - - - - - - 
D E S I G N W I N E
http://www.designwine.com
website by websolute
- - - - - - - - - - - - - - - - - - - - */

/* homepage buttons
- - - - - - - - - - - - - - - - - - - - */
function homepage_btn()
{
    maxHeightWidth3 = 0; //homepage width3 maxHeight
    $(".wrap3.homepage .width3").each(function ()
    {
        if ($(this).height() > maxHeightWidth3)
        {
            maxHeightWidth3 = $(this).height();
        }
    });
    $(".wrap3.homepage .width3").height(maxHeightWidth3 + 30);

    maxHeightWidth2 = 0; //homepage width2 maxHeight
    $(".wrap.homepage .width2:lt(2)").each(function ()
    {
        if ($(this).height() > maxHeightWidth2)
        {
            maxHeightWidth2 = $(this).height();
        }
    });
    $(".wrap.homepage .width2:lt(2)").height(maxHeightWidth2 + 20);

    maxHeightWidth2 = 0; //homepage width2 maxHeight
    $(".wrap.homepage .width2:gt(1)").each(function ()
    {
        if ($(this).height() > maxHeightWidth2)
        {
            maxHeightWidth2 = $(this).height();
        }
    });
    $(".wrap.homepage .width2:gt(1)").height(maxHeightWidth2 + 20);
}


/* homepage selections
- - - - - - - - - - - - - - - - - - - - */
var z = 0;
var flagClick = false;

function selWidth()
{
    if ($(window).width() > 0)
    {
        $(".wine_selection").css({ "width": $(window).width() + "px" });
        $(".wrap_wine_selection").css({ "width": ($(".wine_selection").width() * $(".wine_selection").size()) + "px" });
    }
    else
    {
        $(".wrap_wine_selection, .wine_selection").css({ "width": "100%" });
    }
}


function homepage_sel()
{
    var loop;
    selWidth();
    createNav();

    function createNav()
    {
        size = $(".wine_selection").size();
        if (size > 1)
        {
            $(".navigation").prepend('<ul></ul>');
        }
        for (j = 0; j < $(".wine_selection").size(); j++)
        {
            $("#selection .navigation ul").append('<li class="ball png"><a href="#">' + (j + 1) + '</a></li>');
        }
        $("#selection .navigation ul li:eq(0) a").addClass("on");
        $("#selection .navigation ul li a").click(function ()
        {
            clearInterval(firstLoop);
            thisNav = $("#selection .navigation ul li a").index($(this));
            z = thisNav;
            $("#selection :animated").stop();
            flagClick = true;
            animateSel(z);
            return false;
        });
    }

    function animateSel(arg)
    {
        if (arg < $(".wine_selection").size() - 1)
        {
        } else
        {
            z = -1;
        }
        var next = ((arg + 1) > $(".wine_selection").size()) ? 0 : arg;
        $("#selection .navigation ul li a.on").removeClass("on");
        $("#selection .navigation ul li:eq(" + next + ") a").addClass("on");

        if (jQuery.browser.msie)
        {
            if (flagClick)
            {
                $(".box").css({ "padding": "0px" });
            } else
            {
                $(".box").css({ "padding": "0px" }, 500);
            }
            $(".box:eq(" + next + ")").animate({ "padding": "0px" }, 50, function ()
            {
                $(".wrap_wine_selection").animate({ "left": "-" + ($(".wine_selection").width() * arg) + "px" }, 2500, "easeOutQuint", function ()
                {
                    $(".box:eq(" + next + ")").animate({ "padding": "0px" }, 500, function ()
                    {
                        $(".box:eq(" + next + ")").animate({ "padding": "0px" }, 5000, function ()
                        {
                            animateSel(++z);
                            flagClick = false;
                        });
                    });
                });
            });
        } else
        {
            if (flagClick)
            {
                $(".box").css({ "opacity": 0 });
            } else
            {
                $(".box").animate({ "opacity": 0 }, 500);
            }
            $(".wrap_wine_selection").animate({ "left": "-" + ($(".wine_selection").width() * arg) + "px" }, 2500, "easeOutQuint", function ()
            {
                $(".box:eq(" + next + ")").animate({ "opacity": 1 }, 500, function ()
                {
                    $(".box:eq(" + next + ")").animate({ "opacity": 1 }, 5000, function ()
                    {
                        animateSel(++z);
                        flagClick = false;
                    });
                });
            });
        }
    }
    if ($(".wine_selection").size() > 1)
    {
        firstLoop = setTimeout(function () { animateSel(++z) }, 5000);
    }
}


/* menu
- - - - - - - - - - - - - - - - - - - - */
function menu()
{
    $("#menu ul > li:eq(0) li:gt(2)").hide();

    $("#menu span:eq(0), #menu ul > li:eq(0) a:eq(0)").not(".back").click(function ()
    {
        $("#menu span").hide();
        $("#menu ul > li:eq(0) li:gt(2)").show();
        $("#menu ul > li:eq(0) ul").show();
        $("#menu ul > li:eq(1) ul").hide();
    });

    href = location.href.split("/")[4];
    self.status = href;
    $("#menu a[href$=" + href + "]").addClass("on");

    if ($("#menu ul li a.on").size())
    {
        $("#menu ul li a.on").parents("li:eq(1)").find("a:eq(0)").click();
    }

    $("#menu span:eq(0)").click();
}


/* tabs
- - - - - - - - - - - - - - - - - - - - */
function tabs()
{
    if ($("ul.tab_menu").size())
    {
        var wrap = 870;
        var num = $("ul.tab_menu li").size();
        var width = 0;
        var newWidth = 0;
        $("ul.tab_menu li").each(function ()
        {
            width = width + $(this).width() + 1;
        });
        addPad = Math.floor((wrap - width) / num) + 9;
        $("ul.tab_menu li a span").css({ "padding-right": addPad + "px" });
        $("ul.tab_menu li").each(function ()
        {
            newWidth = newWidth + $(this).width() + 1;
        });
        $("ul.tab_menu li:last a span").css({ "padding-right": addPad + (wrap - newWidth - 1) + "px" });

        // click
        $(".tab").addClass("classHidden");
        $(".tab:eq(0)").removeClass("classHidden");
        $("ul.tab_menu li a:first").addClass("on");
        $("ul.tab_menu li a").click(function ()
        {
            $("ul.tab_menu li a").removeClass("on");
            $(this).addClass("on");
            $(".tab").addClass("classHidden");
            $($(this).attr("href")).removeClass("classHidden");
            return false;
        });
    }
}


/* you may also like
- - - - - - - - - - - - - - - - - - - - */
function also_like()
{
    var thisNav = 0;
    if ($("#also_like").size())
    {
        if ($("#also_like .width2").size() > 2)
        {
            $("#also_like").append('<div class="nav clearfix"><a href="#" class="left">&nbsp;</a><ul></ul><a href="#" class="right">&nbsp;</a></div>');
            var nav = Math.ceil(($("#also_like .width2").size() / 2));
            for (i = 0; i < nav; i++)
            {
                $("#also_like .nav ul").append('<li class="ball"><a href="#">&nbsp;</a></li>');
            }
            $("#also_like ul li a:eq(0)").addClass("on");
            $("#also_like ul li a").click(function ()
            {
                thisNav = $("#also_like ul li a").index($(this));
                $("#also_like ul li a.on").removeClass("on");
                $("#also_like ul li a:eq(" + thisNav + ")").addClass("on");
                $("#also_like .scrollable").animate({ "left": "-" + (thisNav * 916) + "px" }, 500);
                return false;
            });

            $("#also_like a.left").click(function ()
            {
                if (thisNav != 0)
                {
                    thisNav = thisNav - 1;
                    $("#also_like ul li a.on").removeClass("on");
                    $("#also_like ul li a:eq(" + thisNav + ")").addClass("on");
                    $("#also_like .scrollable").animate({ "left": "-" + (thisNav * 916) + "px" }, 500);
                }
                return false;
            });

            $("#also_like a.right").click(function ()
            {
                if (thisNav != nav - 1)
                {
                    thisNav = thisNav + 1;
                    $("#also_like ul li a.on").removeClass("on");
                    $("#also_like ul li a:eq(" + thisNav + ")").addClass("on");
                    $("#also_like .scrollable").animate({ "left": "-" + (thisNav * 916) + "px" }, 500);
                }
                return false;
            });
        }
    }
}


/* - - - - - - - - - - - - - - - - - - - - 
VINI AJAX
- - - - - - - - - - - - - - - - - - - - */
function vinoAjax()
{
    if ($(".single_wine").size())
    {
        $(".single_wine .caratteristiche_vino").html('<img src="/img/loading.gif" class="loading" alt="loading" />');
        j = 0;
        function ajax(i)
        {
            if (i < $(".single_wine").size())
            {
                $(".single_wine:eq(" + i + ")").each(function ()
                {

                    try
                    {
                        id = $(this).find(".caratteristiche_vino").attr("class").split("id_")[1];
                    }
                    catch (e) { id = null; }

                    if (id != null)
                    {
                        $this = $(this);
                        $.ajax({
                            type: "POST",
                            url: "/ws/wsGetContent.asmx/GetCaratteristicheVino",
                            cache: false,
                            contentType: "application/json; charset=utf-8",
                            data: "{id: " + id + "}",
                            dataType: "json",
                            success: function (data)
                            {
                                $this.find(".caratteristiche_vino").html(data.d.HTML);
                                ajax(++j);
                            },
                            error: function (data)
                            {
                                //self.status = self.status + "errore ";
                                ajax(++j);
                                if (data.d != null)
                                    $this.find(".caratteristiche_vino").html(data.d.ErrMessage);
                            }
                        });
                    }
                });
            } else
            {
                return false;
            }
        }

        ajax(j);
    }
}


/* scrollnotes
- - - - - - - - - - - - - - - - - - - - */
function scrollNotes()
{
    if ($("#notes").size())
    {
        $domH = $(document).height();
        $top = $(document).scrollTop();
        spost = Math.floor(10 + $top);
        if ($top > 133)
        {
            $("#notes").stop().animate({ top: spost }, 1000);
        } else
        {
            $("#notes").stop().animate({ top: 133 }, 1000);
        }
    }
}


/* paginazione ricerce
- - - - - - - - - - - - - - - - - - - - */
function GoToPage_Default(p)
{
    GoToPage("frmPager", "hfCurrentPage", p);
}

function GoToPage(formName, hiddenName, destPage)
{
    var currPage = $("#" + hiddenName).val();
    //alert(currPage + " - " + destPage);
    if (currPage != destPage)
    {
        $("#" + hiddenName).val(destPage);

        var act = $("#" + formName).attr("action");
        if (destPage != 1)
        {
            if (act.indexOf("?") >= 0)
                act = act + "&p=" + destPage;
            else
            {
                if (act.charAt(act.length - 1) == "/")
                    act = act + "?p=" + destPage;
                else
                    act = act + "/?p=" + destPage;
            }

            $("#" + formName).attr("action", act);
        }

        $("#" + formName).submit();
    }
}

function GoToPage2(formName, hiddenName, action, destPage)
{
    var currPage = $("#" + hiddenName).val();
    //alert(currPage + " - " + destPage);
    if (currPage != destPage)
    {
        if (destPage != 1)
            action = action + "&p=" + destPage;

        $("#" + hiddenName).val(destPage);
        $("#" + formName).attr("action", action);
        $("#" + formName).submit();
    }
}

/* ricerche
- - - - - - - - - - - - - - - - - - - - */
function searchByRegion(val, text, act)
{
    $("#hfCurrRegion").val(val);
    $("#frmSetRegion").attr("action", (act + "?r=" + text));
    $("#frmSetRegion").submit();
}

function searchByType(t, val, text, act)
{
    $("#hfSearchFor").val(t);
    $("#hfCurrWType").val(val);
    $("#frmSetWType").attr("action", (act + "?" + t + "=" + text));
    $("#frmSetWType").submit();
}



/* carrello: aggiungi prodotto
- - - - - - - - - - - - - - - - - - - - */
function AddProduct(idP, codArt, qta, goUrl, t)
{
    $.ajax({
        type: "POST",
        url: "/ws/wsBasket.asmx/AddProduct",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: "{id: " + idP + ", codArt: '" + codArt + "', qta: " + qta + ", pType: " + t + "}",
        dataType: "json",
        success: function (data)
        {
            GoToBasket(goUrl);
        },
        error: function (data)
        {
            //self.status = self.status + "errore ";
        }
    });
}

/* carrello: rimuovi prodotto
- - - - - - - - - - - - - - - - - - - - */
function RemoveProduct(idP, codArt, msgConfirm)
{
    var goOn = confirm(msgConfirm);
    if (goOn)
    {
        $.ajax({
            type: "POST",
            url: "/ws/wsBasket.asmx/RemoveProduct",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{id: " + idP + ", codArt: '" + codArt + "'}",
            dataType: "json",
            success: function (data)
            {
                $("#lista_" + codArt).fadeOut(500);
                UpdateCountAndTot(data);
            },
            error: function (data)
            {
                //self.status = self.status + "errore ";
                if (data.d != null)
                    alert(data.d.ErrMessage);
            }
        });
    }
}

/* carrello: aggiornamento Qta
- - - - - - - - - - - - - - - - - - - - */
function setQtaTemp(id1, id2)
{
    if (!isNaN($("#" + id1).val()))
        $("#" + id2).val($("#" + id1).val());
}

function changeQta(id1, id2, coId, codArt)
{
    var from = $("#" + id1).val();
    var to = $("#" + id2).val();

    /* validazione */
    if (isNaN(to) || to <= 0)
    {
        $("#" + id2).attr("style", "color:#f00;");
        return;
    }

    if (to > 50)
    {
        to = 50;
    }

    $("#" + id2).removeAttr("style");

    /* se necessario cambio */
    if (from != to)
    {
        //alert("CAMBIO da " + from + " a " + to);
        changeQtaCallWS(id1, id2, to, coId, codArt);
    }
    //else
    //    alert("CAMBIO NON NECESSARIo " + from + " = " + to);
}


function changeQtaCallWS(id1, id2, newQta, CoId, codArt)
{
    $.ajax({
        type: "POST",
        url: "/ws/wsBasket.asmx/ChangeQtaProduct",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: "{id: " + CoId + ", codArt: '" + codArt + "', newQta: " + newQta + "}",
        dataType: "json",
        success: function (data)
        {
            var qta = data.d.Props.qtaProd;
            if (qta > 1)
            {
                $("#" + id2).parent().parent().find("#priceTot").html(data.d.Props.priceTotProd);
                $("#" + id2).parent().parent().find(".sel_tot").show();
            }
            else
                $("#" + id2).parent().parent().find(".sel_tot").hide();

            $("#" + id1).val(qta);
            $("#" + id2).val(qta);
            UpdateCountAndTot(data);
        },
        error: function (data)
        {
            //self.status = self.status + "errore ";
            if (data.d != null)
                alert(data.d.ErrMessage);
        }
    });
}


function UpdateCountAndTot(data)
{
    $(".basketTot").html("<strong>" + data.d.Props.priceTot + "</strong>");
    $("#basketNrItems").html(data.d.Props.qtaTot);
}


function CheckBasket()
{
    var ok = CheckPaeseSped();

    if (ok)
    {
        // Check QTA
        var txtQta = $.trim($("#basketNrItems").html());
        var qta = parseInt(txtQta);

        if (isNaN(qta))
            return false;
        else
        {
            if (qta <= 0)
            {
                var c = "<div class='fancyLanding'>" + $("#alertBasketEmpty").html() + "</div>";
                $.fancybox({ 'content': c });
            }
            return (qta > 0);
        }
    }
    else
        return ok;
}

function CheckPaeseSped()
{
    var area = $("#cboAree").val();
    $("#cboAree").removeClass("red");

    if (area == "-1")
    {
        $("#cboAree").addClass("red");
        $("#cboAree").parent().parent().addClass("red");

        var c = "<div class='fancyLanding'>" + $("#alertPaeseSpedReq").html() + "</div>";
        $.fancybox({ 'content': c });
    }

    if (area == "-2")
    {
        $("#linkOtherCountryContacts").click();
    }

    return (area != "-1" && area != "-2");
}

function retrievePrezzoCorriere()
{
    if ($("#cboAree").size())
    {
        var naz = $("#cboAree").val();

        //alert(area);
        $("#spanOtherCountry").hide();
        if (naz == -1)
        {
            $("#sp_price").html("");
        }
        else if (naz == -2)
        {
            $("#sp_price").html("");
            $("#spanOtherCountry").show();
            $("#linkOtherCountryContacts").click();
        }
        else
        {
            $("#loadingSpeseSped").show();
            $.ajax({
                type: "POST",
                url: "/ws/wsBasket.asmx/RetrievePriceDelivery",
                cache: false,
                contentType: "application/json; charset=utf-8",
                data: "{idNazione: " + naz + "}",
                dataType: "json",
                success: function (data)
                {
                    $("#loadingSpeseSped").hide();
                    $(".basketTot").html("<strong>" + data.d.Props.TOTALE + "</strong>");
                    $("#sp_price").html(data.d.Props.SSPED);
                    $("#sp_price").show();
                },
                error: function (data)
                {
                    $("#loadingSpeseSped").hide();
                    if (data.d != null)
                        alert(data.d.ErrMessage);
                }
            });
        }

    }
}



/* utente: logout
- - - - - - - - - - - - - - - - - - - - */
function DoLogout()
{
    $.ajax({
        type: "POST",
        url: "/ws/wsUsers.asmx/Logout",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: "",
        dataType: "json",
        success: function (data)
        {
            window.location.reload();
        },
        error: function (data)
        {
            //self.status = self.status + "errore ";
            if (data.d != null)
                alert(data.d.ErrMessage);
        }
    });
}


/* ricerca vino: 5 steps
- - - - - - - - - - - - - - - - - - - - */
function SearchWine_GetNextStep(step, my)
{
    $("#hfStep" + step).val(my.id);
    gaTrackPage($("#ga_" + my.id).val());

    if (step == 5)
        $("#frmDataForSearch").submit();
    else
    {
        $.ajax({
            type: "POST",
            url: "/ws/wsGetContent.asmx/SearchWine_GetStep",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{iStep: " + ++step + "}",
            dataType: "json",
            success: function (data)
            {
                $("#hfCurrStep").val(step);
                $("#divStep .wrap").fadeOut(400, function ()
                {
                    $("#divStep .wrap").html(data.d.HTML);
                    $("#divStep .wrap").fadeIn(400);
                });
            },
            error: function (data)
            {
                //self.status = self.status + "errore ";
                if (data.d != null)
                    $this.find(".divStep").html(data.d.ErrMessage);
            }
        });
    }
}

function SearchGift_GetNextStep(step, my)
{
    $("#hfStep" + step).val(my.id);
    gaTrackPage($("#ga_" + my.id).val());

    if (step == 5)
        $("#frmDataForSearch").submit();
    else
    {
        $.ajax({
            type: "POST",
            url: "/ws/wsGetContent.asmx/SearchGift_GetStep",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{iStep: " + ++step + "}",
            dataType: "json",
            success: function (data)
            {
                $("#hfCurrStep").val(step);
                $("#divStep .wrap").fadeOut(400, function ()
                {
                    $("#divStep .wrap").html(data.d.HTML);
                    $("#divStep .wrap").fadeIn(400);
                });
            },
            error: function (data)
            {
                //self.status = self.status + "errore ";
                if (data.d != null)
                    $this.find(".divStep").html(data.d.ErrMessage);
            }
        });
    }
}


String.prototype.pad = function (l, s, t)
{
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};



/* winebottle zoom
- - - - - - - - - - - - - - - - - - - - */
function winebottleZoom()
{
    if ($("#winebottle_zoom").size())
    {
        $("#winebottle_zoom").appendTo($("#path"));
    }
}




function setFancyBox()
{
    if ($("a.iframe").size())
        $("a.iframe").fancybox({ "type": "iframe", "width": 350, "height": 200 });

    if ($("a.iFramePrivacy").size())
        $("a.iFramePrivacy").fancybox({ "type": "iframe", "width": 700, "height": 650 });

    if ($("a.iFrameBasket").size())
        $("a.iFrameBasket").fancybox({ "type": "iframe", "titleShow": false, "width": 850, "height": 550 });

    if ($("a.iFrameFooter").size())
        $("a.iFrameFooter").fancybox({ "type": "iframe", "titleShow": false, "width": 850, "height": 550 });

    if ($("a.iFramePresent").size())
        $("a.iFramePresent").fancybox({ "modal": true, "titleShow": false, "width": 600, "height": 300 });

    if ($("a.iFrameSmall").size())
        $("a.iFrameSmall").fancybox({ "titleShow": false, "width": 450, "height": 150 });

    if ($("a.iFrameSmall2").size())
        $("a.iFrameSmall2").fancybox({ "titleShow": false, "width": 650, "height": 350 });

    if ($("#linkPaeseSpedReq").size())
        $("#linkPaeseSpedReq").fancybox({ "overlayOpacity": 0.8, "overlayColor": "#000000" });

    if ($("#linkOtherCountryContacts").size())
        $("#linkOtherCountryContacts").fancybox({ "type": "iframe", "titleShow": false, "overlayOpacity": 0.8, "overlayColor": "#000000", "width": 450, "height": 250 });

    if ($("a.bottle_zoom").size())
        $("a.bottle_zoom").fancybox({ 'autoScale': false, 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 600, 'speedOut': 200, "titleShow": false, "margin": 60, "padding": 40, "overlayOpacity": 0.6, "overlayColor": "#000000" });

    if ($("#hrefPayments").size())
        $("#hrefPayments").fancybox({ 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 800, 'speedOut': 400, "titleShow": false, "margin": 60, "padding": 40, "overlayOpacity": 0.8, "overlayColor": "#000000" });

}


/* Go To Basket
- - - - - - - - - - - - - - - - - - - - */
function GoToBasket(destUrl)
{
    var retPage = window.location.href;
    window.location.href = destUrl;
}


/* Track Download
---------------------- */
function trackDownload(file)
{
    //alert('/downloads' + file);
    gaTrackPage('/downloads' + file);
}



/* Add Like Present
--------------------- */
function present_CloseFancy()
{
    $.fancybox.close();
}

function present_Open()
{
    $("#txtPresent").val($.trim($("#hfPresentText").val()));
    var currText = $.trim($("#hfPresentText").val());
    if (currText.length > 0)
        $("#btnPresent_Delete").show();
    else
        $("#btnPresent_Delete").hide();
}


function present_Delete()
{
    $("#txtPresent").val("");
    present_SetAndClose();
}

function present_SetAndClose()
{
    $("#hfPresentText").val($.trim($("#txtPresent").val()));
    present_Save();
    $.fancybox.close();
}

function present_Save(testo)
{
    $.ajax({
        type: "POST",
        url: "/ws/wsBasket.asmx/SavePresentNote",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: "{text: \"" + $("#hfPresentText").val() + "\"}",
        dataType: "json",
        success: function (data)
        {
        },
        error: function (data)
        {
        }
    });
}


function removeBad(strTemp)
{
    strTemp = strTemp.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g, "");
    return strTemp;
}


function TextArea_MaxLength(sender, MaxLen)
{
    return (sender.value.length <= MaxLen);
}


/*******************
GenericaValidate
*******************
function GenericaValidate(cssClass)
{
var ok = true;

$('.' + cssClass + ' input:visible').each(function ()
{
var myId = this.id;
var validator = myId + "Req";

if ($("#" + validator).size())
{
// è un campo obbligatorio
var type = $(this).attr("type");
if (type == "text")
{
var v = $("#" + myId).val();
if ($.trim(v).length <= 0)
{
$("#" + validator).show();
ok = false;
}
else
$("#" + validator).hide();
}
else if (type == "checkbox")
{
if ($("#" + myId + ":checked").size() == 0)
{
ok = false;
$("#" + validator).show();
}
else
$("#" + validator).hide();
}
}
});
return ok;
}
*/

function GenericaValidate(cssClass)
{
    var ok = true;

    $('.' + cssClass + ' input:visible').each(function ()
    {
        var myId = this.id;
        var validator = myId + "Req";

        if ($("#" + validator).size())
        {
            // è un campo obbligatorio
            var type = $(this).attr("type");
            if (type == "text")
            {
                var v = $("#" + myId).val();
                if ($.trim(v).length <= 0)
                {
                    $("#" + myId).addClass("validationErr");
                    ok = false;
                }
                else
                    $("#" + myId).removeClass("validationErr");
            }
            else if (type == "checkbox")
            {
                if ($("#" + myId + ":checked").size() == 0)
                {
                    ok = false;
                    $("#" + myId).parent().addClass("validationErr");
                }
                else
                    $("#" + myId).parent().removeClass("validationErr");
            }
        }
    });

    $('.' + cssClass + ' select:visible').each(function ()
    {
        var myId = this.id;
        var validator = myId + "Req";

        if ($("#" + validator).size())
        {
            var v = $("#" + myId).val();
            if (v == null || v == "-1" || v == "")
            {
                ok = false;
                $("#" + myId).addClass("validationErr");
            }
            else
                $("#" + myId).removeClass("validationErr");
        }
    });

    return ok;
}


function VaidateEmail(email_id)
{
    return ValidateEmail(email_id);
}

function ValidateEmail(email_id)
{
    var ok = false;
    //var idVal = "#" + email_id + "Req";
    var val = $("#" + email_id).val();
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    ok = reg.test(val);

    if (ok)
        $("#" + email_id).removeClass("validationErr");
    else
        $("#" + email_id).addClass("validationErr");
    /*
    if ($(idVal).size())
    {
    if (ok)
    $(idVal).hide();
    else
    $(idVal).show();
    }*/

    return ok;
}


/* window resize
- - - - - - - - - - - - - - - - - - - - */
$(window).resize(function ()
{
    selWidth();
    scrollNotes();
});


/* window load
- - - - - - - - - - - - - - - - - - - - */
$(window).load(function ()
{
    homepage_btn();
    scrollNotes();
});


/* window scroll
- - - - - - - - - - - - - - - - - - - - */
$(window).scroll(function ()
{
    scrollNotes();
});


/* - - - - - - - - - - - - - - - - - - - - 
INIT
- - - - - - - - - - - - - - - - - - - - */
$(function ()
{
    try
    { menu(); }
    catch (e) { }
    homepage_sel();
    tabs();
    also_like();
    vinoAjax();
    scrollNotes();
    setFancyBox();
    winebottleZoom();
    retrievePrezzoCorriere();
    freeSearch();

    if ($("#btnDWClubReg").size())
    {
        $("#txtRegDWClub").focus(function ()
        {
            if (!$("#hfTextSrc").size())
            {
                var temp = $("#txtRegDWClub").val();
                $("#txtRegDWClub").after("<input type='hidden' id='hfTextSrc' Value='" + temp + "' />");
            }
            $("#txtRegDWClub").val("");
        });

        $("#txtRegDWClub").blur(function ()
        {
            var v = $.trim($("#txtRegDWClub").val());
            if (v.length <= 0)
                $("#txtRegDWClub").val($("#hfTextSrc").val());
        });


        $("#btnDWClubReg").click(function ()
        {
            var v = $("#txtRegDWClub").val();

            if (!$("#hfTextSrc").size())
                v = "";
            else if (v == $("#hfTextSrc").val())
                v = "";

            preReg_HomePage(v);
        });
    }

    if ($("#hideDWCar").size())
    {
        if ($("#hideDWCar").val() == 1)
        {
            $("#txtDWCard").remove();
            $("#dwCard .lit_black_btn").remove();
            $("#spHideDwCard").show();
        }
    }

    // keyup change
    $(".sel_qta input").each(function ()
    {
        $(this).keyup(function ()
        {
            var myId = $(this).attr("id");
            var cod = $(this).attr("rel");
            var coId = myId.split("qta_")[1]; // coId = 469_SEL12144112
            coId = coId.split("_")[0];

            changeQta($(this).next().attr("id"), myId, coId, cod); //changeQta('qtaTemp_114', 'qta_114', 114);
        });
    });

    if ($("#currArea").size())
    {
        var coId = $("#currArea").val();
        $("#caMenu" + coId).addClass("on");
    }

    if ($("#hfPayMethods").size())
    {
        $(".metodoDiPagamento").hide();
        var v = $("#hfPayMethods").val();
        var s = v.split(",");
        for (var i in s)
        {
            if (s[i] != "")
                $("#" + s[i]).show();
        }
    }

    // RESET RICERCA a STEP
    // ( per history.back() )
    $(".ricerca input:radio").removeAttr("checked");
});



function freeSearch()
{
    try
    {

        $("#txtSearchBox").focusin(function ()
        {
            $("#txtSearchBox").val("");
        });

        $("#txtSearchBox").focusout(function ()
        {
            var txt = $.trim($("#txtSearchBox").val());
            if (txt.length <= 0)
            {
                var label = $("#txtSearchBoxLabel").val();
                $("#txtSearchBox").val(label);
            }
        });

        $("#txtSearchBox").autocomplete({
            source: function (request, response)
            {
                var term = request.term;
                $.ajax({
                    url: "/ws/wsGetContent.asmx/AutocompleteSearch",
                    data: "{ 'term': \"" + term + "\", 'top': 10 }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data)
                    {
                        response($.map(data.d, function (item)
                        {
                            return {
                                id: item.id,
                                label: item.label,
                                value: item.label
                            }
                            $(".ui-autocomplete").css("z-index", "105");
                        }))
                    }
                }
            );
            },
            minLength: 3,
            select: function (event, ui)
            {
            }
        }
    );

        if ($("#hrefSearch").size())
        {
            $("#hrefSearch").click(function ()
            {
                $("#txtSearchBoxVal").remove();
                var label = $("#txtSearchBoxLabel").val();
                var txt = $.trim($("#txtSearchBox").val());
                txt = txt.replace("'", " ");
                if (txt != label && txt.length > 0)
                {
                    var t = $("#frmFreeSearch").attr("action");
                    t = t + "?txt=" + txt;
                    $("#frmFreeSearch").attr("action", t);
                    $("#frmFreeSearch").submit();
                }
            });
        }
    }
    catch (e)
    {
    }
}




/*-----------------*/
//      LOGIN      //
/*-----------------*/

$(function ()
{
    //$("#validationErrMessage").hide();
    $(".validator").each(function ()
    {
        $(this).before("&nbsp;");
        $(this).hide();
    });
});


function ShowRetrievePassword()
{
    $("#divLinks").hide();
    $("#divLogin").hide(350);
    $("#divRetrievePassword").show(350);
}

function ShowLogin()
{
    $("#divLinks").hide();
    $("#divRetrievePassword").hide(350);
    $("#divLogin").show(350);
}


/* Controlla l'esistenza della EMail e fa il redirect alla Registrazione */
function CheckEmailAndRedirect(destUrl)
{
    var email = $.trim($("#txtEmailBeforeReg").val());

    if (email.length == 0)
        $("#sEmailBeforeRegVal").show();
    else
    {
        $.ajax({
            type: "POST",
            url: "/ws/wsUsers.asmx/CheckEmailIfExist",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{eMail: \"" + email + "\"}",
            dataType: "json",
            success: function (data)
            {
                if (!data.d.Status)
                    window.location.href = destUrl;
                else
                    $("#checkEmailMsg").html(data.d.HTML);
            },
            error: function (data)
            {
                self.status = self.status + "errore ";
                if (data.d != null)
                    alert(data.d.ErrMessage);
            }
        });
    }
}


/* LOGIN */
function DoLogin()
{
    if (ValidateLogin())
    {
        var Uname = $.trim($("#txtUsername").val());
        var Pwd = $.trim($("#txtPassword").val());

        $.ajax({
            type: "POST",
            url: "/ws/wsUsers.asmx/Login",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{Username: \"" + Uname + "\", Password: \"" + Pwd + "\"}",
            dataType: "json",
            success: function (data)
            {
                $("#login_ErrMsg").html(data.d.HTML);
                if (data.d.Status)
                {
                    parent.$(".iframe").replaceWith("<strong>" + data.d.Props.Title + "</strong>" + data.d.Props.Logout);
                    setTimeout("parent.$.fancybox.close();", 200);
                }
            },
            error: function (data)
            {
                self.status = self.status + "errore ";
                if (data.d != null)
                    alert(data.d.ErrMessage);
            }
        });
    }
}

/* LOGIN & REDIRECT */
function DoLoginAndRedirect(destUrl)
{
    if (ValidateLogin())
    {
        var Uname = $.trim($("#txtUsername").val());
        var Pwd = $.trim($("#txtPassword").val());

        $.ajax({
            type: "POST",
            url: "/ws/wsUsers.asmx/Login",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{Username: \"" + Uname + "\", Password: \"" + Pwd + "\"}",
            dataType: "json",
            success: function (data)
            {
                if (!data.d.Status)
                    $("#login_ErrMsg").html(data.d.HTML);
                else
                    window.location.href = destUrl;
            },
            error: function (data)
            {
                self.status = self.status + "errore ";
                if (data.d != null)
                    alert(data.d.ErrMessage);
            }
        });
    }
}



function ValidateLogin()
{
    var ok = true;
    var Uname = $.trim($("#txtUsername").val());
    var Pwd = $.trim($("#txtPassword").val());

    if (Uname.length == 0)
    {
        $("#sUnameValidator").show();
        ok = false;
    }
    else
        $("#sUnameValidator").hide();

    if (Pwd.length == 0)
    {
        $("#sPwdValidator").show();
        ok = false;
    }
    else
        $("#sPwdValidator").hide();

    return ok;
}


/* RECUPERO PASSWORD */
function doRetrievePassword()
{
    if (validateRetrievePassword())
    {
        var eMail = $.trim($("#txtEmail").val());

        $.ajax({
            type: "POST",
            url: "/ws/wsUsers.asmx/RetrievePassword",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{eMail: \"" + eMail + "\"}",
            dataType: "json",
            success: function (data)
            {
                $("#RetrPwd_ErrMsg").html(data.d.HTML);
            },
            error: function (data)
            {
                //self.status = self.status + "errore ";
                if (data.d != null)
                    alert(data.d.ErrMessage);
            }
        });
    }
}

function validateRetrievePassword()
{
    var ok = true;
    var eMail = $.trim($("#txtEmail").val());

    if (eMail.length == 0)
    {
        $("#sEmailValidator").show();
        ok = false;
    }
    return ok;
}


function goToRegistrazione(url)
{
    parent.$.fancybox.close();
    parent.window.location.href = url;
}



/*********************
RegistraUtente
**********************/
function RegistraUtente(method)
{
    var retValue = false;

    if (ValidateUser())
    {
        var userData = GetUtente();

        $.ajax({
            async: false,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/WS/wsUsers.asmx/" + method,
            data: JSON2.stringify(userData),
            dataType: "json",
            timeout: 5000,
            success:
                function (a)
                {
                    retValue = a.d.Status;
                    if (!retValue)
                        $("#sRegMessage").html(a.d.HTML);
                },
            error:
                function (e)
                {
                    $("#sRegMessage").html(a.d.HTML);
                    retValue = false;
                }
        });
    }
    return retValue;
}


/*********************
RegistraUtente
**********************/
function RegistraUtenteConNotifica(method)
{
    var retValue = false;
    $("#sRegMessage").html("");

    if (ValidateUser())
    {

        $("#sRegMessage").before("<img id='loading' src='/img/loading.gif' />");
        var userData = GetUtente();

        $.ajax({
            async: false,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/WS/wsUsers.asmx/" + method,
            data: JSON2.stringify(userData),
            dataType: "json",
            timeout: 5000,
            success:
                function (a)
                {
                    $("#loading").remove();
                    $("#sRegMessage").hide();
                    $("#sRegMessage").html(a.d.HTML);
                    $("#sRegMessage").fadeIn(800);
                },
            error:
                function (e)
                {
                    $("#loading").remove();
                    $("#sRegMessage").html("Service Error!");
                }
        });
    }
    return retValue;
}


/******************
CAMBIO PASSWORD
******************/
function CambiaPassword()
{
    $("#sRegMessage").html("");

    if (ValidaCambioPassword())
    {
        $("#sRegMessage").before("<img id='loading' src='/img/loading.gif' />");

        $.ajax({
            async: false,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/WS/wsUsers.asmx/ChangePassword",
            data: JSON2.stringify({ 'oldPwd': $.trim($("#txtOldPwd").val()), 'newPwd': $.trim($("#txtNewPwd1").val()) }),
            dataType: "json",
            timeout: 5000,
            success:
                function (a)
                {
                    $("#loading").remove();
                    $("#sRegMessage").hide();
                    $("#sRegMessage").html(a.d.HTML);
                    $("#sRegMessage").fadeIn(800);
                },
            error:
                function (e)
                {
                    $("#loading").remove();
                    $("#sRegMessage").html("Service Error!");
                }
        });
    }
}

function ValidaCambioPassword()
{
    var ok = true;
    $("#divPwdMustMatch").hide();

    if (!validateItem("txtOldPwd")) ok = false;
    if (!validateItem("txtNewPwd1")) ok = false;
    if (!validateItem("txtNewPwd2")) ok = false;

    var pwd1 = $.trim($("#txtNewPwd1").val());
    var pwd2 = $.trim($("#txtNewPwd2").val());

    if (pwd1 != pwd2)
    {
        ok = false;
        $("#txtNewPwd1Val").show();
        $("#txtNewPwd2Val").show();
        $("#divPwdMustMatch").fadeIn(800);
    }

    return ok;
}



/************************
DWC_RegistraUtente
*************************/
function DWC_RegistraUtente()
{
    if (ValidateUser())
    {
        var userData = GetUtente();

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/WS/wsUsers.asmx/Register",
            data: JSON2.stringify(userData),
            dataType: "json",
            timeout: 5000,
            success:
                function (a)
                {
                    $("#sRegMessage").html(a.d.HTML);
                    var content = "<div class='fancyLanding'>" + a.d.HTML + "</div>";

                    if (a.d.Status)
                        $.fancybox({ 'content': content, 'onClosed': fnRedir });
                    else
                        $.fancybox({ 'content': content });

                    if (a.d.Status)
                    {
                        var p = location.href.replace("http://www.designwine.com/", "");
                        gaTrackPage(p + "/?Iscrizione_Completata");
                    }
                },
            error:
                function (e)
                {
                    alert("Service error!");
                }
        });
    }
}


/*******************
GetUtente
********************/
function GetUtente()
{
    var newUser = {};

    $('.field_signup input').each(function ()
    {
        newUser[this.id] = this.value;
    });

    // campi 'speciali'
    newUser["Username"] = newUser["Email"];
    newUser["Privacy"] = $("#Privacy:checked").size() ? true : false;
    newUser["Newsletter"] = $("#Newsletter:checked").size() ? true : false;

    var nazione = $("#Nazione").val();
    newUser["Nazione"] = nazione;

    if (nazione = "114")
        newUser["Provincia"] = $("#Provincia").val();
    else
        newUser["ProvinciaTxt"] = $("#txtProvincia").val();

    return { 'Utente': newUser };
}

/*******************
ValidateUser
********************/
function ValidateUser()
{
    var ok = true;
    ok = GenericaValidate("field_signup")

    // length
    var pIva = $.trim($("#txtPIva").val());
    var cf = $.trim($("#txtCF").val());

    if (pIva.length <= 0 && cf.length > 0)
    {
        $("#txtPIvaReq").hide();
        ok = true;
    }
    else if (pIva.length > 0 && cf.length <= 0)
    {
        $("#txtCFReq").hide();
        ok = true;
    }

    if (!ValidateSelect("Nazione"))
        ok = false;

    if ($("#Provincia:visible").size())
    {
        if (!ValidateSelect("Provincia"))
            ok = false;
    }

    if ($("#txtProvincia:visible").size())
    {
        var v = $.trim($("#txtProvincia").val());
        if (v.length <= 0)
        {
            $("#ProvinciaReq").show();
            ok = false;
        }
        else
            $("#ProvinciaReq").hide();
    }

    if ($("#ddlNazione3:visible").size())
    {
        if (!ValidateSelect("ddlNazione3"))
            ok = false;
    }

    if ($("#ddlProvincia2:visible").size())
    {
        if (!ValidateSelect("ddlProvincia2"))
            ok = false;
    }

    if ($("#txtProvinciaSped:visible").size())
    {
        var v = $.trim($("#txtProvinciaSped").val());
        if (v.length <= 0)
        {
            $("#ddlProvincia2Req").show();
            ok = false;
        }
        else
            $("#ddlProvincia2Req").hide();
    }

    var pwd1 = $("#Password").val();
    var pwd2 = $("#Password2").val();

    if (pwd1 != null && pwd2 != null)
    {
        if (pwd1.length > 0 && pwd2.length > 0 && pwd1 != pwd2)
        {
            $("#PasswordEqual1").show();
            $("#PasswordEqual2").show();
            ok = false;
        }
    }

    return ok;
}



function ValidateSelect(id)
{
    var ok = true;

    if ($("#" + id).size())
    {
        var val = $("#" + id).val();
        if ((val == null) || (val != null && val == "-1") || (val != null && val == "-999") || (val != null && val == ""))
        {
            $("#" + id + "Req").show();
            ok = false;
        }
        else
            $("#" + id + "Req").hide();
    }
    return ok;
}


function manageRdbGendar(rdb)
{
    if (rdb.id == "SessoM")
        $("#SessoF").removeAttr("checked");
    else
        $("#SessoM").removeAttr("checked");
}


function NazioneChangedCheckOut(id, idProv)
{
    var v = NazioneChanged(id, idProv, "txtProvincia1");
    if (v != "114" && v != "95")
    {
        $("#chkShowAddress").attr("checked", "checked");
        ShowIndirizzo();
        setTimeout("$('#chkShowAddress').attr('disabled', 'disabled');", 400);
    }
    else
    {
        if ($("#chkShowAddress:disabled").size())
            $("#chkShowAddress").removeAttr("disabled");
    }

}


function NazioneChanged(id, idProv, txtProvId)
{
    if (idProv.length > 0)
    {
        var v = NazioneChanged2(id, idProv, "114", txtProvId);
        return v;
    }
    return false;
}

function NazioneChanged2(id, idProv, val, txtProvId)
{

    var value = $("#" + id).val();
    if (txtProvId == null || txtProvId == "")
        txtProvId = "txtProvincia";

    if (value != val)
    {
        $("#" + idProv).hide();
        $("#" + idProv).after("<input id=\"" + txtProvId + "\" type=\"text\" />");
    }
    else
    {
        $("#" + idProv).show();
        $("#" + txtProvId).remove();
    }

    return value;
}


function myNazioneChanged(idNaz, idProv, idTxtProv)
{
    return;
    var currVal = $("#" + idNaz).val();
    if (currVal == "114")
    {
        $("#" + idTxtProv).hide();
        $("#" + idProv).show();
    }
    else
    {
        $("#" + idProv).hide();
        $("#" + idTxtProv).show();
    }
}


function preReg_HomePage(e_mail)
{
    var url = $("#hfRedirectToClub").val();
    var email = $.trim(e_mail);

    if (email.length > 0)
    {
        $("#preReg_Loading").show();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/WS/wsUsers.asmx/CheckEmailIfExist",
            data: JSON2.stringify({ 'eMail': email }),
            dataType: "json",
            timeout: 5000,
            success:
                function (a)
                {
                    $("#preReg_Loading").hide();
                    if (a.d.Status)
                        location.href = url;
                    else
                    {
                        $("#preRegMsg").remove();

                        val = "<div class='fancyLanding'>" + a.d.HTML + "</div>";
                        $.fancybox({ 'content': val, 'onClosed': fnRedir });
                        // $("#hfRedirectToClub").before("<span id=\"preRegMsg\">" + a.d.HTML + "</span>")
                    }
                },
            error:
                function (e)
                {
                    $("#preReg_Loading").hide();
                }
        });
    }
    else
        location.href = url;
}

function fnRedir()
{
    location.href = "/";
}
