﻿var loadingTimeout = false;
var overCartLink = false;
var overCartHover = false;
var overProductHover = false;
var overProduct = false;
var productHoverProduct;

function showFeedback(messageType, message) {
    feedback = $("#ajax-feedback");
    feedback.removeClass("ajax-loading");
    feedback.addClass("ajax-" + messageType);
    feedback.html(message);
    feedback.fadeIn("fast");
    setTimeout("ajaxHideFeedback()", 5000);
}

function ajax(requestPath, parameters, loadingMsg, callback) {
    $("#ajax-feedback").html((typeof (loadingMsg) == "undefined" || !loadingMsg) ? "Please wait..." : loadingMsg);
    loadingTimeout = setTimeout("ajaxShowLoading()", 500);

    var request = $.post(requestPath, parameters, function(data) {
        var feedback;
        if (loadingTimeout) {
            clearTimeout(loadingTimeout);
            loadingTimeout = false;
        }
        var contentType = request.getResponseHeader("Content-type");
        if (contentType && contentType.indexOf("application/json") == 0) {
            data = eval("(" + data + ")");
        }
        if (typeof (callback) != "undefined" && callback != null) {
            callback(data, parameters);
        }
        if (typeof (data.message) != "undefined") {
            showFeedback(data.messageType, data.message);
        }
        else {
            $("#ajax-feedback").fadeOut("fast");
        }
    });
}

function partial(requestPath, parameters, loadingMsg, callback, container, replace) {
    $("#ajax-feedback").html((typeof (loadingMsg) == "undefined" || !loadingMsg) ? "Please wait..." : loadingMsg);
    loadingTimeout = setTimeout("ajaxShowLoading()", 500);

    var request = $.post(requestPath, parameters, function(data) {
        var feedback;
        if (loadingTimeout) {
            clearTimeout(loadingTimeout);
            loadingTimeout = false;
        }
        var contentType = request.getResponseHeader("Content-type");
        if (contentType && contentType.indexOf("application/json") == 0) {
            data = eval("(" + data + ")");
        }
        if (typeof (data) == "object" && typeof (data.message) != "undefined") {
            showFeedback(data.messageType, data.message);
        }
        else {
            if (replace)
                $("#" + container).replaceWith(data);
            else
                $("#" + container).html(data);
            $("#ajax-feedback").fadeOut("fast");

            if (typeof (callback) != "undefined" && callback) {
                callback(data, parameters);
            }
        }
    }, "html");
}

function popupPage(url, title, width, height) {
    if (typeof (width) == "undefined") {
        width = Settings.PopupDefaultWidth;
    }
    if (typeof (height) == "undefined") {
        height = Settings.PopupDefaultHeight;
    }
    $('#page-dialog').dialog("destroy");
    $('#page-dialog').dialog({ height: height, modal: true, width: width }).
        dialog('option', 'title', 'Please wait...').
        dialog('open').html('');
    var request = $.post(url, {}, function(data) {
        var contentType = request.getResponseHeader("Content-type");
        if (contentType && contentType.indexOf("application/json") == 0) {
            data = eval("(" + data + ")");

            if (typeof (data) == "object" && typeof (data.message) != "undefined") {
                $('#page-dialog').dialog("close");
                showFeedback(data.messageType, data.message);
                return;
            }
        }
        else {
            data = { title: ((typeof (title) != "undefined") ? title : document.title), content: data };
        }
        $('#page-dialog').dialog('option', 'title', data.title);
        $('#page-dialog').html(data.content);
    }, "html");
}

function popupContent(contentName) {
    popupPage("/content/raw/" + contentName);
}

function popupProductPage(productID) {
    popupPage('/product/popup/' + productID, 'Viewing Product', Settings.PopupProductWidth, Settings.PopupProductHeight);
}

function emailSignup(listName, emailAddress) {
    $('#page-dialog').dialog({ height: Settings.PopupDefaultHeight, modal: true, width: Settings.PopupDefaultWidth }).
        dialog('option', 'title', 'Please wait...').
        dialog('open').html('');
    var request = $.post("/email/signup", { list: listName, email: emailAddress }, function(data) {
        var contentType = request.getResponseHeader("Content-type");
        if (contentType && contentType.indexOf("application/json") == 0) {
            data = eval("(" + data + ")");

            showFeedback(data.messageType, data.message);
            $('#page-dialog').dialog("close");
        }
        else {
            $('#page-dialog').dialog('option', 'title', 'Email Signup');
            $('#page-dialog').html(data);
        }        
    }, "html");    
}

function ajaxShowLoading() {
    if (!loadingTimeout) {
        return;
    }
    var feedback = $("#ajax-feedback");
    feedback.addClass("ajax-loading");
    feedback.removeClass("ajax-info");
    feedback.removeClass("ajax-warning");
    feedback.removeClass("ajax-error");
    feedback.fadeIn("fast");
}

function ajaxHideFeedback() {
    $("#ajax-feedback").fadeOut("slow");
}

