﻿/// <reference path="jquery-1.3.2-vsdoc.js"/>

$.DEBUG = false;

$(window).load(function () {

    var lCol = $('.bottom-corner');
    var rCol = $('.right-content');
    var lHeight = lCol.height();
    var rHeight = rCol.height();

    if (lHeight < rHeight) {
        lCol.height(rHeight - 40);
    }
    frontBanner();
    SetTabHover();
    SetTabClick();
    SetDropdownChange();
    SetSortbarChange();
    stepControl();
    SetEmailBoxFocus();
    ActivateDroppy();
    LabelFocusFix();
    MiniCartExpand();
    FooterLinks()
    SearchboxClear();
    EqualHeights();
    SwitchBands();
    makeAccordion();
});


function frontBanner() {
    $('.banner-home .slides').cycle({
        timeout: 15000,
        pager: '.banner-nav'
    });
}


function TestArea() {
    /************* Test Area *************/



    /*************************************/
}

function log(s) {
    if ($.DEBUG) {
        try { console.log(s); }
        catch (e) { }
    }
}

function stepControl() {
    $('ol#steps li:not(li.past) a').click(function(e){
        e.preventDefault();
    });
}


function SetTabHover() {
    $('ul.tabs li').hover(function () {
        $(this).removeClass('off')
        $(this).addClass('on')
    }, function () {
        $(this).addClass('off')
        $(this).removeClass('on')
    });
}

function ActivateDroppy() {
    $('li.droppy').hover(function () {
        $('div.letters').hide();
        $('li.slidey').removeClass('hover');
        $('li.slidey > h3 > a').removeClass('activated');
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover')
    });
    $('li.slidey > h3 > a').live('click', function (e) {
        if ($(this).hasClass('activated')) {
            e.preventDefault();
            $('div.letters').slideUp();
            $('li.slidey').removeClass('hover');
            $(this).removeClass('activated');
        } else {
            e.preventDefault();
            $('div.letters').slideDown();
            $('li.slidey').addClass('hover');
            $(this).addClass('activated');
        }
    });
    $('li.bands').hover(function () {
        var div = $(this).find("div");
        if (div.length == 0) {
            var char = $(this).find("a").html();
            LoadBandByChar($(this), char);
        }
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    });
}

function LoadBandByChar(element, char){
    $.ajax({
        url: "/Ajax/Tags",
        type: "POST",
        dataType: "json",
        data: {
            searchTerm: char,
            sortOrder: "Name"
        },
        success: function (data) {
            var html = '<div class="bands"><ul>';
            $.each(data, function(key, tag) {
                html += '<li><a href="/bands/' + tag.UrlName + '">' + tag.Name + '</a>';
            });
            html += '</ul></div>';
            element.append(html);
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            //alert(errorThrown);
        }
    })
}

function LabelFocusFix() {
    $("#item-sizes label.in-stock").click(function () {
        $("#item-sizes label.in-stock").removeClass("focus");
        $(this).addClass("focus");
    });
}

function MiniCartExpand() {
    $(".minicart-item").click(function(){
        $(this).addClass("clicked");
        $(this).animate({ height: "175px", top: "-151px" });
        $(this).children("h5").hide();
        $(this).children("a.deletebutton").hide();
        $(this).children("h3").show();
    });
    $(".minicart-item").mouseleave(function (e) {
        if($(e.target).hasClass('minicart-item')){
            $(this).children("h5").show();
            $(this).children("a.deletebutton").show();
            $(this).children("h3").hide();
            $(this).removeClass("clicked");
            $(this).animate({ height: "19px", top: "0px" });
        }
    });
}

function FooterLinks() {
    $("#footer li:nth-child(5n+1)").addClass("group1");
    $("#footer li:nth-child(5n+2)").addClass("group2");
    $("#footer li:nth-child(5n+3)").addClass("group3");
    $("#footer li:nth-child(5n+4)").addClass("group4");
    $("#footer li:nth-child(5n+5)").addClass("group5");
}

function EqualHeights() {
    var shippingMethodHeight = $("#shippingMethod").height();
    $("#paymentInformation").css({ minHeight: shippingMethodHeight + "px" });
}

function SearchboxClear() {
    $("#searchTermAjax").focus(function () {
        $(this).val('');
    });
}

