
// CONFIG notes. Below are some comments that point to where this script can be customized.
// Note: Make sure to include a <tbody></tbody> in your table's HTML

var INPUT_NAME_PREFIX = 'inputName'; // this is being set via script
var RADIO_NAME = 'totallyrad'; // this is being set via script
var TABLE_NAME = 'grdOnDutyCategories'; // this should be named in the HTML
var ROW_BASE = 1; // first number (for display)
var hasLoaded = true;
var Ids ='';


function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

	function RemoveOnDutyCategories(form){				
			var Ids='';
			var checkboxes = GetCheckBoxes(false);
			DeleteAllRows(checkboxes)		
		}

	
	function DeleteAllRows(checkboxes){
		for (i=checkboxes.length-1;i>=0;i--){
							DeleteTableRow(checkboxes[i]);						 
							}		
	}

	function DeleteTableRow(thisRow)
		{
			var theRow = thisRow.parentNode.parentNode;
			theRow.parentNode.removeChild(theRow);
		}

	function SetCategoriesChild(categories)
	{		
		var txtIDs = document.getElementById('txtIDS');
		var Ids = '';
		var concepts = categories.split(',');
		var values = '';
		var checkboxes = GetCheckBoxes(true);	
		DeleteAllRows(checkboxes);
		for (var i=0; i <=concepts.length-1;i++ ){
			values = concepts[i].split('-');
			insertRowToTable(values[0],values[1]);
			if( Ids != '' )
						{
							Ids +=  ',' + values[0] ;
						}else
						{
							
							Ids = Ids + values[0] ;	
						}	
			}
			
		txtIDs.value = Ids;
	}
	
	function GetCheckBoxes(All){
		var elements = document.getElementsByTagName('input'); 
		var txtIDs = document.getElementById('txtIDS');
		var Ids = '';
		var t; 
		var checkboxes = []; 
		for (var i=0, len=elements.length; i<len; i++){ 
			t = elements[i]; 
				if ('checkbox' == t.type && t.name == 'cbxDeleteOnDutyCategories'){ 					
				if (All == false){
						if(t.checked==true){
							checkboxes.push(t); 
						} 
						else{
							if( Ids != '' )
							{
								Ids +=  ',' + t.value ;
							}else
							{
								
								Ids = Ids +t.value ;	
							}		
						}
					}				
					else{
						checkboxes.push(t); 
					}	
			}
		}		
			txtIDs.value = Ids;
			
		return checkboxes;

	}

function opencategorypopup()
	{
		window.open('OnDutyLookup.aspx?Lookup=true','MenuPopup','Scrollbars=no,menubars=no,toolbars=no,width=700,height=300');
		self.close;
	}
function myRowObject(one, two, three)
{
	this.one = one; // text object
	this.two = two; // text object
	this.three = three; // input checkbox object
}
function insertRowToTable(ID,Concept)
{
	if (hasLoaded) {
		var tbl = document.getElementById(TABLE_NAME);
		var rowToInsertAt = tbl.tBodies[0].rows.length;		
		for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
			if (tbl.tBodies[0].rows[i].myRow && tbl.tBodies[0].rows[i].myRow.three.getAttribute('type') == 'checkbox' && tbl.tBodies[0].rows[i].myRow.three.checked) {
				rowToInsertAt = i;
				break;
			}
		}
		addRowToTable(rowToInsertAt,ID,Concept);
	}
}


/*
 * addRowToTable
 * Inserts at row 'num', or appends to the end if no arguments are passed in. Don't pass in empty strings.
 */
function addRowToTable(num,ID,Concept)
{
	if (hasLoaded) {
		var tbl = document.getElementById(TABLE_NAME);
		var nextRow = tbl.tBodies[0].rows.length;
		var iteration = nextRow + ROW_BASE;
		if (num == null) { 
			num = nextRow;
		} else {
			iteration = num + ROW_BASE;
		}
		
		// add the row
		var row = tbl.tBodies[0].insertRow(num);
		
		// CONFIG: requires classes named classy0 and classy1
		row.className = 'classy' + (iteration % 2);
	
		// CONFIG: This whole section can be configured
		
		// cell 0 - text
		var cell0 = row.insertCell(0);
		var textNode = document.createTextNode(ID);
		cell0.appendChild(textNode);
		
		// cell 1 - text
		var cell1 = row.insertCell(1);
		var textNode = document.createTextNode(Concept);
		cell1.appendChild(textNode);		

		
		
		// cell 3 - input checkbox
		var cell2 = row.insertCell(2);
		var cbEl = document.createElement('input');
		cbEl.setAttribute('type', 'checkbox');
		cbEl.setAttribute('name', 'cbxDeleteOnDutyCategories');
		cbEl.setAttribute('value', ID);
		cbEl.setAttribute('id', ID);

		cell2.appendChild(cbEl);
		
		
		// Pass in the elements you want to reference later
		// Store the myRow object in each row
		row.myRow = new myRowObject(textNode, textNode, cbEl);
	}
}


function EditMsgGroup(groupID)
{
	document.getElementById('lnkTitle' + groupID).style.display = 'none'; 
	document.getElementById('txtGrp' + groupID).style.display = 'inline'; 
	document.getElementById('imgUpdate' + groupID).style.display = 'inline';
	document.getElementById('imgCancel' + groupID).style.display = 'inline'; 
}

