﻿var scrolItemsOnPage = 1;
var ajaxPageItemCount = 25;
var alphaPageItemCount = 28;
var totalItemsCount = -1;
var alphaLetter = "a";
var aplhaAjaxPageItemCount = 28;
var alphatotalItemsCount = -1;
var cookieName = 'bandsPageCookieNumber';
var naviItemsCount = 5;
var activeItem;
var mainNaviItemsSize;
var alphaNaviItemsSize;
var lowerNaviClick = false;

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function renderPages(scrollableAPI, count, totalDisplay, containerID, alphabox) {
    var htmlForNavi = "";
    var htmlForPages = "";
    var allpageCount;
    if (alphabox) {
        allpageCount = Math.ceil(count / alphaPageItemCount);
    }
    else {
        allpageCount = Math.ceil(count / ajaxPageItemCount);
    }

    for (var i = 0; i < allpageCount; i++) {
        var c = i + 1;
        if (i > 0) {
            htmlForNavi += '<div class="linkItem">' + c + '</div>';
        } else {
            htmlForNavi += '<div class="linkItem active">' + c + '</div>';
        }
        htmlForPages += '<div class="pageContainer"></div>';
    }
    var $container = $(containerID);
    var $t = $container.find('.totalItemsCount');
    if ($t) {
        $t.each(function() {
            $(this).text(totalDisplay);
        });
    }
    $container.find('.navigatorContainer').each(
                function() {
                    var $container = $(this).find('.items');
                    $container.empty();
                    $container.css('left', '0');
                    if (htmlForNavi != "") {
                        $container.append($(htmlForNavi));
                        var $scroll = $(this).find('.scrolable');
                        var $naviHold = $(this).find('.PrevScrNextContainer');
                        var scrollWidth = 75;
                        switch (allpageCount) {
                            case (1):
                                {
                                    scrollWidth = 10;
                                    break;
                                } case (2):
                                {
                                    scrollWidth = 30;
                                    break;
                                } case (3):
                                {
                                    scrollWidth = 45;
                                    break;
                                } case (4):
                                {
                                    scrollWidth = 62;
                                    break;
                                } case (5):
                                {
                                    scrollWidth = 75;
                                    break;
                                }
                        }
                        $scroll.width(scrollWidth);
                        //$naviHold.width(scrollWidth + 90);
                    };
                });
    initScrollNavi(allpageCount, containerID, scrollableAPI, alphabox);
    $(containerID + ' div.scrollContainer div.scrolable div.items').empty().append($(htmlForPages));
}
function parceAjaxResponse($pageItem, data, alphabox) {
    var $d = $(data);
    var itemsInSelection = $d.find('resultItemsCount').text();
    var cntr = 0;
    var totalAddedCounter = 0;
    var html = "";
    var maxItemsInColumn = 5;
    if (alphabox) {
        maxItemsInColumn = 7;
    }
    $d.find('item').each(function() {
        var $item = $(this);
        var bandUrl = $item.find('url').text();
        if (cntr === 0) {
            html += '<div class="itemContainer">';
        }
        html += '<div class="item"><div class="imageContainer">'
                             + '<a href="' + bandUrl + '"><img src="' + $item.find('imagePath').text() + '" /></a>'
                             + '</div><div class="bandName"><a href="' + bandUrl + '" ';
        var tooltip = $item.find('tooltip').text();
        if (tooltip != "") {
            html += 'title="' + tooltip + '">';
        }
        else {
            html += '>';
        }
        html += $item.find('name').text()
                             + '</a></div>'
        if (!alphabox) {
            html += '<div class="info"><a href="' + bandUrl + '#tab=concerts' + '">' + $item.find('concertCount').text();
            if ($item.find('concertCount').text() == '1') {
                html += '</a> concert</div>';
            }
            else {
                html += '</a> concerts</div>';
            }
            html += '<div class="info"><a href="' + bandUrl + '#tab=photos' + '">' + $item.find('photoCount').text();
            if ($item.find('photoCount').text() == '1') {
                html += '</a> photo</div>';
            }
            else {
                html += '</a> photos</div>';
            }
            html += '<div class="info"><a href="' + bandUrl + '#tab=videos' + '">' + $item.find('videoCount').text();
            if ($item.find('videoCount').text() == '1') {
                html += '</a> video</div>';
            }
            else {
                html += '</a> videos</div>';
            }
            //html += '<div class="info"><a href="' + bandUrl + '">' + $item.find('videoCount').text() + '</a> videos</div>'
            //html += '<div class="info"><a href="' + bandUrl + '">' + $item.find('reviewCount').text() + '</a> reviews</div>'
        }
        html += '</div>';
        cntr++;
        totalAddedCounter++;
        if ((cntr === maxItemsInColumn) || (cntr == itemsInSelection) || (totalAddedCounter == itemsInSelection)) {
            html += '</div>';
            cntr = 0;
            $pageItem.append($(html));
            html = "";
        }
    });
    //$pageItem.append('<div class="toolTipContainer"></div>');
    // $pageItem.find('pageContainer a[title]').tooltip('#mainContent div.scrollContainer div.toolTipContainer');
}
function getPageContent(scrollableApi, requestedPage, startLetter, alphabox) {
    var letter = startLetter;
    var requestItemsCount = ajaxPageItemCount;
    var imageHeight = '90';
    var imageWidth = '122';
    var dispNameLettersCount = '18';
    if (alphabox) {
        letter = alphaLetter;
        requestItemsCount = aplhaAjaxPageItemCount;
        imageHeight = '75';
        imageWidth = '100';
        dispNameLettersCount = '15';
    }
    var requestFrom = requestedPage * requestItemsCount;
    if ((totalItemsCount !== -1) && (requestFrom >= totalItemsCount)) { return true; }
    var $page = 0;
    if (scrollableApi) {
        $page = scrollableApi.getItems().eq(requestedPage);
        var chld = $page.children();
        var length = chld.length.toString();
        var x = '0';
        if (length != x) {
            return true;
        };
    };
    var timeoutID;
    if (!alphabox) {
        timeoutID = setTimeout("$('div.loadOverlay').show().fadeTo('fast', overlayOpacity)", globalOverlayDelay);
    }
    $.ajax({
        type: 'GET',
        cache: false,
        async: true,
        url: '/Handlers/BandsHandler.ashx',
        data: ({
            "startFrom": letter,
            "from": requestFrom,
            "count": requestItemsCount,
            "imageWidth": imageWidth,
            "imageHeight": imageHeight,
            "dispNameLength": dispNameLettersCount
        }),
        success: function(data) {
            if (!alphabox) {
                clearTimeout(timeoutID);
                $('#mainContent div.loadOverlay').stop().fadeTo('normal', 0, function() { $(this).hide(); });
            }
            var $d = $(data);
            if ($d.find('result').text() == 'success') {
                if (alphabox) {
                    if (alphatotalItemsCount < 0) {
                        alphatotalItemsCount = $d.find('totalCount').text();
                        var totalDisplay = $(data).find('totalCountDisplay').text();
                        renderPages(scrollableApi, alphatotalItemsCount, totalDisplay, '#overlayID', alphabox);
                    };
                }
                else {
                    if (totalItemsCount < 0) {
                        totalItemsCount = $d.find('totalCount').text();
                        var totalDisplay = $(data).find('totalCountDisplay').text();
                        renderPages(scrollableApi, totalItemsCount, totalDisplay, '#mainContent', alphabox);
                    };
                }
                if (scrollableApi) {
                    $page = scrollableApi.getItems().eq(requestedPage);
                    parceAjaxResponse($page, data, alphabox);
                }
            }
        }
    });
    return true;
};
function swithAphaClick(scrollableApi, switchIndex) {
    var currPage = scrollableApi.getPageIndex();
    var index = switchIndex / scrolItemsOnPage;
    index = Math.ceil(index);
    var text = $('#alphaPagesNavi a:eq(' + index + ')').text();
    $('#alphaPagesNavi ').find('a').each(function() {
        $(this).removeClass('active');
        if ($(this).text() === text) {
            $(this).addClass('active');
        };
    });
};
function setSelectedAlphaBoxLetter(letter) {
    $('#overlayID div.overlayLetters a').each(function() {
        $(this).removeClass('selectedLetter');
        if ($(this).text() === letter) {
            $(this).addClass('selectedLetter');
        };
    });
}
function clearItemsList(scrollableApi) {
    var html = '<div class="pageContainer"></div>';
    scrollableApi.getItemWrap().empty().append($(html));
    return true;
}
function cookieChange(curValue, scrApi) {
    var value = readCookie(cookieName);
    if (!value) {
        value = 25;
        createCookie(cookieName, value, 14);
    };
    doCounterChange(value, scrApi);
}
function doCounterChange(value, scrApi) {
    if (ajaxPageItemCount.toString() != value.toString()) {
        ajaxPageItemCount = parseInt(value);
        totalItemsCount = -1;
        clearItemsList(scrApi);
        scrApi.setPage(0);
        var $p = $('#mainContent div.scrollContainer');
        animateScrollable($p, value);
    }
}
function animateScrollable($container, value) {
    if ($container) {
        var scrl = $container.find('div.scrolable');
        var mainContainer = $('#mainContent');
        var overlay = $('.loadOverlay');
        var requiredHeight = $container.height();
        var scrollableHeight = scrl.height();
        var mainHeight = mainContainer.height();
        switch (value.toString()) {
            case '25':
                requiredHeight = 831;
                break;
            case '50':
                requiredHeight = 1650;
                break;
            case '75':
                requiredHeight = 2460;
                break;
        }

        scrollableHeight = requiredHeight - 27;
        mainHeight = requiredHeight + 74;

        mainContainer.animate({ height: mainHeight + 20 }, 'slow');
        $container.animate({ height: requiredHeight }, 'slow');
        scrl.animate({ height: scrollableHeight }, 'slow');
        overlay.height(scrollableHeight + 29);
    }
}
function switchAfterScrollItemClick(path, alphabox) {
    var naviItemsSize;
    if (alphabox) {
        naviItemsSize = alphaNaviItemsSize;
    }
    else {
        naviItemsSize = mainNaviItemsSize;
    }
    var $s = $(path).find('.scrolable').scrollable();
    if ($s) {
        var visibleItems = $s.getVisibleItems();
        var itemsLength = visibleItems.length;
        if (itemsLength <= naviItemsCount && $s.getPageAmount() == "1") {
            $(path).each(function() {
                $(this).find('.NextNavi').addClass('disabledPageNavi');
                $(this).find('.PrevNavi').addClass('disabledPageNavi');
            });
        }
        else {
            if (activeItem <= "1") {
                activeItem = 1;
                $(path).each(function() {
                    $(this).find('.PrevNavi').addClass('disabledPageNavi');
                    $(this).find('.NextNavi').removeClass('disabledPageNavi');
                });
            }
            else {
                if (activeItem >= naviItemsSize) {
                    activeItem = naviItemsSize;
                    $(path).each(function() {
                        $(this).find('.PrevNavi').removeClass('disabledPageNavi');
                        $(this).find('.NextNavi').addClass('disabledPageNavi');
                    });
                }
                else {
                    $(path).each(function() {
                        $(this).find('.NextNavi').removeClass('disabledPageNavi');
                        $(this).find('.PrevNavi').removeClass('disabledPageNavi');
                    });
                }
            }
        }
    }
}
function resizeScroll(path, curIndex) {
    var scrollCont = $(path).parent();
    var scrollContWidth = 100;
    var navigatogCont = $(scrollCont).parent();
    var navigatogContWidth = 154;
    var scrollWidth = 75;
    if (curIndex < 6) {
        scrollWidth = 75;
    }
    else {
        if (curIndex < 8) {
            scrollWidth = 85;
        }
        else {
            if (curIndex < 10) {
                scrollWidth = 95;
            }
            else {
                if (curIndex < 96) {
                    scrollWidth = 100;
                }
                else {
                    if (curIndex < 97) {
                        scrollWidth = 110;
                        scrollContWidth = 110;
                        navigatogContWidth = 165;
                    }
                    else {
                        if (curIndex < 98) {
                            scrollWidth = 115;
                            scrollContWidth = 115;
                            navigatogContWidth = 170;
                        }
                        else {
                            if (curIndex < 99) {
                                scrollWidth = 123;
                                scrollContWidth = 123;
                                navigatogContWidth = 178;
                            }
                            else {
                                if (curIndex < 100) {
                                    scrollWidth = 132;
                                    scrollContWidth = 132;
                                    navigatogContWidth = 186;
                                }
                                else {
                                    if (curIndex < 999) {
                                        scrollWidth = 146;
                                        scrollContWidth = 146;
                                        navigatogContWidth = 195;
                                    }
                                    else {
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    $(path).width(scrollWidth);
    $(scrollCont).width(scrollContWidth);
    $(navigatogCont).width(navigatogContWidth);
}
function doNaviClick(index, scrollableApi, path) {
    $(path + ':eq(0) .scrolable').scrollable().click(activeItem - 1);
    $(path + ':eq(1) .scrolable').scrollable().click(activeItem - 1);
    scrollableApi.setPage(index - 1);
};
function lowerClickChech(navi) {
    if ($(navi).hasClass('lowerNavi')) {
        lowerNaviClick = true;
    }
    else {
        lowerNaviClick = false;
    }
}
function initScrollNavi(allpageCount, naviName, scrollContentApi, alphabox) {
    allpageCount = naviItemsCount;
    var apiNaviTop = $(naviName + ' .PrevScrNextContainer:eq(0) .scrolable').scrollable({
        size: allpageCount,
        disabledClass: 'disabledPageNavi',
        onSeek: function(index) {
            resizeScroll(naviName + ' .PrevScrNextContainer:eq(0) .scrolable', this.getIndex() + 1);
            return true;
        }
    });
    if (apiNaviTop.mousewheel != undefined) {
        apiNaviTop.mousewheel();
    }
    var apiNaviBottom = $(naviName + ' .PrevScrNextContainer:eq(1) .scrolable').scrollable({
        size: allpageCount,
        disabledClass: 'disabledPageNavi',
        onSeek: function(index) {
            resizeScroll(naviName + ' .PrevScrNextContainer:eq(1) .scrolable', this.getIndex() + 1);
            return true;
        }
    });
    if (apiNaviBottom.mousewheel != undefined) {
        apiNaviBottom.mousewheel();
    }
    var naviItemsSize = $(naviName + ' .PrevScrNextContainer:eq(0) .scrolable').scrollable().getSize();
    if (alphabox) {
        alphaNaviItemsSize = naviItemsSize;
    }
    else {
        mainNaviItemsSize = naviItemsSize;
    }
    activeItem = '1';
    switchAfterScrollItemClick(naviName + ' .PrevScrNextContainer', alphabox);

    $(naviName + ' .PrevScrNextContainer .scrolable .items .linkItem').click(function() {
        if (!alphabox) {
            lowerClickChech($(this).parentsUntil('naviMainContainer'));
        }
        activeItem = $(this).text();
        doNaviClick(activeItem, scrollContentApi, naviName + ' .PrevScrNextContainer');
        switchAfterScrollItemClick(naviName + ' .PrevScrNextContainer', alphabox);
    });

    $(naviName + ' .PrevScrNextContainer .NextNavi').unbind().click(function() {
        if (!alphabox) {
            lowerClickChech($(this).parentsUntil('naviMainContainer'));
        }
        activeItem++;
        doNaviClick(activeItem, scrollContentApi, naviName + ' .PrevScrNextContainer');
        switchAfterScrollItemClick(naviName + ' .PrevScrNextContainer', alphabox);
    });
    $(naviName + ' .PrevScrNextContainer .PrevNavi').unbind().click(function() {
        if (!alphabox) {
            lowerClickChech($(this).parentsUntil('naviMainContainer'));
        }
        activeItem--;
        doNaviClick(activeItem, scrollContentApi, naviName + ' .PrevScrNextContainer');
        switchAfterScrollItemClick(naviName + ' .PrevScrNextContainer', alphabox);
    });
}

$(function() {
    var funcAuth = AuthModule();
    funcAuth.SetReloadPage(true);
    var firstCall = true;
    var value = readCookie(cookieName);
    if (!value) {
        value = 25;
        createCookie(cookieName, value, 14);
    }
    $('.itemsOnPageCounter').val(value);
    ajaxPageItemCount = parseInt(value);
    var $p = $('#mainContent div.scrollContainer');
    animateScrollable($p, value);
    firstCall = false;
    var photosApi = $('#mainContent div.scrollContainer div.scrolable')
					.scrollable({
					    prev: $('#alphaPagesNavi div.paneNextPrev div.prevPage'),
					    next: $('#alphaPagesNavi div.paneNextPrev div.nextPage'),
					    size: scrolItemsOnPage,
					    onBeforeSeek: function(index) {

					        getPageContent(photosApi, index, "", false);
					    },
					    onSeek: function(event) {
					        if (lowerNaviClick) {
					            $.scrollTo('#mainContent .naviMainContainer:eq(0)', 800);
					        }
					    }
					}).navigator({ api: true });
    photosApi.setPage(0);

    //init overlay 	 
    $('div.alphaList  a').live('click', function() {
        alphaLetter = $(this).text();
        setSelectedAlphaBoxLetter(alphaLetter);
        clearItemsList(apiScrollable);
        alphatotalItemsCount = -1;
        return true;
    });
    $('#overlayID div.overlayLetters  a').live("click", function(e) {
        e.preventDefault();
        alphaLetter = $(this).text();
        setSelectedAlphaBoxLetter(alphaLetter);
        clearItemsList(apiScrollable);
        alphatotalItemsCount = -1;
        apiScrollable.setPage(0);
        return true;
    });
    $('div.alphaList a').overlay({
        target: '#overlayID',
        effect: 'apple',
        onLoad: function(event) {
            apiScrollable.reload();
            apiScrollable.setPage(0);
            return true;
        }
    });

    var apiScrollable = $('#overlayID div.scrollContainer div.scrolable')
					.scrollable({
					    size: scrolItemsOnPage,
					    api: true,
					    disabledClass: 'disabledPageNavi',
					    onBeforeSeek: function(index) {
					        getPageContent(apiScrollable, index, alphaLetter, true);
					    },
					    onSeek: function(event) {
					        swithAphaClick(apiScrollable, event);
					    }
					});
    apiScrollable.setPage(0);
    $('.itemsOnPageCounter').each(function() {
        $(this).change(function() {
            if (!firstCall) {
                var curValue = $(this).val();
                createCookie(cookieName, curValue, 14);
                cookieChange(curValue, photosApi);
            }
        });
    });
});