function SwitchBands() {
    $("#sortbar a.switch-bands").click(function () {
        $(this).hide();
        $("#sortbar select").show();
    });

    $("#sortbar a.switch-cats").click(function () {
        $(this).hide();
        $("#sortbar select").show();
    });
}

function SetTabClick() {
    $('ul.tabs li').click(function() {
        //highlight clicked tab
        $('ul.tabs li').addClass("off");
        $('ul.tabs li.active').removeClass('active');
        $(this).addClass('active');

        //show panel
        $(".tc").css("display", "none");

        var panelID = this.id.split("-")[1];
        $("#div-" + panelID).css("display", "block");

        return false;
    });
}


function makeAccordion() {
    $('#accordion').accordion({
        autoHeight: false
    });
}


function SetDropdownChange() {
    $('select#itemID').change(function() {
        UpdateItem(this.value);
    });
}

function SetSortbarChange() {
    $("select.pageSize").change(function() {
        //log($(this).parents("form"));
        $(this).parents("form").submit();
    });

    $("select.sortBy").change(function() {
        $(this).parents("form").submit();
    });
}

function SetEmailBoxFocus() {
    var defaultValue = "Email Address";
    $(".bottom-corner .inbox input#email").focus(function() {
        if (this.value == defaultValue)
            this.value = "";
    });
    $(".bottom-corner .inbox input#email").blur(function() {
        if (this.value == "")
            this.value = defaultValue;
    });
}

function UpdateImage(imageID, width, height) {
    $("#mainImage").attr("src", "/showimage.axd?id=" + imageID + "&w=" + width + "&h=" + height);
}

// AJAX Update
function UpdateItem(itemID) {
    $.getJSON("/ItemGroup/UpdateItem/" + itemID, null,
    function(result) {

        //update dropdown
        $('select#itemID').val(itemID);

        //update item name
        document.title = result.name;
        $("#breadcrumbName").text(result.name);
        $("#NameHeader").text(result.name);

        //update item info
        $("#ItemDetails").replaceWith(result.ItemDetails);

        //update selected option in dropdownlist
        $('select#optionList option[value={ITEMID}]'.replace("{ITEMID}", itemID)).attr("selected", "selected");

        //update main image
        $('#mainImageLink').replaceWith(result.MainImageBlock);

        //update alternate images
        $('#alternateImages').replaceWith(result.AlternateImages);

        //update specs
        $("#div-specs div").replaceWith(result.Specs);
        //$("table.specTable tbody tr:even").addClass("alt");
    });     
}

function ChangeImage(imageID) {
    $.get("/ItemGroup/MainImage/" + imageID, null,
    function(result) {
        $('#mainImageLink').replaceWith(result);
    });
}

//function UpdateName(itemID) {
//    $.get("/ItemGroup/UpdateName/" + itemID, null,
//    function(name) {
//        log("Name: " + name);
//        document.title = name;
//        $("#NameHeader").text(name);
//    });
//}

//function UpdateSection(itemID, sectionName) {
//    $.get("/ItemGroup/Update" + sectionName + "/" + itemID, null,
//    function(response) {
//        log(response);
//        $("#" + sectionName).replaceWith(response);
//    });
//}

////AJAX:UpdateItem
//function UpdateItem(itemID) {
//    $.getJSON("/ItemGroup/Update/" + itemID, null,
//    function(itemVM) {
//        $.each(itemVM, function(i, property) {
//            console.log(i + " : " + property);
//        });
//    });
//}


function split(val) {
    return val.split(/,\s*/);
}

function extractLast(term) {
    return split(term).pop();
}