function UpdateCancelMsgGroup(groupID, isUpdate)
{
	var newLink = document.getElementById('lnkTitle' + groupID);
	var newText = document.getElementById('txtGrp' + groupID);
	
	if (isUpdate)
	{
		newLink.innerHTML = newText.value;
	}
	else
	{
		newText.value = newLink.innerHTML;
	}
	newLink.style.display = 'inline';
	
	newText.style.display = 'none';
	document.getElementById('imgUpdate' + groupID).style.display = 'none'; 
	document.getElementById('imgCancel' + groupID).style.display = 'none'; 
}

function MsgCharCount(objTextBox, nameSpan)
{
	var objSpan = document.getElementById(nameSpan);
	
	objSpan.innerHTML = objTextBox.value.length;
	
	return true;
}

function ValidateMsgText(nameTextBox, messageLength)
{
	var objTextBox = document.getElementById(nameTextBox);
	if (objTextBox.value.length > messageLength)
	{
		return confirm("Your message length exceeds the average message length permitted by cell phones. Confirm that you want to send it anyway?");
	}
	return true;
}

///This function is only for the expiration tracker for groups page
var CheckUncheckAll = function(cbControl, checkHandler)
{   
    var state;
    var CheckboxLabel = document.getElementById("CheckboxLabel");
    var chkBoxList = document.getElementById(cbControl);
    var chkBoxCount= chkBoxList.getElementsByTagName("input");

    if(CheckboxLabel == null || chkBoxList == null || chkBoxCount == null)
    {
        return;
    }
    
    if(checkHandler.checked)
    {
        state = true;
        CheckboxLabel.innerHTML = "Check all";
    }
    else
    {
        state = false;
        CheckboxLabel.innerHTML = "Check all";
    }
    
    for(var i=0;i<chkBoxCount.length;i++)
    {
        chkBoxCount[i].checked = state;
    }

    return false; 
}

// This function controls a confirmation box in the manage tracking items page only    
var requestDeleteConfirmation = function(hdnOldNameID, txtNewNameID)
{
    var result = true;
    var hdnOldName = document.getElementById(hdnOldNameID);
    var txtNewName = document.getElementById(txtNewNameID);
    if(hdnOldName != null && txtNewName != null)
    {
        if(hdnOldName.value != txtNewName.value)
        {
            // name changed
            result = confirm('This will change the name of all existing entries with this item name as well as all future entries?');
        }
        else
        {
            result = true;
        }
    }
    else
    {
        result = true;
    }
    
    return result;
    
}

	var PerformDutyOperation = function(dutyOperationFunction)
	{
        var dutyText = document.getElementById("txtDutyForInput");
        var dutyCombo = document.getElementById("cboDutyForInput");

        if(dutyText != null && dutyCombo != null)
        {
            dutyOperationFunction(dutyText, dutyCombo)
        }
	    
	}
		
    var AddDutyItem = function(textbox, combobox)
    {
        if(textbox.value.length == 0)
        {
            alert("Please, enter a valid duty category name");
            return;
        }
        else
        {
            if(!this.isNewCategoryName(textbox.value, combobox))
            {
                alert("The duty category name already exists in the dropdown box.");
                return;
            }
            else
            {
                var newOption = document.createElement("option");
                combobox.options.add(newOption);
                newOption.text = textbox.value;
                newOption.value = "-1";
                newOption.selected = true;
                textbox.value = "";
            }
        }
    }
    
    var PutDutyItem = function(textbox, combobox)
    {
        if(combobox.value == "select")
        {
            textbox.value = "";
        }
        else
        {
            textbox.value = combobox.options[combobox.selectedIndex].text;
        }
    }

    var RemoveDutyItem = function(textbox, combobox)
    {
        var selIndex = combobox.selectedIndex;

        if(selIndex < 0 || combobox.value == "select")
        {
            return;
        }

        combobox.options[selIndex] = null;
        textbox.value = "";
    }

    var UpdateDutyItem = function(textbox, combobox)
    {
        var selIndex = combobox.selectedIndex;

        if(selIndex < 0 || textbox.value.length == 0 || combobox.value == "select")
        {
            return;
        }

        combobox.options[selIndex].text = textbox.value;
    }

    var isNewCategoryName = function(item, combo)
    {
        var result = true;
        for(var i=0; i<combo.options.length; i++)
        {
            if(combo.options[i].text == item)
            {
                result = false;
                break;
            }
        }
        return result;
        
    }

    var PrepareDutyItemsForPost = function(textbox, combobox)
    {
        var hiddenField = document.getElementById("hdnDutyForSelected");
        if(hiddenField == null)
        {
            return;
        }

        var items = new Array();

        for(var i=0; i<combobox.options.length; i++)
        {
            items.push(combobox.options[i].value + "," + combobox.options[i].text);
        }
        
        hiddenField.value = items.join("|");
    }	

    var PrepareDispatchersState = function()
    {
        var grid = document.getElementById("grdDispatchCenters");
        var hiddenDispatchers = document.getElementById("hdnDispathersList");
        var DispatchersArray = new Array();
        
        if(grid == null || hiddenDispatchers == null)
        {
            return true;
        }
        
        var rows = grid.getElementsByTagName("TR");
        
        if(rows.length > 0)
        {
            for(var i = 1; i < rows.length; i++)
            {
                var columns = rows[i].getElementsByTagName("TD");
                if(columns.length == 2)
                {
                    var text = columns[0].innerText;
                    var value = "";
                    var checkboxes = columns[1].getElementsByTagName("input");
                    if(checkboxes.length == 1)
                    {
                        value = checkboxes[0].getAttribute("datavalue");
                        DispatchersArray.push(value +  ":" + text);
                    }
                }
            }
            
            hiddenDispatchers.value = DispatchersArray.join("|");
        }
        return true;
        
    }
	
