﻿function Grid(objectName, isInteractive, titleElementID, theadID, tbodyID, btnAddID, btnEditID, btnDeleteID, btnPrintID)
{
    var m_NavHandler = null;
    
    var m_AutoUpdate = true;
    var m_DataType = null;
    var m_TrainingID = null;
    var m_UserID = null;
    var m_SortColumn = null;
    var m_RowIDs = new Array();
    var m_SelectedRowID = null;
    
    var m_AjaxArea = null;
    var m_DataTypeChangedCallback = null;
    var m_UpdatedCallback = null;
    var m_RowSelectedCallback = null;
    
    var titleElement = document.getElementById(titleElementID);
    var thead = document.getElementById(theadID);
    var tbody = document.getElementById(tbodyID);
    var btnAdd = document.getElementById(btnAddID);
    var btnEdit = document.getElementById(btnEditID);
    var btnDelete = document.getElementById(btnDeleteID);
    var btnPrint = document.getElementById(btnPrintID);
    var request = null;
    
    this.SetAutoUpdate = function(value) { m_AutoUpdate = value; }
    this.GetAutoUpdate = function() { return m_AutoUpdate; }
    
    this.SetDataType = function(value)
    {
        m_DataType = value;
        m_TrainingID = null;
        m_UserID = null;
        m_SortColumn = null;
        
        if(m_DataTypeChangedCallback != null)
            m_DataTypeChangedCallback(value);
    }
    this.GetDataType = function() { return m_DataType; }
    
    this.SetTrainingID = function(value) { m_TrainingID = value; }
    this.GetTrainingID = function() { return m_TrainingID; }
    
    this.SetUserID = function(value) { m_UserID = value; }
    this.GetUserID = function() { return m_UserID; }
    
    this.SetSortColumn = function(value) { m_SortColumn = value; }
    this.GetSortColumn = function() { return m_SortColumn; }
    
    this.SetAjaxArea = function(value) { m_AjaxArea = value; }
    this.SetDataTypeChangedCallback = function(value) { m_DataTypeChangedCallback = value; }
    this.SetUpdatedCallback = function(value) { m_UpdatedCallback = value; }
    this.SetRowSelectedCallback = function(value) { m_RowSelectedCallback = value; }
    
    function construct()
    {
        if(typeof Nav != "undefined")
            m_NavHandler = Nav.CreateHandler("Grid", NavCallback);
        
        if(btnAdd != null)
            btnAdd.onclick = AddClicked;
        if(btnEdit != null)
            btnEdit.onclick = EditClicked;
        if(btnDelete != null)
            btnDelete.onclick = DeleteClicked;
        if(btnPrint != null)
            btnPrint.onclick = PrintClicked;
    }
    
    // Selects the row with the given index.
    this.SelectRow = function(row_index)
    {
        if(!isInteractive)
            return;
            
        if(m_SelectedRowID == m_RowIDs[row_index])
            return;
            
        var trs = tbody.getElementsByTagName("tr");
        for(var i = 0; i < trs.length; i++)
            trs[i].className = (i == row_index) ? "Selected" : "";

        m_SelectedRowID = m_RowIDs[row_index];
            
        if(m_RowSelectedCallback != null)
            m_RowSelectedCallback(m_DataType, m_RowIDs[row_index]);
    }
    
    // Displays a popup window containing the page at the given source.
    function ShowPopup(src, width, height, showMenus, name)
    {
        if(!width) width = 780;
        if(!height) height = 350;
        
        src += (src.indexOf('?') == -1 ? "?" : "&");
        src += "SaveCallback=" + objectName + ".Update";
        
        var w = window.open(src, (name ? name : "GridPopup"), "width=" + width + ", height=" + height + ", resizable=yes, scrollbars=yes, status=no,menubar=" + (showMenus ? "yes" : "no"));
        if(window.focus)
            w.focus();
    }
    
    function AddClicked()
    {
        var src = "";
        var width = null;
        var height = null;
        
        if(m_DataType == "Training")
            src = "ModifyTraining.aspx";
        else if(m_DataType == "Users") {
            src = "ModifyUser.aspx";
            width = "880";
            height = "430";
        } else if(m_DataType == "TrainingUsers") {
            src = "ModifyUserTraining.aspx?TrainingID=" + m_TrainingID;
            width = "600";
        } else if(m_DataType == "UserTraining") {
            src = "ModifyUserTraining.aspx?UserID=" + m_UserID;
            width = "600";
        } else {
            return;
        }
            
        ShowPopup(src, width, height);
    }
    
    function EditClicked()
    {
        if(m_SelectedRowID == null || m_SelectedRowID.length == 0)
            return;
            
        var src = "";
        var width = null;
        var height = null;
        
        if(m_DataType == "Training")
            src = "ModifyTraining.aspx?ID=" + m_SelectedRowID;
        else if(m_DataType == "Users") {
            src = "ModifyUser.aspx?ID=" + m_SelectedRowID;
            width = "880";
            height = "430";
        } else if(m_DataType == "TrainingUsers") {
            src = "ModifyUserTraining.aspx?UserID=" + m_SelectedRowID + "&TrainingID=" + m_TrainingID;
            width = "600";
        } else if(m_DataType == "UserTraining") {
            src = "ModifyUserTraining.aspx?UserID=" + m_UserID + "&TrainingID=" + m_SelectedRowID;
            width = "600";
        } else {
            return;
        }
            
        ShowPopup(src, width, height);
    }
    
    function DeleteClicked()
    {
        if(m_SelectedRowID == null || m_SelectedRowID.length == 0)
            return;

        if(window.confirm("Warning: The selected record and all data associated with it will be deleted. Do you want to continue?"))
            Update("DeleteID=" + escape(m_SelectedRowID));
    }
    
    function PrintClicked()
    {
        var src = "GridPrint.aspx";
        var d = new Date();
	    src += "?time=" + d.getTime();
	    src += "&DataType=" + escape(m_DataType);
	    if(m_TrainingID != null)
	        src += "&TrainingID=" + escape(m_TrainingID);
	    if(m_UserID != null)
	        src += "&UserID=" + escape(m_UserID);
	    if(m_SortColumn != null)
	        src += "&SortColumn=" + escape(m_SortColumn);
	        
        ShowPopup(src, 660, 400, true, "GridPrint");
    }
    
    function RowDoubleClicked()
	{
	    if(!isInteractive)
	        return;
	        
	    if(m_DataType == "Training" || m_DataType == "UserTraining") {
	        m_DataType = "TrainingUsers";
	        m_TrainingID = m_SelectedRowID;
	        m_SortColumn = null;
	        Update();
	        
	        if(m_DataTypeChangedCallback != null)
	            m_DataTypeChangedCallback(m_DataType);
	    } else if(m_DataType == "TrainingUsers") {
	        m_DataType = "UserTraining";
	        m_TrainingID = null;
	        m_UserID = m_SelectedRowID;
	        m_SortColumn = null;
	        Update();
	        
	        if(m_DataTypeChangedCallback != null)
	            m_DataTypeChangedCallback(m_DataType);
	    } else {
	        EditClicked();
	    }
	}
        
    function CreateXMLHttpRequestObject()
    {
		var tmp;
		
		if(window.XMLHttpRequest) {
			tmp = new XMLHttpRequest();
			if(tmp.overrideMimeType)
				tmp.overrideMimeType("text/xml");
		} else if(window.ActiveXObject) {
			try {
				tmp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				try {
					tmp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e2) {}
			}
		}
		
		return tmp;
	}
	
	function ParseColumns(columns)
	{
        // remove existing column header row
	    while(thead.childNodes.length > 0)
	        thead.removeChild(thead.firstChild);
	        
	    var tr = document.createElement("tr");
	    
	    // add columns to new column header row
	    for(var i = 0; i < columns.length; i++) {
	        var th = document.createElement("th");
	        th.onclick = new Function(objectName + ".SetSortColumn(" + (i + 1 == m_SortColumn ? -(i + 1) : (i + 1)) + "); " + objectName + ".Update()");
	        if(columns[i].firstChild)
	            th.innerHTML = HtmlEncode(columns[i].firstChild.nodeValue);
	        tr.appendChild(th);
	    }
	    
	    thead.appendChild(tr);
	}
	
	function CreateTableCell(cell)
	{
	    var td = document.createElement("td");
	    if(cell.attributes.getNamedItem("Color") != null)
	        td.style.color = cell.attributes.getNamedItem("Color").value;
	    if(cell.attributes.getNamedItem("Bold") != null)
	        td.style.fontWeight = (cell.attributes.getNamedItem("Bold").value.toLowerCase() == "true") ? "bold" : "inherit";
	    
        if(cell.firstChild == null)
            return td;
        
        var type = (cell.attributes.getNamedItem("Type") != null ? cell.attributes.getNamedItem("Type").value : null);
        var value = HtmlEncode(cell.firstChild.nodeValue);
        
        if(type == "Date" && isInteractive) {
            // make dates be links
            var a = new Array();
            a = value.split(" / ");
            value = "";
            
            for(var i = 0; i < a.length; i++) {
                if(i > 0)
                    value += " - ";
                    
                value += "<a href=\"javascript:ShowDate('" + a[i] + "')\">" + a[i] + "</a>";
            }
        } else if(type == "Email" && isInteractive) {
            // make mailto link
            value = "<a href=\"mailto:" + value + "\">" + value + "</a>";
        }
        
        td.innerHTML = value;
            
        return td;
	}
	
	function ParseRows(rows)
	{
	    m_RowIDs.length = 0;
	    m_SelectedRowID = null;
	    
	    // remove existing rows
	    while(tbody.childNodes.length > 0)
	        tbody.removeChild(tbody.firstChild);
	    
	    // loop through each row
	    for(var i = 0; i < rows.length; i++) {
	        var id = rows[i].attributes.getNamedItem("ID").value;
	        var cells = rows[i].getElementsByTagName("Cell");
	        var tr = document.createElement("tr");
	        
	        tr.onclick = new Function(objectName + ".SelectRow(" + i + ")");
	        tr.ondblclick = RowDoubleClicked;
	        
	        // loop through each cell
	        for(var j = 0; j < cells.length; j++)
	            tr.appendChild(CreateTableCell(cells[j]));
	        
	        tbody.appendChild(tr);
	        m_RowIDs.push(id);
	    }
	}
	
	function ParseXml()
	{
	    // continue only if the response is complete
	    if(request.readyState != 4 || request.status != 200)
	        return;
	        
	    var data = request.responseXML.getElementsByTagName("GridData").item(0);
	    var columns = data.getElementsByTagName("Columns").item(0).getElementsByTagName("Column");
	    var rows = data.getElementsByTagName("Rows").item(0).getElementsByTagName("Row");
	    
	    if(titleElement != null) {
	        titleElement.style.fontSize = "12pt";
	        titleElement.style.color = "#971919";
	        titleElement.innerHTML = data.attributes.getNamedItem("Title").value;
	    }
	    m_SortColumn = parseInt(data.getElementsByTagName("Columns").item(0).attributes.getNamedItem("Sort").value);
	    
	    ParseColumns(columns);
	    ParseRows(rows);
	    
	    if(m_NavHandler != null) {
	        m_NavHandler.SetParamValue("DataType", m_DataType);
	        m_NavHandler.SetParamValue("TrainingID", m_TrainingID);
	        m_NavHandler.SetParamValue("UserID", m_UserID);
	        m_NavHandler.SaveParamList();
	        Nav.UpdateHash();
	    }
	    
	    if(m_UpdatedCallback != null)
	        m_UpdatedCallback();
	}
	
	function NavCallback()
	{
	    m_DataType = m_NavHandler.GetParamValue("DataType");
	    m_TrainingID = m_NavHandler.GetParamValue("TrainingID");
	    m_UserID = m_NavHandler.GetParamValue("UserID");
	    Update();
	    
	    if(m_DataTypeChangedCallback != null)
	            m_DataTypeChangedCallback(m_DataType);
	}
	
	function Update(data)
	{
	    if(m_DataType == null)
	        return;
	    
	    request = CreateXMLHttpRequestObject();
	    if(!request)
	        return;
	    
	    // set source
	    var src = "GridData.aspx";
	    var d = new Date();
	    src += "?time=" + d.getTime();
	    src += "&DataType=" + escape(m_DataType);
	    if(m_TrainingID != null)
	        src += "&TrainingID=" + escape(m_TrainingID);
	    if(m_UserID != null)
	        src += "&UserID=" + escape(m_UserID);
	    if(m_SortColumn != null)
	        src += "&SortColumn=" + escape(m_SortColumn);
	        
	    request.onreadystatechange = ParseXml;
	    
	    // if there's data, send a POST request; otherwise, use GET
	    if(data != null) {
	        request.open("POST", src, true);
	        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	        request.setRequestHeader("Content-Length", data.length);
	    } else {
	        request.open("GET", src, true);
	    }
	    request.send(data);
	}
	
	this.Update = function(data)
	{
        Update(data);
	}
	
	function HtmlEncode(s)
	{
	    var tmp = s;
	    
	    tmp = tmp.replace(/\&/, "&amp;");
	    tmp = tmp.replace(/</, "&lt;");
	    tmp = tmp.replace(/>/, "&gt;");
	    tmp = tmp.replace(/\"/, "&quot;");
	    
	    return tmp;
	}
	
	construct();
}
