﻿
function sortChanged(attribute, isDesc) {
    $('ul#list02 > li').sortElements(function (a, b) {
        var aValue = parseFloat($(a).attr(attribute));
        var bValue = parseFloat($(b).attr(attribute));

        if (!aValue) {
            aValue = $(a).attr(attribute);
        }

        if (!bValue) {
            bValue = $(b).attr(attribute);
        }

        if (isDesc) {
            return aValue < bValue ? 1 : -1;
        } else {
            return aValue > bValue ? 1 : -1;
        }
    });

    $('ul#list02 > li').removeClass("first");
    $('ul#list02 > li').first().addClass("first");
}

function sortSelected(selectedValue) {
    if (selectedValue == 'prodRelevanceDesc') {
        document.location = Globals.sortUrl.replace("sortBy=_sortBy_", '');
    } else {
        document.location = Globals.sortUrl.replace("=_sortBy_", "=" + escape(selectedValue));
    }
    return;
}

function onProductViewMoreClick(e) {
    var ctl = $(this);
    var text = ctl.html();

    // don't do anything if text is loading. That means an event is already running
    if (text == 'Loading...') return;
    
    ctl.html("Loading...");
    $.get($(this).attr('href'), {}, function (html) {
        var ul = $(html);
        var list = $('li', ul);
        $('ul#list02').append(list);
        ctl.remove();
        $('#product-view-more').click(onProductViewMoreClick);
    });
    e.preventDefault();
}

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

$(function () {
    $('select#product-sort').change(function () {
        var selectedValue = $(this).val();
        sortSelected(selectedValue);
    });

    /*if ($('select#product-sort option:selected').length) {
        sortSelected($('select#product-sort option:selected').val());
    }*/

    $('#product-view-more').click(onProductViewMoreClick);

    if ($('#product-view-more').length > 0) {
        $(window).scroll(function () {
            var ctl = $('#product-view-more');
            if (ctl.length > 0) {
                if (isScrolledIntoView(ctl)) {
                    ctl.click();
                }
            }
            else {
                $(window).unbind('scroll');
            }
        });
    }
});
