﻿//add .NET-style format function to Javascript string object
String.prototype.format = function( text )
{
    //check if there are two arguments in the arguments list
    if ( arguments.length <= 1 )
    {
        //if there are not 2 or more arguments there’s nothing to replace
        //just return the original text
        return text;
    }
    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for( var token = 0; token <= tokenCount; token++ )
    {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ),
                                                arguments[ token + 1 ] );
    }
    return text;
};

//make rows and columns for table
function makeTableRows(trFormat, tdFormat, rowsCount, colsCount)
{
    cols = "";
    for (var i = 0; i < colsCount; i++)
    {
        cols += tdFormat;
    }
    rows = "";
    for (var i = 0; i < rowsCount; i++)
    {
        rows += "".format(trFormat, cols);
    }
    return rows;
}

//update table and hi-light changed cell
function updateTable(table, sectionId, groupId)
{
    var tbody = $(table).children("tbody");
    var url = window.location.href.substr(0,window.location.href.lastIndexOf("/")) + "/GetGroupData.aspx?section=" + sectionId + "&group=" + groupId;
    $.getJSON(url, function(data) {
        var oldRowsCount = tbody.children(":not(:first)").length;
        var appendedRowsCount = data.length - oldRowsCount;
        if (appendedRowsCount > 0)
        {
            var colsCount = 0
            for (i in data[0]) {
                colsCount++;
            }
            tbody.append(makeTableRows("<tr>{0}</tr>","<td></td>", appendedRowsCount, colsCount));
        }
        tbody.children(":odd").addClass("stripe");
        tbody.children(":not(:first)").each(function(row) {
            var col = 0;
            var cells = $(this).children();
            var dataRow = data[row];
            for (i in dataRow) {
                if ((languageId == 0) && (col == 0)) {
                    dataRow[i] = replaceStr(dataRow[i], {"month":"Tháng", "year":"Năm", "total value":"Tổng GTDD", "foreigners":"NĐTNN", "buy":"Mua", "sell":"Bán"});
                }
                if (cells.eq(col).html().toLowerCase().replace(/"/g,'') != dataRow[i].toLowerCase()) {
                    cells.eq(col).html(dataRow[i]).filter(function(i){return 0 < oldRowsCount}).addClass("hilite");
                }
                col++;
            }
        });
        setTimeout( function() {
            tbody.children(":not(:first)").children(".hilite").removeClass("hilite")
        }, 3000);
    });
    return true;
}

function replaceStr(text, replacements)
{
    var lowerText = text.toLowerCase();
    var res = lowerText;
    for (key in replacements) {
        res = res.replace(key, replacements[key]);
    }
    return res == lowerText ? text : res;
}

//update selected panel
function updatePanel(sectionId, ui)
{
    var panel;
    if (ui) {
        panel = ui.panel.id;
        $("#tabs_"+sectionId).attr("current_panel",panel);
        $(ui.tab).blur();
    }
    else {
        panel = $("#tabs_"+sectionId).attr("current_panel");
    }
    $("#"+panel).children("table").each( function(i) {
        var groupId = this.id.substr("table_content_".length);
        return updateTable(this, sectionId, groupId);
    });
    return true;
}

//init tabs and set-up update function call
function initTabs(tabsId, sectionId, updateInterval)
{
    $("#"+tabsId).tabs({
        select: function(event, ui) { 
            return updatePanel(sectionId, ui);
        },
        selected: -1
    }).tabs("select", 0);
    setInterval(function(){ updatePanel(sectionId); }, updateInterval||8000);
}

