﻿$(document).ready(function() {
    SetupGrid();
    SetupFilter();
});

var RESET_IN_PROGRESS = false;
var progressTimeout;

///NOTE: SetupFilter should run only on the initial page load
function SetupFilter() {
    //Load the filter choice lists and wireup pager events.

    $('.sortOptions').change(function() {
        UpdateView(0); //sort even on empty string so that the default sort is restored
    });

    $('.aFilterSubmit').click(function() {
        UpdateView(0);
    });

    $('.reset').click(function() {
        ResetFilter();
    });

    $('.divOptionAnchor').click(function() {
        //close any other filter slides and cancel their timers first
        var divOptionPanelChildId = $(this).children('.divOptionPanel')[0].uniqueNumber;
        $('.divOptionPanel').each(function() {
            var op = $(this);
            if (op[0].uniqueNumber != divOptionPanelChildId) {
                op.stop();
                op.css('height', 'auto'); //reset incase fast cursor movements messed up the heights
                op.hide();
            }
        });

        if ($(this).children('div:animated').length > 0) {
            /*do not open if animating*/
        }
        else {
            //get height of choices container
            var filterChoicesContainer = $(this).children('div');
            var height = filterChoicesContainer.outerHeight();

            //animate slide movement
            $(this).height(height + 27);
            filterChoicesContainer.slideDown();
        }
    });

    $('.divOptionAnchor').hover(
    //hover on
    function() {
        //code was moved from here to click
        var anchorTimeOutId = $(this).data('filterSlideTimeoutId');
        if (anchorTimeOutId) {
            clearTimeout(anchorTimeOutId);
        }
    },
    //hover off
    function() {
        //setup a timeout to collapse the panel 
        var anchorId = this.id;
        var filterSlideTimeoutId = setTimeout("$('#" + anchorId + " .divOptionPanel').hide();$('#" + anchorId + "').height(27);", 500);
        $(this).data('filterSlideTimeoutId', filterSlideTimeoutId);
    });

    //Slide Buttons
    $(".tblOptionButtons input").click(function() {
        var id = this.id;
        if (id.indexOf('ibCheckAllColor') > -1) {
            $('.tblColorChoices input').attr('checked', 'checked');
        }
        else if (id.indexOf('ibCheckAllSize') > -1) {
            $('.tblSizeChoices input').attr('checked', 'checked');
        }
        else {
            //close the option panels
            $('.divOptionPanel').hide();
            $('.divOptionPanel').parent().height(27);
            UpdateView(0);
        }

        return false;
    });

}


function UpdateView(requestedPageIndex) {
    if (RESET_IN_PROGRESS) {
        return;
    }

    //start progress animation
    ShowProgressPanel();

    var service = new Customization.BVModules.Services.CategoryService();

    cgr = new Customization.BVModules.Services.CategoryGridRequest();
    cgr.CategoryId = $('input[id$="hfCategoryId"]').val();
    cgr.SortType = $('.sortOptions').val();
    cgr.ColorList = [];
    cgr.SizeList = [];
    cgr.OccasionList = [];
    //Disable paging for now.
    cgr.RequestedPageIndex = -1; //requestedPageIndex;

    //load price choice
    var priceChoice = $('.divPriceChoices input:checkbox:checked');
    var priceFilter = priceChoice.length > 0 ? priceChoice.parent().attr('title') : '';
    cgr.PriceFilter = priceFilter.length > 0 ? priceFilter : 0;

    //load color choices
    $('.tblColorChoices input:checked').each(function() {
        cgr.ColorList.push($(this).parent().attr('bvin'));
    });

    //load size choices
    $('.tblSizeChoices input:checked').each(function() {
        cgr.SizeList.push($(this).parent().attr('bvin'));
    });

    //load occasion choices
    $('.tblOccasionChoices input:checked').each(function() {
        cgr.OccasionList.push($(this).parent().attr('bvin'));
    });

    service.GetData(cgr, ServiceDataResponse);
}

function ShowProgressPanel() {
    //show progress panel after some small wait
    progressTimeout = setTimeout("ShowProgressPanelTimeOut();", 1000);
}

function ShowProgressPanelTimeOut() {
    var dpp = $('#categorymain .divProgressPanel');
    var dppBack = $('#categorymain .divProgressPanel .backColor');
    dppBack.css('opacity', '0');
    dpp.css('display', 'block');
    dppBack.fadeTo('slow', 0.7, function() { });

}

function HideProgressPanel() {
    clearTimeout(progressTimeout); //if it has not yet been shown then prevent it from being shown
    $('#categorymain .divProgressPanel').hide(); //if it has been shown then hide it.
}

function ResetFilter() {

    RESET_IN_PROGRESS = true;

    //TODO:
    $('.sortOptions').val("");
    $('.divPriceChoices input:checkbox').attr("checked", "");
    $('.tblColorChoices input:checkbox').attr("checked", "");
    $('.tblSizeChoices input:checkbox').attr("checked", "");
    $('.tblOccasionChoices input:checkbox').attr("checked", "");

    RESET_IN_PROGRESS = false;
}

function ServiceDataResponse(result) {
    $('.gridPlaceholder').html(result.GridMarkup);
    $('.pager').html(result.PagerMarkup);
    SetupGrid();
    HideProgressPanel();
}

var hasLoadedFirstSlide = false;
function SetupGrid() {

    //Setup pager links
    $('.pager a').each(function() {
        var link = $(this);
        //NOTE: Href in IE7 will auto add the absolute url so check &page= after the param
        var href = link.attr('href');
        var param = '&page=';
        var indexOfParam = href.indexOf(param);
        var indexOfVal = indexOfParam + param.length;
        var pageNum = link.attr('href').substr(indexOfVal);
        link.click(function() { UpdateView(pageNum - 1); return false; });
    });

    //Setup scroller
    $('.divDataListWrap').jScrollPane({ showArrows: true, scrollbarWidth: 15, scrollbarMargin: 0, dragMinHeight:120, dragMaxHeight:145 });

    //Setup hover events
    $('.recordimage a').hover(function() {
        var index = parseInt($(this).attr('hoverImageIndex'));
        $('#s1').cycle(index);
    }, function() { });

    //Setup Cycle
    hasLoadedFirstSlide = false;
    var imageCount = $('#s1 .contentWrap').length;
    if (imageCount == 0) {
        return;
    }

    if (imageCount == 1) {
        //if there is only 1 image cycle will not automatically set visibility so do this manually
        $($('#s1 .contentWrap')[0]).show();
    }

    $('#s1').cycle({
        timeout: 0,
        speed: 150,
        startingSlide: 0,
        //move the info content into a region outside the cycle plugin area so text is not pixelated by the transition effect and so there is no color flash
        before: function(curr, next, opts) {
            if (curr.uniqueNumber != next.uniqueNumber) {
                $('.primaryImage .infoShown .infoLink').hide();
            }
        },
        after: function(curr, next, opts) {
            var newInfo = $('.primaryImage .infoHidden:eq(' + opts.currSlide + ')').html();
            $('.primaryImage .infoShown').html(newInfo);

            $('.primaryImage .infoShown .infoLink').show();

            //Adjust image container height since to prevent a gap
            var newHeight = $('.primaryImage img:eq(' + opts.currSlide + ')').height();
            if (hasLoadedFirstSlide) {
                $('.primaryImage .pics').animate({ height: newHeight }, 100, null);
            }
            else {
                //do not animate height change on loading
                $('.primaryImage .pics').height(newHeight);
            }
            hasLoadedFirstSlide = true;
        }
    });
}
