ASMSys_Board_NextData = {}; // format: { table_id: Data[ Set[ img[], img[] ... ], Set[ ... ] ... ], ... }
ASMSys_Board_CurrData = {}; // format: { table_id: Data[ Set[ img[], img[] ... ], Set[ ... ] ... ], ... }
ASMSys_Board_CurrUsed = {}; // format: { table_id: [ pos, pos, pos ... ], ... }
ASMSys_Board_CurrSet = {};   // the index of the current set being used to swap images
ASMSys_Board_Options = {};  // format: { table_id: ["script1.php", function(){ something(); } ], ... }

// load the pet board inside the element id and start swapping
function ASMSys_Board_Load(rows, cols, id, strCallScriptURL, functionShowPet)
{
    var table_id = id + "-table";

    ASMSys_Board_Options[table_id] = new Array();
    ASMSys_Board_Options[table_id][0] = strCallScriptURL;
    ASMSys_Board_Options[table_id][1] = functionShowPet;

    //
    // Board creation
    //
    var table = document.createElement("table");
    table.setAttribute("id", table_id);
    table.setAttribute("border", "0");
    table.setAttribute("cellSpacing", "1");
    table.setAttribute("cellPadding", "2");
    table.setAttribute("align", "center");
    var tbody = table.appendChild(document.createElement("tbody"));

    var td = null;
    var tr = null;

    var i = 0;
    var j = 0;

    for (i = 0; i < rows; ++i)
    {
        tr = tbody.appendChild(document.createElement("tr"));

        for (j = 0; j < cols; j++)
        {
            td = document.createElement("td");
            td.setAttribute("align", "center");
            td.setAttribute("vAlign", "bottom");
            td.setAttribute("width", "90");
            td.setAttribute("height", "115");
            tr.appendChild(td);
        }
    }

    document.getElementById(id).appendChild(table);

    //
    // Start images swapping
    //
    ASMSys_Board_startSwapping(table_id);
}
// start the image swapping loop
function ASMSys_Board_startSwapping(table_id)
{
    if (!ASMSys_Board_CurrData[table_id] && !ASMSys_Board_NextData[table_id])
    {
        // get array of elements to swap through ajax call
        ASMSys_Board_fetchNextDataSet(table_id, ASMSys_Board_startSwapping);
    }
    else if (!ASMSys_Board_CurrData[table_id])
    {
        // copy next data to current data and fill the table, this should happen the first time the board is loaded
        ASMSys_Board_copyNextDatasetToCurrent(table_id);

        // fill table with the 1st set data
        for (var i = 0; i < ASMSys_Board_CurrData[table_id][0].length; ++i)
        {
            ASMSys_Board_TablePut(table_id, ASMSys_Board_CurrData[table_id][0][i], i);
            ASMSys_Board_CurrUsed[table_id].push(i);
        }

        setTimeout(function(){ASMSys_Board_startSwapping(table_id);}, 3000);
    }
    else
    {
        // change one image
        var item = ASMSys_Board_getItemFromCurrentSet(table_id);

        if (!item)
        {
            ASMSys_Board_fetchNextDataSet(table_id, ASMSys_Board_startSwapping);
        }
        else
        {
            ASMSys_Board_TablePut(table_id, item[1], item[0]);
            setTimeout(function(){ASMSys_Board_startSwapping(table_id);}, 3000);
        }
    }
}
// copy next dataset to currentdataset, cleaning the next dataset.
// return true if the data was copied successfully or false otherwise.
function ASMSys_Board_copyNextDatasetToCurrent(table_id)
{
    if (!ASMSys_Board_NextData[table_id])
        return false;

    ASMSys_Board_CurrData[table_id] = new Array();

    for (var i = 0; i < ASMSys_Board_NextData[table_id].length; ++i)
        ASMSys_Board_CurrData[table_id][i] = ASMSys_Board_NextData[table_id][i];

    // clear next data array
    ASMSys_Board_NextData[table_id] = null;
    // reset the used items on current set
    ASMSys_Board_CurrUsed[table_id] = new Array();
    // reset the current set pointer
    ASMSys_Board_CurrSet[table_id] = 0;

    return true;
}
// randomly get an item from the current set of table_id and return it, marking the item as used
// return false if the item couldn't be found
// return format: [pos, item]
function ASMSys_Board_getItemFromCurrentSet(table_id)
{
    // counting the remaining images in the current set
    var currDataRest = ASMSys_Board_CurrData[table_id][ASMSys_Board_CurrSet[table_id]].length - ASMSys_Board_CurrUsed[table_id].length;

    // if there are no remaining images, either get the next dataset or increments the current set pointer
    if (currDataRest == 0)
    {
        // if the current set is the last, get the new dataset, otherwise just go to the next set
        if (ASMSys_Board_CurrSet[table_id] == (ASMSys_Board_CurrData[table_id].length - 1))
        {
            if (!ASMSys_Board_copyNextDatasetToCurrent(table_id))
                return false;
        }
        else
        {
            ++ASMSys_Board_CurrSet[table_id];
            ASMSys_Board_CurrUsed[table_id] = new Array();
        }
    }

    // if we are in the last set of the current data, more data will be loaded for the next iteration
    if (ASMSys_Board_CurrSet[table_id] == (ASMSys_Board_CurrData[table_id].length - 1) && ASMSys_Board_CurrUsed[table_id].length == 0)
        ASMSys_Board_fetchNextDataSet(table_id);

    var r = Math.floor(Math.random() * currDataRest + 1); // random number between 1 and currDataRest
    var ri = 1; // count for r;
    var i, j;
    var imgused = false;

    for (i = 0; i < ASMSys_Board_CurrData[table_id][ASMSys_Board_CurrSet[table_id]].length; ++i)
    {
        // detect if the current image position (i) was already used
        for (j = 0; j < ASMSys_Board_CurrUsed[table_id].length; ++j)
        {
            if (i == ASMSys_Board_CurrUsed[table_id][j])
            {
                imgused = true;
                break;
            }
        }

        if (imgused)
        {
            imgused = false;
            continue;
        }

        if (r == ri)
        {
            ASMSys_Board_CurrUsed[table_id].push(i);
            return [i, ASMSys_Board_CurrData[table_id][ASMSys_Board_CurrSet[table_id]][i]];
        }

        ++ri;
    }
}
// fetch next dataset of images to be used and call function callback when finished.
function ASMSys_Board_fetchNextDataSet(table_id, callback)
{
    var boardR = new ajax(
        ASMSys_Board_Options[table_id][0],
        function(text, status, xml)
        {
            if (status == 200)
            {
                ASMSys_Board_callbackNextData(table_id, text);

                if ((typeof callback) == "function")
                    callback(table_id);
            }
            else
            {
                // try again in 3 seconds
                setTimeout(function(){ASMSys_Board_fetchNextDataSet(table_id, callback)}, 3000);
            }
        }
    );
    boardR.update("", "post");
}
// callback to handle a request to fetch a remote dataset.
function ASMSys_Board_callbackNextData(table_id, text)
{
    ASMSys_Board_NextData[table_id] = eval(text);
}
// put the img (that is a element of a set inside the table table_id at the
// position number pos.
function ASMSys_Board_TablePut(table_id, img, pos)
{
    var tbody = document.getElementById(table_id).firstChild;

    var curpos = 0;
    var i, j, div, eimg, name;

    for (i = 0; i < tbody.childNodes.length; ++i)
    {
        for (j = 0; j < tbody.childNodes[i].childNodes.length; ++j)
        {
            if (curpos == pos)
            {
                div = document.createElement("div");

                eimg = document.createElement("img");

                if (img[2] < 1)
                    eimg.setAttribute("src", "http://spcalaval-com.si-sv2028.com/images/animal-default.png");
                else
                    eimg.setAttribute("src", "http://spcalaval-com.si-sv2028.com/pub/ns/photos_display.php?id_photo=" + img[2] + "&thumbnail=1");

                eimg.setAttribute("border", "0");

                tdiv = document.createElement("div");
                tdiv.className = "name";
                name = document.createTextNode(img[1]);

                tdiv.appendChild(name);
                div.appendChild(eimg);
                div.appendChild(document.createElement("br"));
                div.appendChild(tdiv);

                if (tbody.childNodes[i].childNodes[j].firstChild)
                    tbody.childNodes[i].childNodes[j].removeChild(tbody.childNodes[i].childNodes[j].firstChild);

                tbody.childNodes[i].childNodes[j].style.cursor = "pointer";
                //tbody.childNodes[i].childNodes[j].onclick = function() { window.location = "http://spcalaval-com.si-sv2028.com/show_animal.php?id_animal=" + img[0]; };
                tbody.childNodes[i].childNodes[j].onclick = function() { ASMSys_Board_Options[table_id][1](img[0]); };
                tbody.childNodes[i].childNodes[j].appendChild(div);
                return true;
            }

            ++curpos;
        }
    }
}

