﻿
function initPage() {
    initHighlight();
    initPager();
}

function initHighlight() {
    if (typeof (toHighlight) != "undefined") {
        $("#" + toHighlight).addClass("sel");
    }
    if (typeof (sectionToHighlight) != "undefined") {
        $("#" + sectionToHighlight).addClass("sel");
    }
}

var pagesArray = new Array();
var pagesLink = new Array();
var currentPageIndex = 0;
var backPage = null;
var nextPage = null;

function initPager() {
    if ($("#pageContainer div").length > 0) {
        // Smonto il contenuto nelle sue pagine
        $("#pageContainer div").each(function() {
            pagesArray.push(this);
        });

        // Link "indietro"
        backPage = $("<span class=\"stronglink genPag-arrow-left\">&nbsp;&nbsp;</a></span>").click(goToPrevPage);
        $(".paginationFake").append(backPage);

        var pageElement = null;
        // Creo il paginatore
        for (var i in pagesArray) {
            pageElement = $("<span>" + (parseInt(i) + 1) + "</span>" + (i != pagesArray.length - 1 ? "<span class=\"paginationSeparator\">-</span>" : ""));
            pageElement.data("page", i).click(changePage);
            $(".paginationFake").append(pageElement);
            pagesLink.push(pageElement);
        }

        // Link "avanti"
        nextPage = $("<span class=\"stronglink genPag-arrow-right\">&nbsp;&nbsp;</a></span>").click(goToNextPage);
        $(".paginationFake").append(nextPage);

        setCurrentPage();
    }
}

function goToPrevPage() {
    currentPageIndex -= 1;
    if (currentPageIndex < 0) {
        currentPageIndex = 0;
    }
    setCurrentPage();
}

function goToNextPage() {
    currentPageIndex += 1;
    if (currentPageIndex > (pagesArray.length - 1)) {
        currentPageIndex = pagesArray.length - 1;
    }
    setCurrentPage();
}

function changePage() {
    currentPageIndex = parseInt($(this).data("page"));
    setCurrentPage();
}

function setCurrentPage() {

    // Le rendo invisibili
    for (var i in pagesArray) {
        $(pagesArray[i]).hide();
        $(pagesLink[i]).addClass("stronglink");
    }
    // Rendo visibile quella corrente
    $(pagesArray[currentPageIndex]).show();
    // Segno la pagina corrente
    $(pagesLink[currentPageIndex]).removeClass("stronglink");

    // imposto la visibilità di avanti / indietro
    if (currentPageIndex == 0) {
        backPage.hide();
    } else {
        backPage.show();
    }
    if (currentPageIndex == pagesArray.length - 1) {
        nextPage.hide();
    }
    else {
        nextPage.show();
    }
}

$(document).ready(initPage);