$().ready(function() {
    //$.getJSON("/feedback", function(data) {
    //    if (typeof (data.message) != "undefined" && data.message != null && data.message.length > 0)
    //        showFeedback(data.messageType, data.message);
    //});

    $("#cart-hover").hover(
        function() {
            overCartLink = true;
            var h = $("#cart-popup").addClass("loading");
            var r = $.get("/cart/hover", null, function(data) {
                var feedback;
                var contentType = r.getResponseHeader("Content-type");
                if (contentType && contentType.indexOf("application/json") == 0) {
                    data = eval("(" + data + ")");
                }
                if (typeof (data) == "object" && typeof (data.message) != "undefined") {
                    showFeedback(data.messageType, data.message);
                }
                else {
                    h.html(data);
                }
                h.removeClass("loading");
            }, "html");
            c = $("#cart-hover");
            h.css({ left: (c.offset().left + c.width()) - 200, top: c.offset().top + c.height() }).fadeIn("fast");
        },
        function() {
            overCartLink = false;
            setTimeout("cartHoverOut()", 500);
        }
    );

    $("#cart-popup").hover(
        function() {
            overCartHover = true;
        },
        function() {
            overCartHover = false;
            setTimeout("cartHoverOut()", 500);
        }
    );

    $("#product-hover").hover(
        function() {
            overProductHover = true;
        },
        function() {
            overProductHover = false;
            setTimeout("productHoverFadeOut()", 500);
        }
    );

    $("#search-query").focus(
        function() {
            if (this.value == "Search Keyword") {
                this.value = "";
            }
        }
    );
	
	$("#email-signup").focus(
        function() {
            if (this.value == "Enter Email Address") {
                this.value = "";
            }
        }
    );

    $("#ajax-feedback").ajaxError(function(event, request, settings) {
        showFeedback("error", "An error occurred while performing the request.");
        $('#page-dialog').dialog("close");
    });
});

//$(window).load(function() {
//    refreshCartItemCount();
//});

function cartHoverOut() {
    if (!overCartLink && !overCartHover)
        $("#cart-popup").fadeOut("slow");
}

function relatedVariantSelect(variantSelector, productOid) {
    if (typeof(variantSelector) == "string") {
        variantSelector = document.getElementById(variantSelector);
    }

    var params = $("select", variantSelector).serializeArray();
    
    params.push({ name: 'product', value: productOid });
    
    partial("/product/relatedvariantselect", params, null, function () {
        if ($("#" + variantSelector.id + "-variant").val()) {
            $(".btn_addtobag_small", variantSelector.parentNode).css({ display: '' });
        }
    }, variantSelector.id, false);
}

function addToCart(variantOid, isGift) {
    if (typeof (variantOid) == "undefined" || variantOid == null) {
        variantOid = $("#variantID").val();
        if (variantOid == "_noColor") {
            alert("Select a color before clicking " + Strings.AddToCart + ".");
            return;
        }
        else if (variantOid == "_noSize") {
            alert("Select a size before clicking " + Strings.AddToCart + ".");
            return;
        }
        else if (variantOid == "_noWidth") {
            alert("Select a width before clicking " + Strings.AddToCart + ".");
            return;
        }
        else if (typeof (variantOid) == "undefined" || variantOid == null || variantOid == "") {
            alert("This product cannot be purchased at this time.");
            return;
        }
    }
    
    if (typeof(isGift) == "undefined") {
        isGift = false;
    }
    
    ajax('/cart/add-ajax/add', { oid: variantOid, isGift: isGift, cartItem: $("#CartItem").val() }, null, function(data) {
        if (typeof (data) == "string") {
            $('#page-dialog').dialog("destroy");
            $('#page-dialog').dialog({ height: 250, modal: true, width: 375 }).
                dialog('option', 'title', 'Added to ' + Strings.ShoppingCart).
                dialog('open').html(data);
        }
        if (typeof (data) == "string" || data.messageType == "info") {
        if (typeof (onCartItemAdded) != "undefined") {
            onCartItemAdded(data);
        }
        refreshCartItemCount();
        }
    });
}

function refreshCartItemCount() {
    if ($("#cart-item-count").length > 0) {
        ajax('/cart/itemCount', {}, null, function(data) {
            if (typeof (data) == "string") {
                $("#cart-item-count").html(data);
            }
        });
    }
}

function largerView(oid, color) {
    $('#page-dialog').dialog("destroy");
    $('#page-dialog').dialog({ height: 650, modal: true, width: 702 }).
        dialog('option', 'title', 'Please wait...').
        dialog('open').html('');
    var request = $.post('/product/largerView', { product: oid, variantColor: color },
        function(data) {
            var contentType = request.getResponseHeader("Content-type");
            if (contentType && contentType.indexOf("application/json") == 0) {
                data = eval("(" + data + ")");

                showFeedback(data.messageType, data.message);
                $('#page-dialog').dialog("close");
            }
            else {
                $('#page-dialog').dialog('option', 'title', Strings.LargerView);
                $('#page-dialog').html(data);
            }       
        }, "html");
}

function selectLargerImage(tag, product, color, alternate) {
    $(".larger-image-views .larger-image-view a").removeClass("selected");
    $(tag).addClass("selected");

    ajax("/product/productImage", {
        product: product,
        variantColor: color,
        alternate: alternate
        }, null, function(data) {
            if (data.largerImage != null) {
                $("#larger-image-tag img").attr("src", data.largerImage);
                $("#larger-image-tag img").attr("title", "");
            }
        });
}