$(function () {
    $("#searchForm").submit(function (e) {
        $("#searchTerm").val($("#searchTermAjax").val());
    });
    $(".bandAutocomplete")
    .bind("keydown", function (event) {
        if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
            event.preventDefault();
        }
    })
    .autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Ajax/Tags",
                type: "POST",
                dataType: "json",
                data: {
                    searchTerm: extractLast(request.term),
                    maxResults: 15
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.Name, value: item.UrlName }
                    }))
                },
                error: function (xmlHttpRequest, textStatus, errorThrown) {
                    //alert(errorThrown);
                }
            })
        },
        search: function () {
            $('#addFeaturedTag').attr("disabled", "disabled");
            // custom minLength
            var term = extractLast(this.value);
            if (term.length < 1) {
                return false;
            }
        },
        focus: function () {
            if (!$(this).hasClass('single')) {
                // prevent value inserted on focus
                return false;
            }
        },
        select: function (event, ui) {
            $('#addFeaturedTag').attr("disabled", "");
            $(this).attr('valid', !!ui.item);
            if (!$(this).hasClass('single')) {
                var terms = split(this.value);
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push(ui.item.value);
                // add placeholder to get the comma-and-space at the end
                terms.push("");
                this.value = terms.join(", ");
                return false;
            }
            else {
                $(this).siblings('input[type="hidden"]').first().val(ui.item.value);
                $(this).val(ui.item.label);
                $(this).parents("form").submit();
                return false;
            }
        },
        minLength: 1,
        multiple: !$(this).hasClass('single')
    });
});

/*
    UPDATE PRICE WHEN SIZE ATTRIBUTE SELECTION CHANGES
*/
$(function () {
    $('input[type="radio"][name^="itemid_"]').live("click", function () {
        var form = $(this).parents("form");
        var action = form.attr("action");
        var groupID = action.replace(/[^\d]/g, "");
        var newPrice = $('#' + $(this).attr("id") + '_price').val();
        $(".price").find("span").html("$" + newPrice);
        var newSKU = $('#' + $(this).attr("id") + '_sku').val();
        $("#item-sku").html("Product Number: " + newSKU);
    });
});


/*
ADD TO CART - UPDATE MINI-CART VIA AJAX
*/
$(function () {
    $(".AddtoCartBtn").click(function (e) {
        e.preventDefault();
        var form = $(this).parents("form");
        var action = form.attr("action");
        var groupID = action.replace(/[^\d]/g, "");
        var radio = form.find("input[name=itemid_" + groupID + "]:checked");
        var itemID = radio.val();
        var qty = form.find("select[name=qty_" + groupID + "]").val();
        var data = {};
        if (itemID != null) {
            if (radio.hasClass("out-of-stock")) {
                alert("We're sorry.  This item is currently out of stock.  Please try again later.");
            }
            else {
                $(this).attr("src", "/content/images/btn-add-to-cart-2.png");
                data["itemid_" + groupID] = itemID;
                data["qty_" + groupID] = qty;
                data["returnCartHtml"] = "True";
                $.ajax({
                    url: action,
                    type: "POST",
                    dataType: "text",
                    data: data,
                    success: function (data) {
                        $("#minicart").html(data);
                        $("#minicart").animate({
                            backgroundColor: "#9d221e"
                        }, 250, function () {
                            $(this).animate({
                                backgroundColor: "#0e2e3c"
                            }, 2000);
                        });
                        $(".AddtoCartBtn").attr("src", "/content/images/btn-add-to-cart-3.png");
                        $(".AddtoCartBtn").animate({
                            backgroundColor: "#208240"
                        }, 250, function () {
                            $(this).animate({
                                backgroundColor: "#9d221e"
                            }, 2000, function () {
                                $(".AddtoCartBtn").attr("src", "/content/images/btn-add-to-cart.png");
                            });
                        });
                        MiniCartExpand();
                    },
                    error: function (xmlHttpRequest, textStatus, errorThrown) {
                        //alert(errorThrown);
                    }
                });
            }
        }
        else {
            alert("Please select a size.");
        }
    });

    $("a.deleteCartItem").live("click", function (e) {
        e.preventDefault();
        var itemID = $(this).parents(".minicart-item").find('input[name^="itemid_"]').val();
        $(this).parents(".minicart-item").remove();
        var data = {};
        if (itemID != null) {
            data["id"] = itemID;
            $.ajax({
                url: "/ItemGroup/RemoveFromCart",
                type: "POST",
                dataType: "text",
                data: data,
                success: function (data) {
                    $("#minicart").html(data);
                    $("#minicart").animate({
                        backgroundColor: "#9d221e"
                    }, 250, function () {
                        $(this).animate({
                            backgroundColor: "#0e2e3c"
                        }, 2000);
                    });
                    MiniCartExpand();
                },
                error: function (xmlHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        }
    });
});

