﻿var ds = JSON.parse($("#hdds").val());
var sessionCookieId = $.cookies.get("UserCookieId");
var topSearchBar = $("#pnlTopSearchBar");
var txtCtrl = null;
var promotion = new specialPromotion();
var selectedDivIndex = -1;
var maxDivIndex = -1;
var consts = {
    rColor: [1, 9],
    rClarity: [1, 8],
    rPolish: [1, 5],
    rSymm: [1, 5],
    rCut: [1, 5],
    rFluor: [0, 3],
    rTable: [0, 100],
    rDepth: [0, 100],
    rCrt: [0, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.00, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.00, 3.5, 4.00, 4.5, 5.00, 5.5, 6.00, 6.5, 7.00, 7.5, 8.00, 8.5, 9.00, 9.5, 10.00],
    rPrc: [0, 1000, 2000, 5000, 7000, 10000, 12000, 15000, 17000, 20000, 25000, 30000, 40000, 50000, 70000, 150000, 300000, 500000, 1000000, 1500000]
};

JSON.clone = function (obj) {
    return JSON.parse(JSON.stringify(obj));
};

function specialPromotion() {
    var p = $("#pnlPromoDiscount");
    var d = $("#divPromoDiscountDialog");

    p.click(function () {
        d.show();
    });

    this.panelShow = function () {
        p.show();
    };
    this.dialogShow = function () {
        d.show();
    };
    this.dialogHide = function () {
        d.hide();
    };
    this.dialogObj = function () {
        return d;
    };
}

function applyHeaderJs() {
    $(".menuItem")
       .mouseover(function () {
           $(this)
            .find("div").addClass("menuTitle").end()
            .find("ul").show();
       })
       .mouseout(function () {
           $(this)
            .find("div").removeClass("menuTitle").end()
            .find("ul").hide();
       })
       .find("a").click(function () {
           gTrack("top|" + $(this).attr("ga"));
       });
}

function validateEmail(mail) {
    var emailPattern = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
    return emailPattern.test(mail);
}

function applySubscriber() {
    var btn = $("#btnSubscribeEmail");
    var txt = $("#txtNewsletterEmail");
    btn.click(function () {
        //        if (typeof (Page_ClientValidate) == "function") {
        //            Page_ClientValidate("emailNewsletter");
        //            if (Page_IsValid) {
        var email = $.trim(txt.val());
        if (email != "" && validateEmail(email))
            $.ajax({
                type: "POST",
                url: "/services/subscribersservice.asmx/subscribe",
                data: "{'email':'" + email + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    window.location = ("/thankyou.aspx?s=1&email=" + email);
                }
            });
        //}
        //}
    });
    txt.keypress(function (event) {
        if (event.keyCode == "13") {
            event.preventDefault();
            btn.click();
        }
    });
}

function applyBottomJs() {
    $(".socpnl").find("a[ga]").click(function () {
        gTrack("footer|" + $(this).attr("ga"));
    });
}

function applyUserAccauntJs() {
    var list = $("#ulUserProfileList");
    $("#divUserProfile")
        .mouseover(function () {
            list.show();
        })
        .mouseout(function () {
            list.hide();
        });
}

function gTrack(title) {
    try {
        _gaq.push(["_trackEvent", title, "clicked"]);
    }
    catch (e) { }
}

function popUp(URL) {
    var day = new Date();
    var id = day.getTime();
    eval("page" + id + " = window.open('" + URL + "', '" + id + "', 'toolbar=0,scrollbars=0,location=1,statusbar=1,menubar=0,resizable=0,width=460,height=340,left=790,top=475');");
}

function callSpecialDiscountService() {
    if (sessionCookieId != null) {
        $.ajax({
            url: "/services/services.svc/getavailablediscount",
            data: { userId: sessionCookieId, total: (wishlistTotal + shoppingCartSubTotal) },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (result) {
                onSpecialDiscountDisplayed(result.d);
            }
        });
    }
    return;
}

function onSpecialDiscountDisplayed(promo) {
    try {
        var cookieName = "displayPromoDiscountNotAtFirst";
        if (promo != null) {
            $.get('/controls/jtemplates/_tmpl.special-promo.html', function (templates) {
                $('body').append(templates);
            })
            .success(function () {
                $("#tmplSpecialPromo").tmpl(promo).appendTo(promotion.dialogObj());
                promotion.panelShow();
                //                if (typeof(isShoopingCartPage) !== "undefined") {
                //                    $("#pnlApplySpecial").show();
                //                }
                if ($.cookies.get(cookieName) == null) {
                    $.cookies.set(cookieName, "true");
                    promotion.dialogShow();
                    callUserEventService();
                }
            });
        }
        else {
            $.cookies.del(cookieName);
        }
    }
    catch (e) { }
    return;
}