function back() {
    window.history.go(-1);
}

function closePopup() {
    $('#page-dialog').dialog("close");
}

function productHover(products, idOrX, Y) {
    overProduct = true;
    if ($("#product-hover").css("display") == "block" && productHoverProduct == products) {
        return;
    }
    productHoverProduct = products;
    var x2, y2, h = $("#product-hover").addClass("loading");
    if (typeof(products) == "string") {
        products = [products];
    }
    var r = $.post("/product/data", { productID: products }, function(data) {
        var contentType = r.getResponseHeader("Content-type");
        if (contentType && contentType.indexOf("application/json") == 0) {
            data = eval("(" + data + ")");
        }
        if (typeof (data) == "object" && typeof (data.message) != "undefined") {
            showFeedback(data.messageType, data.message);
        }
        else {
            h.html(data);
            if (typeof (Y) == "undefined") {
                var obj = $("#" + idOrX);
                var f = obj.offset();
                h.css({ left: ((obj.width() - h.width()) / 2) + f.left, top: ((obj.height() - h.height()) / 2) + f.top });
            }
        }
        h.removeClass("loading");
    }, "html");
    if (typeof (Y) == "undefined") {
        var obj = $("#" + idOrX);
        var f = obj.offset();

        x2 = ((obj.width() - h.width()) / 2) + f.left;
        y2 = ((obj.height() - h.height()) / 2) + f.top;
    }
    else {
        x2 = idOrX;
        y2 = Y;
    }
    h.css({ left: x2, top: y2 }).html("Loading...").fadeIn("fast");
}

function productHoverOut() {
    overProduct = false;
    setTimeout("productHoverFadeOut()", 500);
}

function productHoverFadeOut() {
    if (!overProductHover && !overProduct)
        $("#product-hover").fadeOut("slow");
}

//------------------------------------------------------------------------
// Product specific methods
//------------------------------------------------------------------------
function switchTab(id) {
    $("#product .desc-features .select-bar a").removeClass("active");
    $("#product .desc-features .tab-content").css("display", "none");
    $("#" + id + "-tab").addClass("active");
    $("#" + id + "-content").css("display", "block");
}
function prodChangeImage(productOid, newColor, alternateNum) {
    ajax("/product/productImage",
    {
        product: productOid,
        variantColor: newColor,
        alternate: (typeof (alternateNum) != "undefined" ? alternateNum : 0)
    }, null, function(data) {
        productCurrentProduct = productOid;
        productCurrentColor = newColor;
        if ($("#magnifier_space").length > 0) {
            if (data.main != null && data.main.length > 0) {
                init_loading_sequence(data.main, (data.zoom != null ? data.zoom : data.zoomalt));
            }
        }
        else {
            if (data.main != null && data.main.length > 0) {
                $("#product-image img").attr("src", data.main);
            }
        }
        $("#picture-zoom").css("background-image", "url(" + data.zoomalt + ")");
    });
}
function prodSelectionChange(productOid) {
    partial("/product/variantSelect",
    {
        product: productOid,
        variantColor: $("#variantColor").val(),
        variantSize: $("#variantSize").val(),
        variantWidth: $("#variantWidth").val()
    }, null, null, "product-variant-selector");

    if ($("#variantColor").val().length > 0) {
        prodChangeImage(productOid, $("#variantColor").val());
    }
}
function prodSelectSwatch(productOid, a, oid, alternate) {
    $(".swatches li a").removeClass("selected");
    $(a).addClass("selected");

    if (oid.length > 0) {
        partial("/product/variantSelect",
        {
            product: productOid,
            variantColor: oid,
            variantSize: "",
            variantWidth: ""
        }, null, function(data) {
            //var selector = $("#variantColor")[0];
            //$("#product .details .selected-color .label").html(selector.options[selector.selectedIndex].text);
            $("#color-label").html($("#ColorName").val());
        }, "product-variant-selector");
    }
    prodChangeImage(productOid, oid, alternate);
}

//------------------------------------------------------------------------
// Survey form specific methods
//------------------------------------------------------------------------
function setValueByName(name, value) {
    var field = $("*[name='" + name + "']");
    if (field.length > 0) {
        if (field[0].tagName == "input") {
            if (field[0].type == "radio") {
                field.each(function() {
                    if (this.value == value) {
                        this.checked = true;
                    }
                });
                return;
            }
            else if (field[0].type == "checkbox") {
                field.attr("checked", (value.length > 0));
                return;
            }
        }
        field.val(value);
    }
}

function setFieldValue(surveyID, name, value) {
    $("#" + surveyID + " :input[name='" + name + "']").val(value);
}

function initSurveyForm(formName, templateName, id) {
    $("#" + id + " :submit").click(function() {
        var post = $("#" + id + " :input").serializeArray();
        post[post.length] = {name: 'templateName', value: templateName};
        partial("/survey/submitpartial/" + formName, post, null, null, id);
        return false;
    });
}