function closePromoDlg() {
    if (typeof (isShoopingCartPage) !== "undefined") {
        window.location.reload();
    }
    promotion.dialogHide();
    return;
}

function callUserEventService() {
    if (sessionCookieId != null) {
        $.ajax({
            type: "POST",
            url: "/services/wfservices.asmx/writeuseraction",
            data: "{'userId': '" + sessionCookieId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
    }
    return;
}

function runDiamondsSearch() {
    setJsonToCookieWithExpires("diamondsearchsettings", {
        ctmin: ds.ctmin,
        ctmax: ds.ctmax,
        colormin: ds.colormin,
        colormax: ds.colormax,
        claritymin: ds.claritymin,
        claritymax: ds.claritymax,
        grademin: ds.grademin,
        grademax: ds.grademax,
        shape: ds.shape,
        size: ds.size,
        page: 1,
        pricemin: ds.pricemin,
        pricemax: ds.pricemax
    });
    window.location.href = "/loose-diamonds/search.aspx";
}

function promotionPrincessSearch(val) {
    ds.shape = parseInt(val);
    runDiamondsSearch();
}

function setDivZindex() {
    var zIndexNumber = 1500;
    $('div').filter(function () {
        var obj = $(this);
        var objId = obj.attr("id");
        return (typeof (objId) != 'undefined' && objId.indexOf("fancy") == -1) && !obj.hasClass("ui-dialog");
    }).each(function () {
        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    });
    return;
}

function getInfoBlock() {
    var infoBlock = "";
    if (shoppingCartSubTotal > 0 || wishlistTotal > 0)
        infoBlock = "C: $" + shoppingCartSubTotal + " - " + "W: $" + wishlistTotal;
    return infoBlock;
}

function getSitesearchJson(method, text) {
    return $.ajax({
        type: "POST",
        url: "/services/sitesearch.asmx/" + method,
        data: "{'value': '" + text + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

function bindTopSearchEvents() {
    var predefinedText = "search for diamonds, rings and jewelry";
    var currentTime;
    var compiled = false;
    var resultsDivVisible = false;

    txtCtrl
        .focusin(function () {
            var obj = $(this);
            if ($.trim(obj.val()) == predefinedText) {
                obj.val("");
            }
            return;
        })
        .focusout(function () {
            var obj = $(this);
            if ($.trim(obj.val()) == "") {
                obj.val(predefinedText);
            }
            return;
        })
        .keypress(function (event) {
            if (event.keyCode == 27) { // ie and ff
                onCancelClick($(this));
            }
            else if (event.keyCode == 13) {
                if (selectedDivIndex != -1) {
                    var obj = topSearchBar.find("div[index='" + selectedDivIndex + "']");
                    var selDivLink = obj.find("div[link]");
                    if ((selectedDivIndex == 0 || selectedDivIndex == 1) && selDivLink.length > 0) {
                        window.location.href = selDivLink.attr("link");
                    }
                    else {
                        gotoSearch(obj.attr("entity"), $.trim($(this).val()));
                    }
                }
                event.preventDefault();
            }
            return;
        })
        .keyup(function (event) {
            if (event.keyCode == 27) { // chrome and ff
                onCancelClick($(this));
            }
            else if (event.keyCode == 8 || event.keyCode == 32 || event.keyCode == 46 || (event.keyCode >= 48 && event.keyCode <= 90) ||
                    (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 109 || event.keyCode == 110) {
                var obj = $(this);
                if (obj.val().length > 1 && obj.val() != predefinedText) {

                    resultsDivVisible = true;
                    currentTime = (new Date()).getTime();
                    setTimeout(function () {

                        if ((new Date()).getTime() - 225 >= currentTime) {

                            if (!compiled) {
                                compiled = true;
                                setAndCompile();
                            }
                            callTopSearchServices(obj.val());
                        }

                    }, 250);
                }
                else {
                    resultsDivVisible = false;
                    topSearchBar.hide();
                }
            }
            else if (event.keyCode == 38 && resultsDivVisible) {
                if (selectedDivIndex > -1)
                    selectedDivIndex--;

                selectItemRow();
            }
            else if (event.keyCode == 40 && resultsDivVisible) {
                if (selectedDivIndex < maxDivIndex)
                    selectedDivIndex++;

                selectItemRow();
            }
            return;
        })
        .val("search for diamonds, rings and jewelry")
        .bind("paste", function () {
            if (!compiled) {
                compiled = true;
                setAndCompile();
            }
            setTimeout(callTopSearchByPaste, 250);
        });
}

function setAndCompile() {
    $.get('/controls/jtemplates/_tmpl.top-search.html', function (templates) {
        $('body').append(templates);
    })
    .success(function () {
        $("#tmplTopSearchBar").template("tmplSearchBar");
    });
}

function onCancelClick(obj) {
    topSearchBar.hide();
    obj
        .val("")
        .focus();
    selectedDivIndex = -1;
}

function selectItemRow() {
    topSearchBar.find("div[index]").each(function () {
        var obj = $(this);
        obj.removeClass("rowSel");
        if (parseInt(obj.attr("index")) == selectedDivIndex) {
            obj.addClass("rowSel");
        }
    });
}

function callTopSearchByPaste() {
    callTopSearchServices($.trim($("#txtTopSearch").val()));
}

function gotoSearch(entity, text) {
    var data = {
        index: entity,
        text: text,
        page: 1
    };
    setJsonToCookie("topSearchCookie", data);
    window.location.href = "/search.aspx";
}

function gotoSearchByIndex(ctrlId, entity) {
    $(ctrlId).keypress(function (event) {
        var text = $.trim($(this).val());
        if (event.keyCode == 13 && text != "") {
            gotoSearch(entity, text);
            event.preventDefault();
        }
    });
}

function setJsonToCookieWithExpires(cookieName, jsonData) {
    if ($.cookies.get(cookieName) != null) {
        $.cookies.del(cookieName);
    }
    var currentTime = new Date();
    $.cookies.set(cookieName, JSON.stringify(jsonData), { expiresAt: new Date(currentTime.getFullYear() + 1, currentTime.getMonth(), currentTime.getDate()) });
}

function setJsonToCookie(cookieName, jsonData) {
    if ($.cookies.get(cookieName) != null) {
        $.cookies.del(cookieName);
    }
    $.cookies.set(cookieName, JSON.stringify(jsonData));
}

function callTopSearchServices(text) {
    selectedDivIndex = -1;
    getSitesearchJson("gettopsearch", text).done(function (data) {
        var index = 0;
        topSearchBar
            .empty()
            .html($.tmpl("tmplSearchBar", data.d))
            .find(".sr")
                .each(function () {
                    $(this).attr("index", index++);
                })
                .hover(function () {
                    selectedDivIndex = parseInt($(this).attr("index"));
                    selectItemRow();
                }, function () {
                    selectedDivIndex = -1;
                    selectItemRow();
                })
                .click(function () {
                    var obj = $(this);
                    var selDivLink = obj.find("div[link]");

                    if ((selectedDivIndex == 0 || selectedDivIndex == 1) && selDivLink.length > 0) {
                        window.location.href = selDivLink.attr("link");
                    }
                    else {
                        gotoSearch(obj.attr("entity"), $.trim(txtCtrl.val()));
                    }
                    return;
                })
            .end()
            .find("#hlTopClose").click(function () {
                onCancelClick(txtCtrl);
            }).end()
            .show();

        maxDivIndex = index - 1;
    });
}

function searchJewelryPage(wredirect) {
    if ($.cookies.get("sidebuilderreqdiamond") == null) {
        $.cookies.set("sidebuilderreqdiamond", "true");
    }

    switch (wredirect) {
        case "r": window.location = "/engagement-rings/search.htm";
        case "e": window.location = "/diamond-earrings/search.htm";
    }
}

function showhighlightshoppingcart() {
    var id = $.cookies.get("lastShoppingCartItemID");
    if (id == null) return;
    $.cookies.del("lastShoppingCartItemID");

    var $tr = $('#sidebar .content_srb tr').filter(function () {
        return $(this).html().indexOf(id) > 0;
    });

    var clrOrig = $tr.css('background-color');
    var clrBlnk = $tr.parent().parent().prev().css('background-color');

    for (var i = 0; i < 4; i++) {
        $tr
            .animate({ opacity: 0.9 }, "slow", function () { $(this).css({ 'background-color': clrBlnk }); })
            .animate({ opacity: 1 }, "slow", function () { $(this).css({ 'background-color': clrOrig }); });
    }
}

function sbdelTrack() {
    $("#sidebar-builders .remove").bind("click", function () {
        gTrack("DeleteFromCart|sidebar");
    });
}

function looseDiamondSearch(shape, category) {
    ds.shape = shape;
    ds.type = category;
    runDiamondsSearch();
}

function pnlFeedback_restoreBackground(ids) {
    var items = $(ids);
    items.css("background-color", "#FDF4D4");
    items.val("");
}


function pnlFeedback_checkFields(ids) {
    var rez = true;

    $.each(ids.split(','), function (i, v) {
        var item = $(v);
        var itemval = $.trim(item.val());
        if (itemval === '' || itemval.indexOf("Required field") === 0) {
            item.css('background-color', '#F56F6F');
            if (itemval === '') item.val("Required field");
            item.bind("click", function () {
                var itemvaln = $.trim(item.val());
                if (itemvaln === '' || itemvaln.indexOf("Required field") === 0) {
                    pnlFeedback_restoreBackground(v);
                }
            });
            rez = false;
        }
        else {
            item.unbind("click");
        }
    });
    
    return rez;
}

var pnlFeedback_onOpenDlg = function () {
    var dialogitem = $(this);    
    var $dialog = dialogitem.parents(".ui-dialog:first");

    $('.step_1', $dialog).show();
    $('.step_2', $dialog).hide();

    $('span.ui-dialog-title', $dialog).css({
        'display': 'block',
        'width': '100%',
        'margin': '0',
        'text-align': 'center',
        'padding': ' 0 auto'
    });

    if (dialogitem.attr('id') !== 'pnlSendRequestGSR')
        $(':input', $dialog).val('');

    $(':input', $dialog).css({ 'background-color': '#fdf4d4', 'border': '1px solid #705a0c' });
    $dialog.css({ 'background-color': '#161003', 'border': '2px solid #f4eeb9' });
    var $titlebar = dialogitem.parents(".ui-dialog:first").find(".ui-dialog-titlebar");
    $titlebar.css({ 'background': 'none', 'border': 'none', 'color': '#fbe88e', 'font-size': '16px' });
    $('span', $titlebar).css({ 'float': 'none' });
    $('#tellusdialog', $titlebar).css({ 'height': '225px' });
    $titlebar.show();

    $('a.ui-dialog-titlebar-close', $titlebar)
    .css({
        'background-image': 'url("/images/jquery_ui_add/close.png")'
        , 'background-position': '2px 2px'
        , 'background-repeat': 'no-repeat'
        , 'border': 'none'
        , 'padding': '0'
    }).html('').show();

};

function closeFeedbackDialog(currentpanel) {
    currentpanel.find(".close-feedback")
        .bind("click", function () {
            currentpanel.dialog("close");
        });
}

function workingBottomFeedback() {
    var $panel = $('#pnlBottomFeedback');

    closeFeedbackDialog($panel);

    $('.send-feedback', $panel).click(function () {

        var email = $("#txtEmailBottomFeedback").val();        
        if (!pnlFeedback_checkFields('#txtMessageBottomFeedback, #txtNameBottomFeedback') || ($.trim(email) !== "" && !validateEmail(email))) return false;
        var spage = document.URL;
        var sdata = "{ name:'" + $('#txtNameBottomFeedback').val() + "',email:'" + email + "',message:'" + $('#txtMessageBottomFeedback').val() + "',page:'" + spage + "'}";
        $.ajax({
            type: "POST",
            url: "/services/wfservices.asmx/putfeedback",
            data: sdata,
            contentType: "application/json",
            dataType: "json",
            success: function () {
                $('.step_1', $panel).hide();
                $('.step_2', $panel).show();
            }
        });
        return false;
    });

    $('#bottomlinkSendRequest').bind("click", function () {
        var itemleft = $(window).width() - 430;
        var itemtop = $(this).offset().top - 300 - $(window).scrollTop();
        $panel.aspdialog({
            title: "<h5 style='display: inline;width: 80%;'>Give us your feedback</h5>",
            width: 400,
            draggable: true,
            closeOnEscape: true,
            modal: false,
            position: [itemleft, itemtop],
            open: pnlFeedback_onOpenDlg
        });
        return false;
    });
}

$(function () {
    setDivZindex();
    $(".updnValidatorCallout").css("z-index", "2000");
    $("#divDialogBuyDiamond").css("z-index", "2000");

    applyHeaderJs();

    if (typeof (isSearch) === "undefined") {
        txtCtrl = $("#txtTopSearch");
        bindTopSearchEvents();
        topSearchBar.css("z-index", "2000");
    }

    callSpecialDiscountService();

    showhighlightshoppingcart();
    applyBottomJs();
    applySubscriber();
    sbdelTrack();

    applyUserAccauntJs();

    workingBottomFeedback();
});

