//$Id: IPAddressManager.js,v 1.25.2.2 2011/12/17 05:28:04 sureshkumar.p Exp $

var valueSpChars = "?&%'\"_`\\+";

function invalidCharsExist(str)
{
	for(var i=0;i<valueSpChars.length;i++)
	{
		for(var j=0;j<str.length;j++)
		{
			if(str.charAt(j)==valueSpChars.charAt(i))
			{
				return true;
			}
		}
	}
	return false;
}

function validateIPAddressManager()
{

	f = document.hostForm;

	if(f.actionFrom.value == 'stopButton')
        {
                return true;
        }
	return true;
}

function groupModifyAlias(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var selValue = (index == null)? tblModel.getSelectedRowIndices(refId):[index];
   if(selValue.length == 0)
   {
      alert("Select atleast one row!!");
      return;
   }
  var resID="";
   for(var i = 0; i < selValue.length; i++)
   {
        if(i < (selValue.length-1))
        {
            resID +=tblModel.getValueAt(selValue[i],colInd1)+" , ";
        }
        else
        {
            resID +=tblModel.getValueAt(selValue[i],colInd1);
        }
   }
   showURLInDialog('/ipam/IPAddressGroupModifyAliasName.jsp?resID='+resID,'position=relative,modal=yes,scrollbars=no,title=Modify Alias Name')
}

function modifyAssertTag(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);

    var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("IPResources.ASSERT_TAG");
   var resourceID = tblModel.getValueAt(index,colInd1)
   var assertTag = tblModel.getValueAt(index,colInd2)


   showURLInDialog('/lan/IPAddressModifyAliasName.jsp?tableName=IPResources&columnName=ASSERT_TAG&name=Asset Tag Name&value='+encodeURIComponent(assertTag)+'&resourceID='+resourceID,'position=relative,modal=yes,scrollbars=no,title=Modify Asset Tag');//No I18N
}
function modifyRogueStatus(menuItemName,refId,additionalParams,index)
{

  // var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);

    var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("RogueResources.ROGUETYPE");
   var resourceID = tblModel.getValueAt(index,colInd1)
   var ROGUETYPE = tblModel.getValueAt(index,colInd2)
   showURLInDialog('/ipam/IPAMModifyRogueType.jsp?tableName=IPResources&columnName=ASSERT_TAG&name=Asset Tag Name&ROGUETYPE='+ROGUETYPE+'&resourceID='+resourceID,'position=relative,modal=yes,scrollbars=no,width=400,title=Modify Rogue Type')
}


function modifyAliasName(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("IPResources.ALIAS_NAME");
   var resourceID = tblModel.getValueAt(index,colInd1)
   var aliasName = tblModel.getValueAt(index,colInd2)

   showURLInDialog('/lan/IPAddressModifyAliasName.jsp?tableName=IPResources&columnName=ALIAS_NAME&name=Alias Name&value='+encodeURIComponent(aliasName)+'&resourceID='+resourceID,'position=relative,modal=yes,scrollbars=no,title=Modify Alias Name');//No I18N
}
function modifyPhoneNumber(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);

   var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("IPResources.TELEPHONE_NUMBER");
   var resourceID = tblModel.getValueAt(index,colInd1)
   var telephoneNumber = tblModel.getValueAt(index,colInd2)
   showURLInDialog('/lan/IPAddressModifyAliasName.jsp?tableName=IPResources&columnName=TELEPHONE_NUMBER&name=Telephone Number&value='+encodeURIComponent(telephoneNumber)+'&resourceID='+resourceID,'position=relative,modal=yes,scrollbars=no,title=Modify Phone Number');//No I18N
}
function modifyLocation(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);

   var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");   p
   var colInd2  = tblModel.getColumnIndex("SNMPResources.SYSLOCATION");
   var resourceID = tblModel.getValueAt(index,colInd1)
   var telephoneNumber = tblModel.getValueAt(index,colInd2)

   showURLInDialog('/lan/IPAddressModifyAliasName.jsp?tableName=SNMPResources&columnName=SYSLOCATION&name=System Location&value='+encodeURIComponent(telephoneNumber)+'&resourceID='+resourceID,'position=relative,modal=yes,scrollbars=no,title=Modify Locatoin');//No I18N
}
function editIPAddressDetails(menuItemName,refId,additionalParams,index)
{
    var menuItemObj = getMenuItemObj(menuItemName);
    var tblModel = getTableModel(refId);
    var count = tblModel.getColumnCount();
    var url ='/modifyIPDetails.cc?uid='+new Date().getTime()+'&';
    for(var i = 0 ; i< count ; i++)
    {
        var colName = tblModel.getColumnName(i);
        var valueAt = tblModel.getValueAt(index,i);
        url = url+""+colName+"="+encodeURIComponent(valueAt)+"&";
    }

    var colInd  = tblModel.getColumnIndex("IPResources.IPADDRESS");
    var ipAddress = tblModel.getValueAt(index,colInd)
    showURLInDialog( url ,'position=absolute,modal=yes,top=70,left=400,scrollbars=no,title=Summary for :- '+ipAddress)

}

function viewIPHistoryDetails(menuItemName,refId,additionalParams,index)
{
   var tblModel = getTableModel(refId);
   // var tblModel = getTableModel(refId);
    var count = tblModel.getColumnCount();
     var url = "/IPAMHistory.cc?";
    for(var i = 0 ; i< count ; i++)
    {
        var colName = tblModel.getColumnName(i);
        var valueAt = tblModel.getValueAt(index,i);
        url = url+""+colName+"="+encodeURIComponent(valueAt)+"&";
    }
    var colInd  = tblModel.getColumnIndex("IPResources.IPADDRESS");
    var ipAddress = tblModel.getValueAt(index,colInd)
    if (navigator.appName == 'Netscape')
        {
                newwin=window.open(url,"Schedule","resizable=yes,scrollbars=yes,toolbar=no","centre");
        }
        else
        {
                newwin=window.open(url,"Schedule","resizable=yes,scrollbars=yes,toolbar=no","centre");
        }

  // showURLInDialog( url,'position=absolute,modal=no,top=50,left=50,scrollbars=no,title=IP Address History for :- '+ipAddress)
}
function modifySubnetName(netID,subnetName)
{
   if(subnetName == undefined)
   {
        subnetName = "Not Defined";
   }
    var resourceID = netID;
    showURLInDialog('/lan/IPAddressModifyAliasName.jsp?tableName=SubNetwork&columnName=SUBNET_NAME&name=Subnet Name&value='+encodeURIComponent(subnetName)+'&resourceID='+resourceID,'position=relative,modal=yes,scrollbars=no,title=Apply SubNet Name');//No I18N

}

function applySubNetName(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("SubNetwork.NETID");
   var colInd2  = tblModel.getColumnIndex("SubNetwork.SUBNET_NAME");
   var netID = tblModel.getValueAt(index,colInd1)
   var subnetName = tblModel.getValueAt(index,colInd2)
   if(netID == undefined)
   {

        colInd1  = tblModel.getColumnIndex("IPAMSummary.NETID");
        netID = tblModel.getValueAt(index,colInd1)
   }
   modifySubnetName(netID,subnetName);


}

function modifiyReservedStatus(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("t1.DESCRIPTION");
   var subNETID = document.getElementById("subNETID").value;
   var resourceID = tblModel.getValueAt(index,colInd1)
   var reservedStatus = tblModel.getValueAt(index,colInd2)
   showURLInDialog('/ipam/ModifiyReservedStatus.jsp?reservedStatus='+reservedStatus+'&resourceID='+resourceID+"&subNETID="+subNETID,'position=relative,modal=yes,scrollbars=no,title=Modify Reserved Status')
}

function modifiyIPStatus(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("IPResources.STATUS");// No I18N
   var subNETID = document.getElementById("subNETID").value;
   var resourceID = tblModel.getValueAt(index,colInd1)
   var Status = tblModel.getValueAt(index,colInd2);
   if(Status=="1"){ // No I18N
       Status="Used"; // No I18N
   }
   if(Status=="2"){ // No I18N
       Status="Transient";// No I18N
   }
   if(Status=="3"){ // No I18N
       Status="Available";// No I18N
   }
   showURLInDialog('/ipam/ModifiyIPStatus.jsp?Status='+Status+'&resourceID='+resourceID+"&subNETID="+subNETID,'position=relative,modal=yes,scrollbars=no,title=Modify Status')
}

function modifyOwnername(menuItemName,refId,additionalParams,index)
{
   var userRole = window.USERROLE;
   if(userRole == '1')
   {
   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("Owner.NAME");

   var resourceID = tblModel.getValueAt(index,colInd1)
   var ownerName = tblModel.getValueAt(index,colInd2)
   showURLInDialog('/ipam/ModifyOwnerName.jsp?ownerName='+encodeURIComponent(ownerName)+'&resourceID='+resourceID,'position=relative,modal=yes,scrollbars=no,title=Assign Owner');//No I18N
   }
   else
   {
 	          showURLInDialog('/framework/UACMessage.jsp?','position=relative,modal=yes,scrollbars=no,title=Authorization Failed');
 	     }
}

function modifyNWAliasName(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("IPResources.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("IPResources.ALIAS_NAME");

   var resourceID = tblModel.getValueAt(index,colInd1)
   var aliasName = tblModel.getValueAt(index,colInd2)

   showURLInDialog('/network/NWModifyAliasName.jsp?aliasName='+encodeURIComponent(aliasName)+'&resourceID='+resourceID,'position=relative,modal=yes,width=300,height=100,scrollbars=no,title=Modify Alias Name');//No I18N

}

function validateModifyAlias(f)
{
    f.actionFrom.value = "modAliasName";
    if(document.subnetInputForm.aliasName.value.length > 100 )
    {
        alert("Alias name cannot exceed 100 characters");
        return false;
    }
	var aliasName = document.subnetInputForm.aliasName.value
		for (i=0; i<aliasName.length; i++)
		{
			var ipChar = aliasName.charCodeAt(i);
			if (ipChar == 92)
			{
				alert("Alias name cannot contain \'\\\'")
					return false;
			}
		}

	return true;
}
function searchAction(action)
{
    if(document.hostForm.enterSearch.value == "no")
    {
        document.hostForm.actionFrom.value=action;
    }
}
function enterKeySearch(val , value , ev)
{

        if(navigator.appName == "Microsoft Internet Explorer")
	{
		if(window.event.keyCode == 13)
		{
                        document.hostForm.actionFrom.value = value;
			document.hostForm.enterSearch.value = "yes";
                        //setIPMAction(value);
		}
	}
	else if(navigator.appName == "Netscape")
	{
		if(ev.which == 13)
		{
                        document.hostForm.actionFrom.value = value;
			document.hostForm.enterSearch.value = "yes";
                        //setIPMAction(value);
		}
	}

}

function showSelectColumn(html)
{
    document.getElementById("subnetData").innerHTML=html;
}




function showInputField(choice)
{

        if(choice == 'homeTab'){
                window.clearInterval(intervalID);
                document.subnetForm.homeDetailTab.value="homeTab"
                ShowTab('homeTab');
                HideTab('inputTab');
                //HideTab('settingTab');
                renderSubnet("IPAddressSummaryTableView.cc")

        }else if(choice == 'inputTab')
        {
                document.subnetForm.homeDetailTab.value="inputTab"
                window.clearInterval(intervalID);
                ShowTab('inputTab');
                HideTab('homeTab');
                //HideTab('settingTab');
                renderSubnet("IPAddresssubnetView.cc")

        }
}

function ShowTab(divId)
{
	var id = document.getElementById(divId);
	id.style.display = "block";
}
function HideTab(divId){
	var id = document.getElementById(divId);
	id.style.display = "none";
}

function renderSubnet(viewName)
{
 viewName = viewName+'&uid='+new Date().getTime();
   var localVar = "subnetData";
    var myAnonFunction = function(response,reqOptions)
    {
       document.getElementById(localVar).innerHTML = response.getOnlyHtml();
    };
    AjaxAPI.sendRequest({URL:viewName,ONSUCCESSFUNC:myAnonFunction});
 }
 function renderIPAMGraph(viewName , id , netID )
{
 viewName = viewName+'&uid='+new Date().getTime();
   var localVar = id;
    var myAnonFunction = function(response,reqOptions)
    {
       document.getElementById(localVar).innerHTML = response.getOnlyHtml();
    };
    AjaxAPI.sendRequest({URL:viewName,PARAMETERS:netID,ONSUCCESSFUNC:myAnonFunction});
 }
var closeErrorMessageDivTimerID;
function IPAddSubnetModifiedAction()
{
    closeDialog();
    refreshIPAMViews();

}
function closeResponseText()
{
    window.clearInterval(closeErrorMessageDivTimerID);
     var emailchaneIDElem = document.getElementById('mc_messagediv');
    if(emailchaneIDElem.className != "hide") {
        emailchaneIDElem.className = "hide";
    }
}


//This code for refresh view after scanning in progress in Subnet Summary Page
var intervalID = "";
function refreshPage(scanningStatus)
{
    if(scanningStatus == 'true')
    {
        window.setTimeout('refreshIPAMViews()',3000);
    }
}

var lastTimeAjaxCalled = 0;
var subnetScanDelay = 3; // in seconds
subnetScanDelay = subnetScanDelay * 1000;

//to use this method to print the js logs in a div, put a div <div id='jslogdiv'></div> in IPAddSubnetListView.jsp
//function addToDiv(data)
//{
//document.getElementById('jslogdiv').innerHTML=document.getElementById('jslogdiv').innerHTML+"<br>"+data;
//}

function processSubnetScanInfo(jsScanData)
{
    var req = null;
    if(window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        req  = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.onreadystatechange = function()
    {
	    var dbScanData=null;
	    try
	    {
	    //alert('ready state : '+req.readyState);
        if(req.readyState == 4)
        {
	        //alert('status : '+req.status+', ready state : '+req.readyState);
            if(req.status == 200)
            {
                dbScanData = trim(req.responseText);
                //addToDiv('dbData : '+dbScanData+', jsScanData : '+jsScanData);
                //alert('jsScanData : '+jsScanData);
				
				jsScanData = trim(jsScanData);
				dbScanData = trim(dbScanData);
				
				var diff=diffExistsInIPs(jsScanData, dbScanData);

				//alert('Diff Exists : '+diff);
				
				//LOGIC of the 3 blocks below:
				//if diff exists, refresh
				//else if we still have data, we check diff after a delay
				//else if we do not have data, we quit
				
                if(diff)
                {
					//addToDiv('Refresh Window... Nowww....');
	                refreshIPAMViews();  // refresh subnet scan page
					lastTimeAjaxCalled = 0;
                }
                else if (jsScanData!='' && dbScanData!='') // no diff but subnets are scanning
                {
					//addToDiv('will call ajax in '+subnetScanDelay+' secs');
					window.setTimeout('processSubnetScanInfo("'+dbScanData+'")',subnetScanDelay);
                }
                else
                {
					//addToDiv('final....jsScanData : \''+jsScanData+'\'  dbScanData : \''+dbScanData+'\'');
                }
            }
        }
    	}
    	catch(err)
    	{
	    	//alert('Unexpected error! Contact support@oputils.com with the screenshot of this page! : '+err.description);//No I18N
			refreshIPAMViews();  // refresh subnet scan page
    	}
    };

    var nowTime = new Date().getTime();
    if((nowTime - lastTimeAjaxCalled) >= subnetScanDelay) // avoiding multiple calls due to page navigation reload
    {
		//addToDiv('---------------------------------------------------');
	    //addToDiv('Ajax Request ...LastTimeAjaxCalled : '+lastTimeAjaxCalled+'|| Time diff : '+(nowTime - lastTimeAjaxCalled));
	    //addToDiv('Time diff : '+(nowTime - lastTimeAjaxCalled));
	    var url='/IPAddressScanSubnetAction.do?actionFrom=getSubnetScanInfo&uid='+new Date().getTime();//No I18N
	    req.open("POST",url, true);
	    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    req.send(null);
	    lastTimeAjaxCalled = nowTime;
	}
}

function diffExistsInIPs(jsScanData, dbScanData) //used in processSubnetScanInfo()
{
	if(jsScanData=='' && dbScanData=='')
	{
		return false;
	}
	//alert('jsScanData : '+jsScanData+'dbScanData : '+dbScanData);
	var jsScanDataArr = jsScanData.split(',');
	var dbScanDataArr = dbScanData.split(',');
	if(jsScanDataArr[0] != dbScanDataArr[0])
	{
		return true;
	}
	else if(jsScanDataArr.length > 1 && dbScanDataArr.length > 1)
	{
		var diffExists=null;
		for(var i=1;i<jsScanDataArr.length;i++) //ips start from array index 1. array index 0 has the array size
		{
		    diffExists=true;
			for(var j=1;j<dbScanDataArr.length;j++)
			{
				if(jsScanDataArr[i] == dbScanDataArr[j])
				{
					diffExists = false;
					break;
				}
			}
			if(diffExists)
			{
				break;
			}
		}
		//addToDiv('diffExists : '+diffExists);
		return diffExists;
	}
	return null;
}

function IPAddAliasNameModifiedAction()
{
   refreshIPMangerView("IPAddressAvailabilityView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("IPAMTreeSummaryView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("IPAddresssubnetView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("IPLevelSearchView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("IPLevelSearchView1",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));

   refreshIPMangerView("SPMSwitchResultView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("SPMInputView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("ConnectedIPInSPM",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));//No I18N

   refreshSubView("IPAMCustomFieldListView");
   refreshSubView("SPMCustomFieldListView");
   closeDialog();
}
function IPAddAliasNameModifiedAction123()
{
  // closeDialog();
   refreshIPMangerView("IPAddressAvailabilityView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("IPAMSummaryView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("IPAddresssubnetView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshIPMangerView("IPLevelSearchView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
   refreshSubView("CustomFieldListView");//Its use for customField do not   delete it.
}

function refreshIPMangerView(id,useOldState)
{
ViewAPI.refreshView({VIEWTOREFRESH_RN:id,USEOLDSTATE_RN:(useOldState == false),NAVIGABLE_RN:true});
}
function cancelAliasNameModifiedAction()
{
   var formDiv = document.getElementById("modifyAliasName_div");
   document.getElementById("modifyAliasName_container").appendChild(formDiv);
}

function refreshIPAMViews()
{
   window.clearInterval(intervalID);
   refreshSubView("IPAddresssubnetView");
   refreshSubView("IPAddressAvailabilityView");
}

function refreshSubnetViews()
{
   window.clearInterval(intervalID);
   refreshSubView("IPAddresssubnetView");
   refreshSubView("IPAddressAvailabilityView");
}

function IPAddSubnetModifiedAction()
{
    closeDialog();
    refreshSubnetViews();
}

function showAddField(val) {

   var addSubnetElem = document.getElementById(val);
   var addSubnetLinkElem = document.getElementById("addSubnetLink");

   if(addSubnetElem.style.display =="none") {
        window.clearInterval(intervalID);
       addSubnetElem.style.display="block";
        addSubnetLinkElem.style.display="none";
   } else {
       addSubnetElem.style.display="none";
       addSubnetLinkElem.style.display="block";
       //renderSubnet("IPAddresssubnetView.cc")
   }


}
function closeAddField(val)
{
    showAddField(val)
    //refreshIPAMViews();
    //renderSubnet("IPAddresssubnetView.cc")
}
function setIPMAction(f,action)
{
        //alert(action);
	f.actionFrom.value=action;
}

function validateInputValues()
{
    var daysVal = document.settingsForm.days.value
    if(daysVal.length == 0)
        {
               alert("Please enter the Number of Days value.");
                document.settingsForm.days.focus();
                return false;
        }
        if(parseInt(daysVal)  != daysVal)
        {
                alert("Number fo days value should be an integer.");
                document.settingsForm.days.focus();
                return false;
        }
        if(daysVal < 1 || daysVal > 299)
        {
                alert("Number of days value should be between 1 a nd 299.");
                document.settingsForm.days.focus();
                return false;
        }

        var url = '/IPAddressManager.do?&actionFrom=saveDays&days='+daysVal+'&uid='+new Date().getTime();
        persist(url);
}
function validateIPAddressSettings()
{
    if(document.subnetForm.actionFrom.value == "cancel")
    {
        showSwitchSettings()
        return false;
    }else if(document.subnetForm.actionFrom.value == "save")
    {
        validateInputValues();
        return false;
    }


    return true;
}

function showSwitchSettings() {
    var emailchaneIDElem = document.getElementById('emailchaneID');
    if(emailchaneIDElem.style.visibility =="visible") {
        emailchaneIDElem.style.visibility="hidden";
    }

    document.settingsForm.actionFrom.value="getNumberOfDays";
   var switchSettingElem = document.getElementById('policyTableID');
   if(switchSettingElem.style.visibility =="hidden") {
       switchSettingElem.style.visibility="visible";
       var url = '/IPAddressManager.do?&actionFrom=getNumberOfDays&uid='+new Date().getTime();;
       persist(url);
   } else {
       switchSettingElem.style.visibility="hidden";
   }

}
function persist(url)
{
        var ua = navigator.userAgent.toLowerCase();
        //alert(ua);
        if (window.XMLHttpRequest)
        {
                req = new XMLHttpRequest();
                req.onreadystatechange = processReqChangeDay;
                req.open("GET", url, true);
                req.send(null);
        }
        else if (window.ActiveXObject)
        {

                isIE = true;
                req = new ActiveXObject("Microsoft.XMLHTTP");
                if (req)
                {
                        req.onreadystatechange = processReqChangeDay;
                        req.open("GET", url, true);
                        req.send(null);
                }
        }else
        {

            req  = new ActiveXObject("Msxml2.XMLHTTP");
            isIE = true;
            if (req)
            {
                    req.onreadystatechange = processReqChangeDay;
                    req.open("GET", url, true);
                    req.send();
            }
        }

}

function processReqChangeDay()
{

        if (req.readyState == 4)
	{

		if (req.status == 200)
                {
                    var action = trim(document.settingsForm.actionFrom.value);
                    if(action == "getNumberOfDays")
                    {

                        var x = req.responseXML.getElementsByTagName('Settings');
                        var daysValue= trim(x[0].getAttribute("noOfDays"));
                        if(parseInt(daysValue)  == daysValue)
                        {
                            window.document.getElementById("days").value=daysValue;
                        }
                        else
                        {
                            window.document.getElementById("days").value="";
                        }
                    }
                    else if(action == "save")
                    {

                        var result = trim(req.responseText);

                        if(result=="Success")
                        {

                            showSwitchSettings();

                        }
                        else if(result=="Failure")
                        {
                            alert("Available policy days update Failed");
                        }

                    }if(action == "getMailID")
                    {
                       // alert(req.responseText);
                        var x = req.responseXML.getElementsByTagName('MailSettings');;
                        var resolveDNSValue = trim(x[0].getAttribute("toAddress"));
                        document.getElementById("toAdd").value=resolveDNSValue;

                        if(x[0].getAttribute("SoundOption") == "1")
                        {
                            document.settingsForm.selectSound.checked = true;
                        }else
                        {
                            document.settingsForm.selectSound.checked = false;
                        }

                        if(x[0].getAttribute("EmailOption") == "1")
                        {
                            document.settingsForm.emailID.checked = true;
                            document.settingsForm.toAdd.disabled=false;

                        }else
                        {
                            document.settingsForm.emailID.checked = false;
                            document.settingsForm.toAdd.disabled=true;
                        }
                         var count = trim(x[0].getAttribute("COUNT"));
                        document.getElementById("COUNT").value=count;

                        if(x[0].getAttribute("HISTORY_STATUS") == "1")
                        {
                            document.settingsForm.alertHisOption.checked = true;


                        }else
                        {
                            document.settingsForm.alertHisOption.checked = false;

                        }


                    }else if(action == "sendAlerts")
                    {
                       showMailOption("mailCancel");

                    }else if(action == "stopAlerts")
                    {
                        showMailOption("mailCancel");
                    }


                 }
		else
                {
			alert("There was a problem retrieving the XML data:\n" +req.statusText);
		}
	}
}

function validateIPPolicySettings()
{
    var actionVal = document.settingsForm.actionFrom.value;
    document.settingsForm.actionFrom.value
    if(actionVal == "cancel")
    {
        showSwitchSettings()
        return false;
    }else if(actionVal == "save")
    {

        validateInputValues();
        return false;

    }else if(actionVal == "sendAlerts")
    {
       return false;

    }else if(actionVal == "stopAlerts")
    {
        return false;
    }else if(actionVal == "mailCancel")
    {
        return false;
    }

}

function showMailOption(val)
{
    var switchSettingElem = document.getElementById('policyTableID');
    if(switchSettingElem.style.visibility =="visible")
    {
       switchSettingElem.style.visibility="hidden";
    }

    document.settingsForm.actionFrom.value=val;
    var emailchaneIDElem = document.getElementById('emailchaneID');
    if(emailchaneIDElem.style.visibility =="hidden") {

      emailchaneIDElem.style.visibility="visible";
      document.settingsForm.actionFrom.value="getMailID";
      var url = '/IPAddressManager.do?actionFrom=getMailID&uid='+new Date().getTime();
      persist(url);

   } else {
       emailchaneIDElem.style.visibility="hidden";
   }

}

function setButtonType(value)
{

             document.settingsForm.actionFrom.value = value;
             var toAddress = document.settingsForm.toAdd.value;
             var soundOption =document.settingsForm.selectSound.checked;
             var soundFile =document.settingsForm.soundFile.value;
             var mailOption = document.settingsForm.emailID.checked;

             var COUNT =document.settingsForm.COUNT.value;
             var historyOption = document.settingsForm.alertHisOption.checked;
             var HISTORY_STATUS = "0";
             if(historyOption == true)
                 {
                     HISTORY_STATUS = "1";
                 }
             if(value == "sendAlerts")
             {
                if(mailOption == true)
                {
                    toAdd1 = toAddress.split(",");
                    for(var i = 0 ; i< toAdd1.length ; i++)
                    {
                        if(!validateEmail(toAdd1[i]))
                        {
                            return false;
                        }
                    }
                }
                var url = '/IPAddressManager.do?&methodToCall=execute&actionFrom='+value+'&toAddress='+toAddress+'&soundOption='+soundOption+'&soundFile='+soundFile+'&mailOption='+mailOption+'&COUNT='+COUNT+'&HISTORY_STATUS='+HISTORY_STATUS+'&uid='+new Date().getTime();
                persist(url);

             }else if(value == "stopAlerts")
             {
                    var url = '/IPAddressManager.do?&methodToCall=execute&actionFrom='+value+'&toAddress='+toAddress+'&soundOption='+soundOption+'&soundFile='+soundFile+'&mailOption='+mailOption+'&uid='+new Date().getTime();;
                    persist(url);
             }
}
function validateRogue()
{
    return false;
}
function scheduleWindow(linkParams)
{
        if (navigator.appName == 'Netscape')
        {
                newwin=window.open("/framework/WOLScheduler.jsp?"+linkParams,"Schedule","screenX=300,screenY=250,scrollbars=no,toolbar=no,width=500,height=325","centre");
        }
        else
        {
                newwin=window.open("/framework/WOLScheduler.jsp?"+ linkParams,"Schedule","scrollbars=yes,toolbar=no,width=500,height=325","centre");
        }
}
//Newly added codes

function changeTabs(viewName,tabName)
{
    updateState('ipAddressManagerInputPage',"homeDetailTab",tabName,true);
    document.getElementById("homeDetailTab").value = tabName;
    document.getElementById("selectView").value = viewName;
    var localVar = "tt";
    changeStyle(viewName,tabName);

    var selID = tree.getSelectedItemId()
    netID = ""
    if(selID == "GROUP_0")
    {
        viewName = viewName+"?rootURL=true&treeIDValue="+tree.getSelectedItemId();

    }else
    {
       // var netID = getNodeChildSubnetIDs(selID);
        viewName = viewName+"?childNode=true&treeIDValue="+tree.getSelectedItemId();
    }
    renderCurrentView(viewName , localVar , netID);

     var msg = document.getElementById('MsgshowStatusID').value;
     if(msg == 'ShowNext') {
        renderCurrentView("AlertMsgBoard.cc?pageLevel=1","MSGTT")
     }
   // refreshSubView("IPAMMsgBoard");
}
function changeIPAMHomeTabs(viewName,tabName )
{
     var localVar = "ipamHomeID";
     changeIPAMHomeStyle(viewName,tabName);
     renderIPAMGraph(viewName+"?" , localVar ,"");
     //loadTree();
     var msg = document.getElementById('MsgshowStatusID').value;
//     var pageLvl = document.getElementById('PageLevelID').value;
     if(msg == 'ShowNext') {
        renderCurrentView("AlertMsgBoard.cc?pageLevel=1","MSGTT")
     }

}
function assignDates(fromDate,toDate) {
    document.getElementById('AuditFromDate').value = fromDate;
    document.getElementById('AuditToDate').value = toDate;
}
function renderCurrentView(viewName , localVar , netID)
{
   var myAnonFunction = function(response,reqOptions)
   {
	   if(document.getElementById(localVar))
	   {
    	   document.getElementById(localVar).innerHTML = response.getOnlyHtml();
	   }
   };
   if(!netID){
       AjaxAPI.sendRequest({URL:viewName,ONSUCCESSFUNC:myAnonFunction});
   }else{
       AjaxAPI.sendRequest({URL:viewName,PARAMETERS:"",ONSUCCESSFUNC:myAnonFunction});
   }
   window.SPM_VIEW=viewName+"?";
}
function renderTreeCurrentView(viewName , localVar)
{
    var selID = tree.getSelectedItemId();
    var childTrees = tree.getAllSubItems(selID)
    //var netIDs = getChildIDs(childTrees);
    viewName = viewName+"&childNode=true";
    renderCurrentView(viewName , localVar ,"");
}

function changeIPAMHomeStyle(viewName,tabName)
{

    var nwinfo="nwinfo";
    var ipamreports="ipamreports";
    var ipamAudit="ipamAudit";


    if(tabName == undefined)
    {

     nwinfo="nwinfo";
     ipamreports="ipamreports";
     ipamAudit="ipamAudit";

    }
    if(viewName == "ipAddressManager.cc")
    {
        changeBackgroundBlock(nwinfo);
        changeBackgroundNone(ipamreports);
        changeBackgroundNone(ipamAudit);


    }
    else if(viewName == "IPAMReport.cc")
    {
        changeBackgroundNone(nwinfo);
        changeBackgroundBlock(ipamreports);
        changeBackgroundNone(ipamAudit);


    }
    else if(viewName == "AuditView.cc")
    {
        changeBackgroundNone(nwinfo);
        changeBackgroundNone(ipamreports);
        changeBackgroundBlock(ipamAudit);


    }
}
function changeStyle(viewName,tabName)
{

    var summary="summary";
    var input="input";
    var alerts="alert";
    var ipHistory ="ipHistory";

    if(tabName == undefined)
    {

        summary="intabsummary";
        input="intabinput";
        alerts="intabalert";
        ipHistory ="intabipHistory";

    }
    if(viewName == "IPAddressSummaryTableView.cc")
    {
        changeBackgroundBlock(summary);
        changeBackgroundNone(input);
        changeBackgroundNone(alerts);
        changeBackgroundNone(ipHistory);

    }
    else if(viewName == "IPAddresssubnetView.cc")
    {
        changeBackgroundNone(summary);
        changeBackgroundBlock(input);
        changeBackgroundNone(alerts);
        changeBackgroundNone(ipHistory);

    }
    else if(viewName == "IPAddressAlerts.cc")
    {
        changeBackgroundNone(summary);
        changeBackgroundNone(input);
        changeBackgroundBlock(alerts);
        changeBackgroundNone(ipHistory);

    } else if(viewName == "IPHistoryView.cc")
    {
        changeBackgroundNone(summary);
        changeBackgroundNone(input);
        changeBackgroundNone(alerts);
        changeBackgroundBlock(ipHistory);
    }
}

function  changeBackgroundNone(tdName)
{
    document.getElementById(tdName+"1").style.backgroundImage='url(/images/switch_tab_deselect_bg.gif)';
    document.getElementById(tdName+"2").src='/images/switch_tab_deselect_left.gif';
    document.getElementById(tdName+"3").style.backgroundImage='url(/images/switch_tab_deselect_bg.gif)';
    document.getElementById(tdName+"4").className="tabdeselectedtxt";
    document.getElementById(tdName+"5").src='/images/switch_tab_deselect_right.gif';
}

function  changeBackgroundBlock(tdName)
{
    document.getElementById(tdName+"1").style.backgroundImage='url(/images/switch_tab_select_bg.gif)';
    document.getElementById(tdName+"2").src='/images/switch_tab_select_left.gif';
    document.getElementById(tdName+"3").style.backgroundImage='url(/images/switch_tab_select_bg.gif)';
    document.getElementById(tdName+"4").className="tabselectedtxt";
    document.getElementById(tdName+"5").src='/images/switch_tab_select_right.gif';
}

function settingTab(viewName,tabName) {
    if(viewName == "IPAMGenrelSettings.cc") {
        changeBackgroundBlock(tabName);
        changeBackgroundNone("c"+tabName);
        changeBackgroundNone("owner");
        changeBackgroundNone("wmi");
        changeBackgroundNone("cf");
        changeBackgroundNone("publish");
        changeBackgroundNone("router");
        changeBackgroundNone("group");//No I18N
    } else if(viewName == "IPAMConfigureAlert.cc") {
        changeBackgroundBlock(tabName);
        changeBackgroundNone("settings");
        changeBackgroundNone("owner");
        changeBackgroundNone("wmi");
        changeBackgroundNone("cf");
        changeBackgroundNone("publish");
        changeBackgroundNone("router");
        changeBackgroundNone("group");//No I18N
    } else if(viewName == "OwnerMgmt.cc") {
        changeBackgroundBlock(tabName);
        changeBackgroundNone("settings");
        changeBackgroundNone("csettings");
         changeBackgroundNone("wmi");
        changeBackgroundNone("cf");
        changeBackgroundNone("publish");
        changeBackgroundNone("router");
        changeBackgroundNone("group");//No I18N
    } else if(viewName == "WindowsCredentialListView.cc") {
        changeBackgroundBlock(tabName);
        changeBackgroundNone("settings");
        changeBackgroundNone("csettings");
        changeBackgroundNone("owner");
        changeBackgroundNone("cf");
        viewName = viewName+"?chosenTab=WMI";
        changeBackgroundNone("publish");
        changeBackgroundNone("router");
        changeBackgroundNone("group");//No I18N
    } else if(viewName == "IPAMCustomFieldListView.cc") {
        changeBackgroundBlock(tabName);
        changeBackgroundNone("owner");
        changeBackgroundNone("settings");
        changeBackgroundNone("csettings");
        changeBackgroundNone("wmi");
        changeBackgroundNone("publish");
        changeBackgroundNone("router");
        changeBackgroundNone("group");//No I18N
    } else if(viewName == "AutoPublish.cc") {
        changeBackgroundBlock(tabName);
        changeBackgroundNone("owner");
        changeBackgroundNone("settings");
        changeBackgroundNone("csettings");
        changeBackgroundNone("wmi");
        changeBackgroundNone("cf");
        changeBackgroundNone("router");
        changeBackgroundNone("group");//No I18N
    } else if(viewName == "RouterListView.cc") {
        changeBackgroundBlock(tabName);
        changeBackgroundNone("owner");
        changeBackgroundNone("settings");
        changeBackgroundNone("csettings");
        changeBackgroundNone("wmi");
        changeBackgroundNone("cf");
        changeBackgroundNone("publish");
        changeBackgroundNone("group");//No I18N
    } else if(viewName == "SubnetGroupConfig.cc") {//No I18N
        changeBackgroundBlock(tabName);
        changeBackgroundNone("owner");//No I18N
        changeBackgroundNone("settings");//No I18N
        changeBackgroundNone("csettings");//No I18N
        changeBackgroundNone("wmi");//No I18N
        changeBackgroundNone("cf");//No I18N
        changeBackgroundNone("publish");//No I18N
    }

    var localVar = "tt";
    renderCurrentView(viewName , localVar);
}

function addSubnet(viewName,tabName)
{
    var treeID = tree.getSelectedItemId();
    document.getElementById("treeID").value = treeID;

    var temp = treeID.split("_");
    var parentID = temp[0];
    if(parentID == "SUBNET")
        {
            treeID = tree.getParentId(tree.getSelectedItemId());
            temp = treeID.split("_");
            parentID = temp[0];
        }
    if(temp.length > 1)
    {
        parentID = temp[1];
    }

    var parentName = tree.getItemText(treeID);
    var parentPath = getParentPathWithIfon(treeID);

    showURLInDialog('/framework/AddSubnetList.jsp?isAddFromTree=true&parentID='+parentID+"&parentName="+encodeURIComponent(parentName)+"&parentPath="+encodeURIComponent(parentPath)+'&uid='+new Date().getTime(),'position=absolute,modal=yes,top=30,left=250,width=650,scrollbars=no,title=Add Subnet');//No I18N
    changeTabs(viewName,tabName);
}

function addMenuSubnet(menuItemName,refId,additionalParams,index)
{
     var treeID = tree.getSelectedItemId();
    document.getElementById("treeID").value = treeID;

    var temp = treeID.split("_");
    var parentID = temp[0];
    if(parentID == "SUBNET")
        {
            treeID = tree.getParentId(tree.getSelectedItemId());
            temp = treeID.split("_");
            parentID = temp[0];
}
    if(temp.length > 1)
    {
        parentID = temp[1];
    }

    var parentName = tree.getItemText(treeID);
    var parentPath = getParentPathWithIfon(treeID);
    showURLInDialog('/framework/AddSubnetList.jsp?isAddFromTree=true&parentID='+parentID+"&parentName="+encodeURIComponent(parentName)+"&parentPath="+encodeURIComponent(parentPath)+'&uid='+new Date().getTime(),'position=absolute,modal=yes,top=30,width=650,left=250,scrollbars=no,title=Add Subnet');//No I18N
}

function routerMsg()
{
    showURLInDialog('/ipam/RouterTextMsg.jsp','position=absolute,modal=yes,top=150,left=250,width=300,scrollbars=no,title=Discover Subnets from Routers');
}

function checkSubnet(f)
{
    computeForm(f);
    var maskVal=trim(f.mask.value);
    msgDisplay(maskVal);
}
function changeSubnet(f)
{
    calibrateSubnet(f)
    var maskVal=trim(f.mask.value);
    msgDisplay(maskVal);
}

function msgDisplay(maskVal)
{
    if(!checkClassA(maskVal))
    {
        if(maskVal == "255.255.0.0")
        {
            document.getElementById("subnetMsg").innerHTML="You have specified a Class B Subnet. This might have an impact in the performance.";
        }
        else
        {
            document.getElementById("subnetMsg").innerHTML="You have specified a Class A Subnet. This might have an impact in the performance.";
        }
    }
    else if(!checkClassB(maskVal))
    {
        if(!(maskVal=="255.255.255.0"))
        {
            document.getElementById("subnetMsg").innerHTML="You have specified a Class B Subnet. This might have an impact in the performance.";
        }
        else
        {
            document.getElementById("subnetMsg").innerHTML="";
        }

    }
    else
    {
        document.getElementById("subnetMsg").innerHTML="";
    }
}

function checkClassA(maskVal)
{
    var temp = maskVal.split(".");
    if(temp[2]=="0" && temp[3]=="0")
    {
        return false;
    }
    return true;
}

function checkClassB(maskVal)
{
    var temp = maskVal.split(".");

    if (temp[3]=="0")
    {
        return false;
    }
    return true;
}

function checkSubnetDetail(mask)
{
    var msg = "";
    if(!checkClassA(mask))
    {
        msg="Do you want to add this Class A Subnet?";
        if(mask=="255.255.0.0")
        {
            msg="Do you want to add this Class B Subnet?";
        }
    }
    else if(!checkClassB(mask))
    {
         if(!(mask=="255.255.255.0"))
        {
            msg="Do you want to add this Class B Subnet?";
        }
    }

    if((msg.length) > 0)
    {
        if (confirm(msg))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    return true;
}

function  checkRowSelect(menuItemName,refId,additionalParams,index)
{
  var tblModel = getTableModel(refId);
  var selectRow=tblModel.getSelectedRowIndices(refId);
  if(selectRow.length<=0)
  {
       alert("Select IPAddress");
       return false;
  }
  else
  {
       var menuItemObj = getMenuItemObj(menuItemName);
       confirmtext = confirm(menuItemObj.CONFIRMSTRING);
       if (confirmtext==true)
       {
           var actUrl = menuItemObj.getActionURL(refId,additionalParams,index);
           menuItemObj.invokeActionURL(actUrl,refId);
       }
       else
       {
           return false;
       }
  }
}

function IPLevelSubnetModify(sNetID,subnet,sMask,sName,sDesc,sValn,sLoc,sScanDetail,domainID,groupID)
{
    var netID = sNetID;
    var subnetAddress = subnet;
    var subnetMask = sMask;
    var subnetname  = sName;
    var desc = sDesc;
    var vlan = sValn;
    var loc =sLoc;
    var scanDetails = sScanDetail;
     var treeID = tree.getSelectedItemId();
    document.getElementById("treeID").value = treeID;

    var temp = treeID.split("_");
    var parentID = temp[0];
    if(parentID == "SUBNET")
        {
            treeID = tree.getParentId(tree.getSelectedItemId());
            temp = treeID.split("_");
            parentID = temp[0];
        }
    if(temp.length > 1)
    {
        parentID = temp[1];
    }

    var parentName = tree.getItemText(treeID);
    var parentPath = getParentPathWithIfon(treeID);

    showURLInDialog('/lan/IPAddressMod.jsp?ipAddress='+subnetAddress+'&netID='+netID+'&subnetMask='+subnetMask+'&subnetname='+encodeURIComponent(subnetname)+'&desc='+encodeURIComponent(desc)+'&vlan='+encodeURIComponent(vlan)+'&loc='+encodeURIComponent(loc)+'&scanDetails='+scanDetails+'&parentID='+parentID+'&groupID='+groupID+'&parentName='+encodeURIComponent(parentName)+'&parentPath='+encodeURIComponent(parentPath)+'&domainID=FetchFromDB&uid='+new Date().getTime() ,'position=absmiddle,modal=yes,scrollbars=no,title=Modify Subnet');//No I18N
}

function updateFiled(txt)
{
    document.getElementById("callFor").value = txt;
}
var time;

function getAjaxObject()
{
        var req = null;
        if(window.XMLHttpRequest)
        {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            req  = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return req;
}

function IPLevelScanNow(sNetID)
{
    document.getElementById("scanMsg").style.display = "block";
    var url='/IPAddressScanSubnetAction.do?netID='+sNetID+'&actionFrom=IPLevelScan&uid='+new Date().getTime();//No I18N
    var req = getAjaxObject();
    req.open("POST",url, true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(null);

    refreshSubView("IPAddressAvailabilityView");//No I18N

    //scan_disabled.gif
}

    function persistValues(url)
    {
	    var req = getAjaxObject();
        req.onreadystatechange = function()
        {
            if(req.readyState == 4)
            {
                if(req.status == 200)
                {
                    var text = trim(req.responseText);

					if(text != "1")
                    {
	                    refreshSubView("IPAddressAvailabilityView");//No I18N
                    }
                    else
                    {
	                    window.setTimeout("persistValues('"+url+"')",10000);
                    }
              }
            }
        };
        req.open("POST",url, true);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(null);
    }

function getStatusID()
{
    var sNetID = document.getElementById("netID").value;
    var url='/IPAddressScanSubnetAction.do?netID='+sNetID+'&actionFrom=getStatusId';//No I18N
    window.setTimeout("persistValues('"+url+"')",10000);
}



function showDropDown(e , id , id1)
{
    var x = getActualLeftSide(document.getElementById(id));
    var y = getActualTopSide(document.getElementById(id));
    var scrollLeft = document.body.scrollLeft;
    var scrollTop = document.body.scrollTop;
    x = x-scrollLeft + 5;
    y = y-scrollTop + 5;
    showURLInDialog('/ipam/SearchDropDown.jsp?uid='+new Date().getTime(),'position=absolute,modal=no,scrollbars=no,left='+x+',top='+y+',width=205,title=Search Drop Down,closeOnBodyClick=yes')
}
function getActualLeftSide(oElement) {

    var iLeft = 0;
    var oNode = oElement;
    while (oNode != document.body) {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }
    return iLeft-1;
}

function getActualTopSide(oElement) {

    var iTop = 0;
    var oNode = oElement;
    while (oNode != document.body) {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    return iTop+16;
}
var oldId = "0";
function showHideImage(id) {
    var hidValue = document.getElementById('selectedValueID').value;
    if(id != hidValue) {
        document.getElementById(hidValue).src = "/images/spacer.gif";
    }
    if(oldId != "0" && oldId != id) {
         document.getElementById(oldId).src = "/images/spacer.gif";
         document.getElementById(id).src="/images/tick_icon.gif";
    }
    oldId = id;
}

var addOldId = "0";
function selectforAddSearch(id) {
    document.getElementById(id).src="/images/tick_icon.gif";
    var hidValue = document.getElementById('addintionValueID').value;
    if(id != hidValue) {
        document.getElementById(hidValue).src = "/images/spacer.gif";
    }
    if(addOldId != "0" && oldId != id) {
         document.getElementById(addOldId).src = "/images/spacer.gif";
         document.getElementById(id).src="/images/tick_icon.gif";
    }
    addOldId = id;
    var selectedToolID = document.getElementById("selectedToolID").value
    var url = "/commonaction.do?actionFrom=storeSearchType&selectValue="+id+"&selectedToolID="+selectedToolID+"&searchKey=additionalSearchKey";//No I18N
    AjaxAPI.sendRequest({URL:url,"METHOD":"POST"});//No I18N
}

function selectforSearch(id)
{
    showHideImage(id)
    document.getElementById(id).src="/images/tick_icon.gif";
    document.getElementById("selectValue").value = id;
    if(document.getElementById("SEARCH_VALUE") != undefined)
    {
        document.getElementById("SEARCH_VALUE").value = id;
    }
    var selectedToolID = document.getElementById("selectedToolID").value
    var url = "/commonaction.do?actionFrom=storeSearchType&selectValue="+id+"&selectedToolID="+selectedToolID+"&searchKey=searchKey";//No I18N
//    AjaxAPI.sendRequest({URL:url,ONSUCCESSFUNC:closeLayer});
    AjaxAPI.sendRequest({URL:url,"METHOD":"POST"});//No I18N
}

function closeLayer()
{
    var searchValue = document.getElementById("SEARCH_VALUE");
    if(!searchValue) {
        searchValue = document.getElementById('textfield222');
        searchValue.focus();
    }
closeDialog();
}


function addOwner(menuItemName,refId,additionalParams,index)
{
   showURLInDialog('/ipam/OwnerAddForm.jsp','position=absolute,modal=yes,top=100,left=300,scrollbars=no,title=Add Owner');
}

function modifyOwner(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("Owner.OWNERID");
   var colInd2  = tblModel.getColumnIndex("Owner.NAME");
   var colInd3  = tblModel.getColumnIndex("Owner.LOCATION");
   var colInd4  = tblModel.getColumnIndex("Owner.DESIGNATION");
   var colInd5  = tblModel.getColumnIndex("Owner.EMAIL");
   var colInd6  = tblModel.getColumnIndex("Owner.PHON_NUMBER");

   var ownerId = tblModel.getValueAt(index,colInd1);
   var ownerName = tblModel.getValueAt(index,colInd2);
   var loc = tblModel.getValueAt(index,colInd3);
   var designation  = tblModel.getValueAt(index,colInd4);
   var emailid = tblModel.getValueAt(index,colInd5);
   var pnumber= tblModel.getValueAt(index,colInd6);
   showURLInDialog('/ipam/OwnerAddForm.jsp?ownerId='+ownerId+'&ownerName='+encodeURIComponent(ownerName)+'&loc='+encodeURIComponent(loc)+'&designation='+encodeURIComponent(designation)+'&emailid='+encodeURIComponent(emailid)+'&pnumber='+encodeURIComponent(pnumber),'position=relative,modal=yes,scrollbars=no,title=Modify User');//No I18N
}

function deleteOwner(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("Owner.OWNERID");
   var colInd2  = tblModel.getColumnIndex("Owner.NAME");
   var ownerID = tblModel.getValueAt(index,colInd1)
   var ownerName = tblModel.getValueAt(index,colInd2)

   var txt="Are you sure you want to delete the owner "+ownerName+"?";
   var confirmtxt=confirm(txt);
   if (confirmtxt == false)
   {
       return false;
   }
   else
   {
       var actUrl = menuItemObj.getActionURL(refId,additionalParams,index);
       actUrl=actUrl+"&ownerID="+ownerID+"&ownerName="+encodeURIComponent(ownerName);//No I18N
       menuItemObj.invokeActionURL(actUrl,refId);
   }
}



function setActionValueWMI(actionValue)
    {

     f= document.schedulerForm;
    document.getElementById("response_layer").innerHTML="";
    document.schedulerForm.actionFrom.value = actionValue;
    if(validateWMIParams())
    {
        var WMILoginName = f.WMILoginName.value;
        var WMIPassword = f.WMIPassword.value;
        var WMIDomainName = f.WMIDomainName.value;
        var WMIDomainControllerName = f.WMIDomainControllerName.value;
        var url = "/IPAddressManager.do?actionFrom="+actionValue+"&WMILoginName="+encodeURIComponent(WMILoginName)+"&WMIPassword="+WMIPassword+"&WMIDomainName="+encodeURIComponent(WMIDomainName)+"&WMIDomainControllerName="+encodeURIComponent(WMIDomainControllerName)+"&uid="+new Date().getTime();//No I18N
        persistWMI(url);
    }

}
 function persistWMI(url)
    {
        var req = null;
        if(window.XMLHttpRequest)
        {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            req  = new ActiveXObject("Microsoft.XMLHTTP");
        }
        req.onreadystatechange = function()
        {
            if(req.readyState == 4)
            {
                if(req.status == 200)
                {
                   if(document.schedulerForm.actionFrom.value == "restoreWMIDefaults")
                    {
                        document.schedulerForm.WMILoginName.value="";
                        document.schedulerForm.WMIPassword.value="";
                        document.schedulerForm.WMIDomainName.value="";
                        document.schedulerForm.WMIDomainControllerName.value="";
                    }
                     document.getElementById("response_layer").innerHTML= " Your changes have been saved";
              }
            }
        };
        req.open("POST",url, true);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(null);
    }
function onSucessFun(resOptions, reqOptions)
{
  var msg = trim(resOptions.responseText);
  if(msg.length > 0 )
  {
        document.getElementById("response_layer").innerHTML = msg;
        //document.getElementById("response_layer").innerHTML="Your changes have been saved";
       // window.setInterval("hideMsgDiv()",3000);
}
}
function PopUpMenuForwardIP(menuItemName,refId,additionalParams,index)
{
     var tblModel = getTableModel(refId);

   var colInd4  = tblModel.getColumnIndex("IPResources.FORWORD_ADDRINLONG");
   var ipAddress = tblModel.getValueAt(index,colInd4)

    showURLInDialog('/framework/TroubleShootSystem.jsp?addressinlong='+ipAddress+'&community=public&convertIP=true','position=relative,top=-20,left=70,modal=no,scrollbars=no,title=System TroubleShoot,closeOnBodyClick=yes')


}
/* Tool List  tools code start */
function PopUpMenu(menuItemName,refId,additionalParams,index)
{
   var yPos =  findPosY(index);

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);

   var colInd1  = tblModel.getColumnIndex("IPResources2.RESOURCEID");
   var colInd2  = tblModel.getColumnIndex("IPResources2.ADDRINLONG");
   var colInd3  = tblModel.getColumnIndex("IPResources2.IPADDRESS");
   var colInd4  = tblModel.getColumnIndex("IPResources2.FORWORD_ADDRINLONG");
   var community = tblModel.getValueAt(index,colInd1)

   var aliasName = tblModel.getValueAt(index,colInd2)
   var ipAddress = tblModel.getValueAt(index,colInd3)
   var flag = 'false';

   if(!aliasName)
   {

      colInd2  = tblModel.getColumnIndex("IPResources.ADDRINLONG");
      colInd4  = tblModel.getColumnIndex("CiscoResources.CHASSIS_ID");
      colInd3  = tblModel.getColumnIndex("IPResources.IPADDRESS");
      aliasName = tblModel.getValueAt(index,colInd2);
      ipAddress = tblModel.getValueAt(index,colInd3)
      var chass_id = tblModel.getValueAt(index,colInd4);

      if(chass_id)
      {
         flag = 'true';
      }

      if(!aliasName)
      {
           colInd1  = tblModel.getColumnIndex("NetMonState.IPADDRESS");
           ipAddress = tblModel.getValueAt(index,colInd1);
           if(!ipAddress)
           {
               colInd1  = tblModel.getColumnIndex("BandWidthHost.IPADDRESS");
               ipAddress = tblModel.getValueAt(index,colInd1);
               if(!ipAddress)
               {
                   colInd1  = tblModel.getColumnIndex("ConfigFileInputConfig.IPADDRESS");
                   colInd2  = tblModel.getColumnIndex("ConfigFileInputConfig.COMMUNITY");
                   ipAddress = tblModel.getValueAt(index,colInd1);
                   community = tblModel.getValueAt(index,colInd2);
                   flag = 'true';
                   if(!ipAddress) {
                       colInd1  = tblModel.getColumnIndex("CFMCSVInputConfig.DEVICENAME");
                       colInd2  = tblModel.getColumnIndex("CFMCSVInputConfig.WRITECOMMUNITY");
                       ipAddress = tblModel.getValueAt(index,colInd1);
                       community = tblModel.getValueAt(index,colInd2);
                   }
               }

           }


      }

   }

  if(!ipAddress)
  {
     colInd1  = tblModel.getColumnIndex("IPHistory.IPADDRESS");
     ipAddress = tblModel.getValueAt(index,colInd1);
  }

   var visibleHeight =	(window.opera) ? document.body.clientHeight || document.documentElement.clientHeight || window.innerHeight
		: window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;

   showURLInDialog('/framework/TroubleShootSystem.jsp?ipAddress='+ipAddress+'&community='+community+'&flag='+flag,'position=relative,top=-20,left=70,modal=no,scrollbars=no,title=System TroubleShoot,closeOnBodyClick=yes')

}
 function setSubnet(uniqueId , subnet)
  {

      updateState(uniqueId,"NETWORKADDRESS",subnet,true);
      updateState(uniqueId,"SEARCH_VALUE",null,true);
      refreshSubView(uniqueId);
      return false;
  }
  function setSubnetView(uniqueId , subnet)
  {
      var selectedSubnet = subnet.split("/");
      subnet = selectedSubnet[0];

      updateState(uniqueId,"NETWORKADDRESS",subnet,true);
      updateState(uniqueId,"SELTAB",document.getElementById("SELTAB").value,true);
      updateState(uniqueId,"PARENTTREEID",document.getElementById("PARENTTREEID").value,true);
      updateState("IPAddressAvailabilityView","NETWORKADDRESS",subnet,true);
      updateState("IPAddressAvailabilityView","dnsFailure","All",true);
      updateState("IPAddressAvailabilityView","PARENTTREEID",document.getElementById("PARENTTREEID").value,true);
      var newTreeID = getNewSelectedID(subnet);
      tree.selectItem(newTreeID,true);
      var parentPath = getParentPath(newTreeID);
      updateState("IPAddressAvailabilityView","parentPath",parentPath,true);
      updateState(uniqueId,"parentPath",parentPath,true);
      //refreshSubView(uniqueId);
      return false;
  }
  function changeSummaryTabs(viewName,tabName)
{

     var localVar = "subnetSummary";

     changeSummaryStyle(viewName,tabName);

     //refreshSubView(uniqueId);
     var NETWORKADDRESS = document.getElementById("NETWORKADDRESS").value;
     viewName = viewName+"&NETWORKADDRESS="+NETWORKADDRESS;

     renderCurrentView(viewName , localVar);

}
function changeSummaryTabs123(viewName,tabName,dnsFailure)
{
     var localVar = "subnetSummary";

     changeSummaryStyle(viewName,tabName);

     // refreshSubView(uniqueId);
     var NETWORKADDRESS = document.getElementById("NETWORKADDRESS").value;
     viewName = viewName+"&NETWORKADDRESS="+NETWORKADDRESS+"&dnsFailure="+dnsFailure+"&filterValue=dns_"+dnsFailure;
     renderCurrentView(viewName , localVar);

}
function changeSummaryStyle( viewName,tabName)
{

    document.getElementById("SELTAB").value = tabName
    var subnetSummary="subnetSummary";
    var history="history";
    var alerts = "alerts";
    if(viewName == "IPAddressAvailabilityView.cc?")
    {
        changeBackgroundBlock(subnetSummary);
        changeBackgroundNone(history);
        changeBackgroundNone(alerts);

    }else if(viewName == "IPHistoryView.cc?isSupnetOpt=false")
    {
        changeBackgroundNone(subnetSummary);
        changeBackgroundBlock(history);
        changeBackgroundNone(alerts);
    }else if(viewName == "IPAddressAlerts.cc?isSupnetOpt=false")
    {
        changeBackgroundNone(subnetSummary);
        changeBackgroundNone(history);
        changeBackgroundBlock(alerts);
    }
    return true;
}

function exportipHistory(viewName , val )
{
    if(window.OWN_EXPORT == undefined)
    {
             var ar;
             if(window.NO_MCK_PDF )
             {
                    var queryString = viewName.split(val);
                    ar = trim(window.SPM_VIEW);
                    ar = ar + queryString[1];
             }
             else if(window.TAB_VIEW_NAME)
             {
                 ar = trim(window.TAB_VIEW_NAME);
                 var noExportView = false;
                 if(window.TRIAL_VIEW)
                 {
                    noExportView = true;
                 }
                 ar = updateStateCookieAndAppendSid(ar);
              }else if(window.ROOT_VIEW_ID)
             {
                ar = getViewURL(ROOT_VIEW_ID);
                ar = updateStateCookieAndAppendSid(ar);
                var csvAndXlsView = true;
                if(window.NO_CSV_VIEW)
                {
                    csvAndXlsView = false;
                }

                var noExportView = false;
                if(window.TRIAL_VIEW)
                {
                    noExportView = true;
                }

              }else if(window.NO_MCK_VIEW)
              {
                ar = trim(window.NO_MCK_VIEW_NAME);
              }

                if(val == "pdf")
                 {
                    ar = ar.replace(/.cc\?/,".pdf?");
                 }else if(val == "csv")
                 {
                    ar = ar.replace(/.cc\?/,".csv?");

                 }else
                 {
                      ar = ar.replace(/.cc\?/,".xls?");
                 }

          ar = ar+"&Export=true";//No I18N
          var index = ar.indexOf('SPMSwitchResultView');
          if(index != -1) {
              setACTableColumns();
          }
          newwin= window.open(ar);
          newwin.focus();

    }else{

          newwin = window.open(viewName  ,'Export',230,220,0);
          newwin.focus();
    }
}


//setACTableColumns only call for switch result export pages
function setACTableColumns() {
    var url = "/SwitchPortMapper.do?actionFrom=setAcTableColumn";//No I18N
    processRequestForSetACTableColumn(url);
}

function processRequestForSetACTableColumn(url) {
    var req = null;
    if(window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        isIE=true;
        req  = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.onreadystatechange = function() {
        if(req.readyState == 4) {
            if(req.status == 200) {
                var doc=req.responseText;
//                alert(doc);
            }
        }
    };
    req.open("POST", url, true);
    req.send(null);
}
    function isIE()
    {
	    var ua = navigator.userAgent.toLowerCase();
	    if ( ua.indexOf( "msie" ) != -1 )
	    {
			return true;
		}
		else
		{
			return false;
		}
    }

function importIPDetails()
{
      var networkAdd =document.getElementById('NETWORKADDRESS').value;
      var cfFileDir = document.getElementById('CFFileDir').value;
      var toolName = document.getElementById('toolName').value;
      var displayName ="Alias Name";
      var windowheight=470;
      if(isIE())
      {
	      windowheight=530;
      }
      newwin=window.open('/importIPDatas.cc?NETWORKADDRESS='+networkAdd+'&displayName='+displayName+'&cfFileDir='+cfFileDir+'&toolName='+toolName,"CustomTool","resizable=yes,screenX=300,screenY=250,scrollbars=yes,toolbar=no,width=675,height="+windowheight,"centre")
}

function importSwitchPortDetails()
{
	var switchID = document.getElementById("RESOURCEID").value;
	var switchName = document.getElementById("SwitchName").value;
	var cfFileDir = document.getElementById('CFFileDir').value;
    var toolName = document.getElementById('toolName').value;
    var displayName ="Alias Name";
    newwin=window.open('/ImportSwitchPort.cc?SwitchID='+switchID+'&displayName='+displayName+"&SwitchName="+switchName+'&cfFileDir='+cfFileDir+'&toolName='+toolName,"CustomTool","resizable=yes,screenX=300,screenY=250,scrollbars=yes,toolbar=no,width=675,height=470","centre")
}

function closeDialogBox()
{
    document.importForm.actionFrom.value = "close";
    closeDialog()
}


function setActionValues(value)
{
     document.routerAddForm.actionFrom.value=value;
}
/* Tools list code end */
function getAction()
{
    var fromList = eval('document.forms[0].selectedSwitches');
    var selColumnTxt = "";
    var selColumn = "";
    for(i=0; i < fromList.options.length ; i++)
    {
        var current = fromList.options[i].value ;
        //if(current != "IPADDRESS")
        {
            selColumn = selColumn+current;
        }
        var noteDispVal = fromList.options[i].text;
        if(noteDispVal.indexOf('(') > -1)
        {
        	noteDispVal = noteDispVal.substring(0,noteDispVal.lastIndexOf('(')-1);
    	}
        selColumnTxt = selColumnTxt+noteDispVal ;
        if(i+1 < fromList.options.length)
        {
            //if(current != "IPADDRESS")
            {
                selColumn = selColumn+",";
            }
            selColumnTxt  = selColumnTxt+", ";
        }
    }
    document.getElementById("groupErrorMssg").innerHTML = selColumnTxt;
    document.schedulerForm.columnName.value=selColumn;
}
function copyToList(optionValue , from,to, hasEnumTypes)
{

    var fromList = eval('document.forms[0].'+from);
    var toList = eval('document.forms[0].'+to);

    var selList;
    var fullList = new Array();
    if(hasEnumTypes)
    {
	    if(optionValue == 'true')
	    {
		    selList = toList;
	    }
	    else
	    {
		    selList = fromList;
	    }

	    for(i=0; i < fromList.options.length ; i++)
	    {
		    fullList[i]=fromList.options[i].value;
	    }
	    for(i=0; i < toList.options.length ; i++)
	    {
		    fullList[i+fromList.options.length]=toList.options[i].value;
	    }
	}

    if(toList.options.length > 0 && toList.options[0].value == 'temp')
    {
        toList.options.length =0;
    }
    var sel =false;
    for(i=0; i < fromList.options.length ; i++)
    {
        var current = fromList.options[i];
        if(current.selected)
        {
            sel =true;
            if(current.value == 'temp')
            {
                alert ('You cannot move this text!');
                return;
            }
            txt = current.text;
            val = current.value;
            if(optionValue == "true")
            {
                var alreadyExist = false;
                for(j = 0 ; j < toList.options.length ; j++)
                {
                    var toValue = toList.options[j].text;
                    if(toValue == txt)
                    {
                        alreadyExist = true;
                    }
                }
                if(!alreadyExist)
                {

                    // var toList1 = eval('document.forms[0].selectedSwitches');
                    toList.options[toList.length]=new Option(txt  ,val);
                    if(current.getAttribute('enumType'))
                    {
	                    toList.options[toList.length-1].setAttribute('enumType', current.getAttribute('enumType'));
                    }
                    if(current.getAttribute('dataType'))
                    {
	                    toList.options[toList.length-1].setAttribute('dataType', current.getAttribute('dataType'));
                    }
                    if(current.className)
                    {
	                    toList.options[toList.length-1].className = current.className;
                    }
                    fromList.options[i]=null;
                    i--;
                }
                else
                {
                    alert("Already added  the device : "+txt);
                }

            }else
            {
                if(current.value == 'IPADDRESS')
                {
                    alert ('You cannot remove \"IP Address\" column');
                }
                else if(current.value == 'IFINDEX')
                {
                    alert ('You cannot remove \"ifIndex\" column');

                }else
                {
                    fromList.options[i]=null;
                    toList.options[toList.length]=new Option(txt  ,val);
                    if(current.getAttribute('enumType'))
                    {
	                    toList.options[toList.length-1].setAttribute('enumType', current.getAttribute('enumType'));
                    }
                    if(current.getAttribute('dataType'))
                    {
	                    toList.options[toList.length-1].setAttribute('dataType', current.getAttribute('dataType'));
                    }
                    if(current.className)
                    {
	                    toList.options[toList.length-1].className = current.className;
                    }
                    i--;
                }
            }

        }
    }
    if(!sel)
    {
        if(optionValue == "true")
        {
            alert ('Please select a column to move');

        }else
        {
            alert ('Please select a column to remove');
        }
    }

    getAction();

    if(hasEnumTypes)
    {
    	displayImportEnumDataLinks(selList,fullList);
	}
}

function displayImportEnumDataLinks(selList,fullList)
{
	var enumTypePresent = false;
	for(i=0;i<fullList.length;i++)
	{
		var colFound = false;
		for(j=0; j < selList.options.length ; j++)
	    {
		    var selOption = selList.options[j];
		    var enumAttr = selOption.getAttribute('enumType');
		    if(enumAttr && enumAttr=='true' && selOption.value == fullList[i])
		    {
			    colFound = true;
			    break;
		    }
	    }

	    var listElem = document.getElementById(fullList[i]+'_link');

	    if(colFound && listElem)
	    {
		    listElem.style.display='';
		    enumTypePresent = true;
	    }
	    else if(!colFound && listElem)
	    {
		    listElem.style.display='none';
	    }
	}

	var enumTypeMsgBoard = document.getElementById('EnumTypeMsgBoard');
	var enumTypeMsgBoard1 = document.getElementById('EnumTypeMsgBoard1');
	if(enumTypePresent)
	{
		enumTypeMsgBoard.style.display='';
		enumTypeMsgBoard1.style.display='';
	}
	else
	{
		enumTypeMsgBoard.style.display='none';
		enumTypeMsgBoard1.style.display='none';
	}
}

var importIntervalID = "";
function windowClose()
{
    window.clearInterval(importIntervalID);

    importIntervalID = window.setInterval('window.close()',60000);
}

function validateImportForm(f)
{
    var button = document.schedulerForm.actionFrom.value
    if(button == "close")
    {
        if( trim(document.schedulerForm.isAction.value) == "true")
        {
            window.opener.document.hostTestForm.actionFrom.value="ipAvailability_tab";
            window.opener.document.hostTestForm.NETWORKADDRESS.value=document.schedulerForm.NETWORKADDRESS.value;
            window.opener.document.hostTestForm.submit();
            window.close()
        }
        else
        {
            window.close();
        }
        return false;
    }
    else if(button == "close_port")
    {
        if( trim(document.schedulerForm.isAction.value) == "true")
        {
            window.opener.document.SwitchDetailsRefreshForm.submit();
            window.close()
        }
        else
        {
            window.close();
        }
        return false;
    }
    else if(button == "importIPDetails" || button == "ImportSwitchPortDetails")
    {
        getAction()
        var fromList = eval('document.forms[0].selectedSwitches');

        if(fromList.options.length == 0){
            alert("Select atleast one column to import ")
            return false;
        }

        var path = document.schedulerForm.csvPath.value
        if(path.length == 0)
        {
            alert("Select a CSV file ");
            return false;
        }
        else
        {
            var splitFile = path.split(".");
            var fileType = (splitFile[splitFile.length - 1]).toLowerCase();
            if(fileType != 'csv' && fileType != 'txt' && fileType != 'xls')
            {
	            alert("Import a csv file");
	            return false;
            }
            window.clearInterval(intervalID);
            intervalID = window.setInterval('windowClose()',1000);
            document.getElementById('ImportSubmit').disabled=true;
            return true;
        }

    }


    return false;
}
function closeWindow(url)
{
    window.opener.document.hostTestForm.actionFrom.value="ipAvailability_tab";
    window.opener.document.hostTestForm.NETWORKADDRESS.value=url;
    window.opener.document.hostTestForm.submit();
    window.close()
}

function setActionValue(f,action,isAction)
{
    f.actionFrom.value=action;
    f.isAction.value =isAction
}

function setAction123(button,action)
{
    button.form.actionFrom.value=action;
}
function openErrorFile(file)
{
    var url ='/IPAddressManager.do?actionFrom=downLoadCSV';
    window.open(url,"htmlExportForm","menubar=1,scrollbars=1,status=1,toolbar=1,resizable","center");
}

function clearSearchValue()
{
    document.getElementById('SEARCH_VALUE').value = "";
}
function checkIPAMToadd(f)
{
    	if(f.emailID.checked )
	{
		f.toAdd.disabled=false;
                f.IPAM_IP_STATE_CHANGED.disabled=false;
                f.IPAM_REVERSE_DNS_FAIL.disabled=false;
                f.IPAM_FORWARD_DNS_FAIL.disabled=false;
                f.IPAM_FORWARD_DNS_IP_MISSMATCH.disabled=false;

                f.IPAM_IP_STATE_CHANGED.checked=true;
                f.IPAM_REVERSE_DNS_FAIL.checked=true;
                f.IPAM_FORWARD_DNS_FAIL.checked=true;
                f.IPAM_FORWARD_DNS_IP_MISSMATCH.checked=true;

//                f.transToAvail.checked=true;
                f.IPAM_LOW_IP_UTILIZE.checked=true;
                f.IPAM_HIGH_IP_UTILIZE.checked=true;
//                f.transToAvail.disabled=false;
                f.IPAM_LOW_IP_UTILIZE.disabled=false;
                f.IPAM_HIGH_IP_UTILIZE.disabled=false;

	}
	else
	{
            f.toAdd.disabled=true;
            f.IPAM_IP_STATE_CHANGED.disabled=true;
            f.IPAM_REVERSE_DNS_FAIL.disabled=true;
            f.IPAM_FORWARD_DNS_FAIL.disabled=true;
            f.IPAM_FORWARD_DNS_IP_MISSMATCH.disabled=true;

            f.IPAM_IP_STATE_CHANGED.checked=false;
            f.IPAM_REVERSE_DNS_FAIL.checked=false;
            f.IPAM_FORWARD_DNS_FAIL.checked=false;
            f.IPAM_FORWARD_DNS_IP_MISSMATCH.checked=false;

//            f.transToAvail.checked=false;
            f.IPAM_LOW_IP_UTILIZE.checked=false;
            f.IPAM_HIGH_IP_UTILIZE.checked=false;

//            f.transToAvail.disabled=true;
            f.IPAM_LOW_IP_UTILIZE.disabled=true;
            f.IPAM_HIGH_IP_UTILIZE.disabled=true;

	}

}
function getDetails()
{
      document.settingsForm.actionFrom.value="getMailID";
      var url = '/IPAddressManager.do?actionFrom=getMailID&uid='+new Date().getTime();
      persist(url);
}
function validateEmailInput()
{

            var value = "sendAlerts";
             document.settingsForm.actionFrom.value = value;
             var toAddress = document.settingsForm.toAdd.value;
             document.settingsForm.toAddress.value=toAddress;
             var soundOption =document.settingsForm.selectSound.checked;
             var soundFile =document.settingsForm.soundFile.value;
             var mailOption = document.settingsForm.emailID.checked;
             document.settingsForm.mailOption.value=document.settingsForm.emailID.checked;
             document.settingsForm.soundOption.value=document.settingsForm.selectSound.checked;

             var COUNT =document.settingsForm.COUNT.value;
             var historyOption = document.settingsForm.alertHisOption.checked;
             var HISTORY_STATUS = "0";

            var daysVal = document.settingsForm.days.value;
            if(daysVal.length == 0)
            {
                alert("Please enter the Number of Days value.");
                document.settingsForm.days.focus();
                return false;
            }
            if(parseInt(daysVal)  != daysVal)
            {
                alert("Number fo days value should be an integer.");
                document.settingsForm.days.focus();
                return false;
            }
            if(daysVal < 1 || daysVal > 299)
            {
                alert("Number of days value should be between 1 a nd 299.");
                document.settingsForm.days.focus();
                return false;
            }
             if(historyOption == true)
                 {
                     HISTORY_STATUS = "1";
                 }
                 document.settingsForm.HISTORY_STATUS.value=HISTORY_STATUS;
             if(value == "sendAlerts")
             {
                if(mailOption == true)
                {
                    if( !document.settingsForm.IPAM_IP_STATE_CHANGED.checked  &&  !document.settingsForm.IPAM_REVERSE_DNS_FAIL.checked  && !document.settingsForm.IPAM_FORWARD_DNS_FAIL.checked && !document.settingsForm.IPAM_FORWARD_DNS_IP_MISSMATCH.checked
                        && !document.settingsForm.IPAM_LOW_IP_UTILIZE.checked && !document.settingsForm.IPAM_HIGH_IP_UTILIZE.checked)
                    {
                            alert("Please select atleast one option to send email ")
                            return false;
                    }else{
                        toAdd1 = toAddress.split(",");
                        for(var i = 0 ; i< toAdd1.length ; i++)
                        {
                            if(!validateEmail(toAdd1[i]))
                            {
                                return false;
                            }
                    }
                  }
                }
             }
             return  true;
 }
 function showSummaryDiv()
{

    var newstates=(document.getElementById("state123").value);
    var treeNodeID = document.getElementById("treeNodeID").value

    var netID = "";
    if(treeNodeID)
        {
          //  netID = getNodeChildSubnetIDs(treeNodeID);
        }
        if(netID.length == 0)
            {
           //     netID = "&TD=0"
            }

   var viewName = "";
   var URL = "";
    if(newstates == "1")
    {
        viewName = "IPAMDNSFailureView.cc";
        URL = "dnsFailureString=true";
    }else if(newstates == "2")
    {
        viewName = "AllIPAvailabilityReservedReport.cc";
        URL = "reservedStatus=3";
    }else if(newstates == "3")
    {
        viewName = "RogueSummary.cc";
        URL = "rogueTypeString=true";
    }else if(newstates == "4")
    {
        viewName = "NICTypeSummaryView.cc";
        URL = "nicTypeString=true";

    }else if(newstates == "6")
    {
            viewName = "IPAMADSummary.cc"
             URL = "PARTOFAD=true";
    }else {

        viewName = "IPAMInventoryView.cc";
        URL = "baseTypeString=true";
    }
    document.getElementById("selectGraph").value = newstates;
       var temp = treeNodeID.split("_");
                        var treeNodeID = temp[0];
                        if(temp.length > 1)
                        {
                            treeNodeID = temp[1];
                        }
    viewName = "/IPAMUpdateURLToGraph.cc?viewName="+viewName+"&childNode=true&treeIDValue="+treeNodeID+"&"+URL+"&SelectTreeID="+tree.getSelectedItemId();
    renderIPAMGraph(viewName , "ipamSubnetSumID" ,  netID)



}
function ShowSelectDiv(divId)
{
	var id = document.getElementById(divId);
	id.style.display = "block";
}
function HideSelectDiv(divId){
	var id = document.getElementById(divId);
	id.style.display = "none";
}
function checkGuestSelect(menuItemName,refId,additionalParams,index)
{
  var tblModel = getTableModel(refId);
  var selectRow=tblModel.getSelectedRowIndices(refId);
  if(selectRow.length <= 0)
  {
       alert("Select device(s) to move as Guest");
       return false;
  }
  else
  {
           var colInd1  = tblModel.getColumnIndex("RogueResources.RESOURCEID");
           var selValue = (index == null)? tblModel.getSelectedRowIndices(refId):[index];

           var resID="";
           for(var i = 0; i < selValue.length; i++)
           {
               var residValue = ""+tblModel.getValueAt(selValue[i],colInd1);

               if(residValue != "null")
                {

                        resID +="&RESOURCEID="+residValue

                }
           }
            if(resID.length == 0)
             {
                  alert("Please select a valid device(s) to move as Guest");
                  return false;
             }
            showURLInDialog('/ipam/guestConfig.jsp?&actionFrom=trustConfigTempDevice&'+resID,'position=relative,modal=yes,scrollbars=no,title=Configure Guest Validity Period')

        }
}
function showAllDetails(viewName , view , title)
{
    var NETID = document.getElementById("subNETID").value;
    var NETWORKADDRESS = document.getElementById("NETWORKADDRESS").value;
    showURLInDialog('expandGraph.cc?viewName='+viewName+"&view="+view+"&NETID="+NETID+"&NETWORKADDRESS="+NETWORKADDRESS+"&title="+title,'position=auto,top=10,modal=yes,scrollbars=no,width=1000,height=500,title='+title+" : "+NETWORKADDRESS)
}
function showAllIPAMDetails(viewName , view , title)
{
    showURLInDialog('expandGraph.cc?viewName='+viewName+"&view="+view+"&title="+title,'position=auto,top=10,modal=yes,scrollbars=no,width=1000,height=500,title='+title)
}

        function EnablePublish(enablePublish, backupType, fileType, noOfBackUp, publishLocationFlag) 
		{
            document.getElementById('noOfBackUp').value = noOfBackUp;
            if(enablePublish == '1') {
                document.getElementById('enablePublish').checked = true;
                if(backupType == '2') {
                    document.getElementById("maintainMax").checked = true;
                    document.getElementById("maintainLastScan").checked = false;
                } else {
                    document.getElementById("maintainLastScan").checked = true;
                    document.getElementById("maintainMax").checked = false;
                }
                if(fileType == '2') {
                    document.getElementById("publishCsv").checked = false;
                    document.getElementById("publishHtml").checked = true;
                } else {
                    document.getElementById("publishHtml").checked = false;
                    document.getElementById("publishCsv").checked = true;
                }
                checkIpamPublishLocation(publishLocationFlag)
            } else {
                document.getElementById('enablePublish').checked = false;
                document.getElementById('maintainLastScan').disabled=true;
                document.getElementById('maintainMax').disabled=true;
                document.getElementById('publishCsv').disabled=true;
                document.getElementById('publishHtml').disabled=true;
                document.getElementById('noOfBackUp').disabled=true;
                document.getElementById('DefaultLocation').disabled = true;
                document.getElementById('SpecifyLocation').disabled = true;
            }
        }
		
        function checkIpamPublishLocation(val) {
            if(val == '1') { // this is default location
                document.getElementById('defaultDirID').style.display = "block";
                document.getElementById('userSpecifyDirID').style.display = "none";
                document.getElementById('histLocationFlag').value= "1";// Default location, if user changed the location, it will set as 2
                document.getElementById('DefaultLocation').checked = true;
            } else {
                document.getElementById('userSpecifyDirID').style.display = "block";
                document.getElementById('defaultDirID').style.display = "none";
                document.getElementById('histLocationFlag').value= "2";
                document.getElementById('SpecifyLocation').checked = true;
            }
        }
		
        function checkBackup() {
            if(document.getElementById('enablePublish').checked) {
                document.getElementById('maintainLastScan').disabled=false;
                document.getElementById('maintainMax').disabled=false;
                document.getElementById('publishCsv').disabled=false;
                document.getElementById('publishHtml').disabled=false;
                document.getElementById('noOfBackUp').disabled=false;
                document.getElementById('DefaultLocation').disabled = false;
                document.getElementById('SpecifyLocation').disabled = false;
            } else {
                document.getElementById('maintainLastScan').disabled=true;
                document.getElementById('maintainMax').disabled=true;
                document.getElementById('publishCsv').disabled=true;
                document.getElementById('publishHtml').disabled=true;
                document.getElementById('noOfBackUp').disabled=true;
                document.getElementById('DefaultLocation').disabled = true;
                document.getElementById('SpecifyLocation').disabled = true;
            }
        }

function setAutoPublish(action,f) 
{
    document.getElementById("response_text").innerHTML="";
    var enablePublish = '0';
    if(document.getElementById("enablePublish").checked) {
        enablePublish = '1';
    }
    var fileType  = document.getElementById("publishCsv").value;
	if(document.getElementById("publishHtml").checked)
	{
		fileType = document.getElementById("publishHtml").value;
	}
    
	var backupType  = document.getElementById("maintainMax").value;
	if(document.getElementById("maintainLastScan").checked)
	{
		backupType = document.getElementById("maintainLastScan").value;
	}
	
	var noOfBackUp = document.getElementById("noOfBackUp").value;
    
    var publishLocationChoice = document.getElementById("SpecifyLocation").value;
	if(document.getElementById("DefaultLocation").checked)
	{
		publishLocationChoice = document.getElementById("DefaultLocation").value;
	}
	
    if(noOfBackUp < 0) {
        alert("Number of back up must be greater than 0");//No I18N
        return;
    }

    var defaultPublishPath = document.getElementById("userSpecifyDir").value;
    var publishPath = document.getElementById("newIPAMHistoryRootDir").value;
    if(publishLocationChoice == '2' && publishPath.length == 0) {
        alert("Publish path cannot be empty");//No I18N
        return;
    }
	
    var url = "/IPAddressManager.do?actionFrom="+action+"&enablePublish="+enablePublish+"&fileType="+fileType+"&backupType="+backupType+"&noOfBackUp="+noOfBackUp+"&publishLocationChoice="+publishLocationChoice+"&publishpath=" +publishPath+"&userSpecifyDir="+defaultPublishPath;//No I18N
    sendPublishAction(url);
}

function sendPublishAction(url) {
    var req = null;
    if(window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject){
        req  = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.onreadystatechange = function(){
        if(req.readyState == 4){
            if(req.status == 200){

             document.getElementById("response_text").innerHTML= " Your changes have been saved";
          }
        }
    };
    req.open("POST",url, true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(null);
}

function hideMsgDiv()
{
    document.getElementById("response_layer").innerHTML="";
}

function testCredential()
{
    f= document.schedulerForm;
    var WMILoginName = f.WMILoginName.value;
    var WMIPassword = f.WMIPassword.value;
    var WMIDomainName = f.WMIDomainName.value;
    var WMIDomainControllerName = f.WMIDomainControllerName.value;

}


function validateWMIParams()
{


    f= document.schedulerForm;
    var WMILoginName = trim(f.WMILoginName.value);
    var WMIPassword = trim(f.WMIPassword.value);
    var WMIDomainName = trim(f.WMIDomainName.value);
    var WMIDomainControllerName = trim(f.WMIDomainControllerName.value);
    var adminStatus = trim(f.adminStatus.value);
    if(WMILoginName == '')
    {
        alert("Administrator login name cannot be empty string");
        return false;
    }
    if(WMIPassword  == '')
    {
        alert("Administrator Password  cannot be empty string");
        return false;
    }
    if(WMIDomainName  == '')
    {
        alert("Domain name/Workgroup cannot be empty string");
        return false;
    }
    if(!checkRecurrenceValues(this.form))
    {
       return false;
    }
    return true;
}


function persistADScanNow(url)
{
    var req = null;
    if(window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        req  = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.onreadystatechange = function()
    {
        if(req.readyState == 4)
        {
            if(req.status == 200)
            {
                var result = trim(req.responseText);
                if(result == "1")
                {
                    document.getElementById("adScan").src='/images/loading_img.gif';
                    document.getElementById("adScanMsg").style.display = "block";
		    		setTimeout ( "getADStatus()" , 5000 ) ;
                }
                else
                {
                    document.getElementById("adScan").src='/images/scan_ad.gif';
                    document.getElementById("adScanMsg").style.display = "none";
                    afterScan();
                }
            }
        }
    };
    req.open("POST",url, true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(null);
}

function afterScan()
{
}

function  getADStatus()
{
  var url = "/IPAddressManager.do?actionFrom=getADStatus&uid="+new Date().getTime();
  persistADScanNow(url);
}


function displayADDetails(menuItemName,refId,additionalParams,index)
{

   var menuItemObj = getMenuItemObj(menuItemName);
   var tblModel = getTableModel(refId);
   var colInd1  = tblModel.getColumnIndex("IPResourcesExt.AD_ID");
   var adID = tblModel.getValueAt(index,colInd1);
   showURLInDialog('/ipam/ADDetailsView.jsp?adID='+adID,'position=absolute,top=100,left=325,modal=yes,scrollbars=no,title=AD Computer Details')
}

function adScanNowFromDomainList()
{
    var url = "/IPAddressManager.do?actionFrom=adScanNow&uid="+new Date().getTime();
    AjaxAPI.sendRequest({URL:url,"METHOD":"POST"});
    refreshSubView('WindowsCredentialListView');
}

function adScanNow()
{
    var url = "/IPAddressManager.do?actionFrom=adScanNow&uid="+new Date().getTime();
    persistADScanNow(url);
}
function ipamSetSubnet(uniqueId , subnet , childNode)
  {
      //var childNode = document.getElementById("childNode").value;
      updateState(uniqueId,"NETWORKADDRESS",subnet,true);
      updateState(uniqueId,"childNode",childNode,true);
      if(document.getElementById("actionFrom").value == "ipam_saerch_tab")
          {
            refreshSubView(uniqueId);
          }else{
       var childTrees = tree.getSubItems(tree.getSelectedItemId())
        var netID = getChildIDs(childTrees);
      var url = uniqueId+".cc?NETWORKADDRESS="+subnet+"&childNode="+childNode;
      //
      renderIPAMGraph(url,"tt" , netID);
  }
      return false;
  }
var partofAD = null;
function moveIPAction()
{
	var action=document.getElementById('moveaction').value;
	if(action=="Reserved")
	{
		invokeMenuAction('markAsReserve', 'IPAddressAvailabilityView',null);
	}
	else if(action=="NotReserved")
	{
                invokeMenuAction('markAsUnReserve', 'IPAddressAvailabilityView',null)
	}
	else if(action=="ReservedStaicIP")
	{
                invokeMenuAction('markAsReserveStatic', 'IPAddressAvailabilityView',null)
	}
	else if(action=="used")
	{
                invokeMenuAction('markAsUsed', 'IPAddressAvailabilityView',null)
	}
	else if(action=="transient")
	{
                invokeMenuAction('markAsTransient', 'IPAddressAvailabilityView',null)
	}
	else if(action=="available")
	{
                invokeMenuAction('markAsAvailable', 'IPAddressAvailabilityView',null)

	}else if(action=="2")
	{
                invokeMenuAction('markAsTrusted', 'IPAddressAvailabilityView',null)

	}else if(action=="3")
	{
                invokeMenuAction('markAsRogue', 'IPAddressAvailabilityView',null)

	}else if(action=="4")
	{
            invokeMenuAction('guestConfig', 'IPAddressAvailabilityView',null)
	}
	document.getElementById('moveaction').options[0].selected = "selected";
}
function changeFilter(uniqueId)
{
    var filterValue=trim(document.getElementById('filteraction').value);
    var temp=filterValue.split("_");
    var state=temp[1];
    var reserved=temp[0];

    var stateValue,reservedStatus;
    if(state == "Used")
    {
        stateValue=1;
    }
    else if(state == "Transient")
    {
        stateValue=2;
    }
    else if(state == "Available")
    {
        stateValue=3;
    }
    else if(state == "NotScan")
    {
        stateValue=5;
    }
    if(reserved == "res")
    {
        reservedStatus=2;
    }
    else if(reserved == "resStatic")
    {
        reservedStatus=3;
    }
    else if(reserved == "notRes")
    {
        reservedStatus=1;
    }
    var rogueType = "All";
    if(reserved == 'rogueType')
    {
        dnsState = "All";
        setFilterState(uniqueId, stateValue , reservedStatus , filterValue ,  dnsState , state);

    }else if(reserved == 'dns')
    {

        setFilterState(uniqueId, stateValue , reservedStatus , filterValue , state ,rogueType);

    }
    else if(reserved == "In AD")
    {
        partofAD = true;
        availState = "all";
        updateState(uniqueId,"ADTYPE","In AD",true);
        setFilterState(uniqueId, stateValue , reservedStatus , filterValue , state,rogueType);
    }
   else if(reserved == "Not in AD")
   {
        partofAD = true;
        availState = "all";
        updateState(uniqueId,"ADTYPE","Not in AD",true);
        setFilterState(uniqueId, stateValue , reservedStatus , filterValue , state,rogueType);
   }
   else
   {
        state = "All"
        setFilterState(uniqueId, stateValue , reservedStatus , filterValue , state,rogueType);
    }
}
function setFilterState(uniqueId , availState , reservedStatus , filterValue ,dnsFailure,rogueType)
{

   updateState(uniqueId,"STATUS",availState,true);
   updateState(uniqueId,"reservedStatus",reservedStatus,true);
   updateState(uniqueId,"filterValue",filterValue,true);
   updateState(uniqueId,"dnsFailure",dnsFailure,true);
   updateState(uniqueId,"rogueType",rogueType,true);
   updateState(uniqueId,"PARTOFAD",partofAD,true);
   refreshSubView(uniqueId);
}
function showCalDiv(uniqueId)
{
    var newstates=(document.getElementById("state1").value);

    updateState(uniqueId,"selectGraph",newstates,true);
    var netid  = document.getElementById("subNETID").value;
    var viewName = "";
    if(newstates == "1")
    {

        viewName = "IPAMSubnetDNSFailureView.cc?";


    }else if(newstates == "2")
    {

        viewName = "IPSubnetReservedReport.cc?";
    }else if(newstates == "3")
    {

        viewName = "RogueSubnetSummaryView.cc?";
    }else if(newstates == "4")
    {

        viewName = "NICTypeSubnetSummaryView.cc?";
    } else if(newstates == "6")
        {
            viewName = "SubnetPartofADReport.cc?";
        }else
        {

            viewName = "InventorySubnetView.cc?";
        }
        //alert(newstates);
         document.getElementById("selectGraph").value = newstates;
    renderIPAMGraph(viewName+"NETID="+netid , "ipamSubnetSumID" )

}
function ShowSelectDiv(divId)
{
	var id = document.getElementById(divId);
	id.style.display = "block";
}
function HideSelectDiv(divId){
	var id = document.getElementById(divId);
	id.style.display = "none";
}
 function setAvaialabilityState(uniqueId , availState,filterValue)
  {
    var temp=filterValue.split("_");
    var state=temp[1];
    var reserved=temp[0];
    var reservedStatus = "";
    var dnsStat = "All";
    var rogueType = "All"
    var inventryType = "All"
    var partofaD = null;

    if(reserved == "resStatic")
    {
        reservedStatus=3;
        updateState("IPSubnetReservedReport","filterValue",filterValue,true);
    }else if(reserved == "dns")
    {
        dnsStat=availState;
        availState = "all";
        updateState("IPAMSubnetDNSFailureView","filterValue",filterValue,true);
    }else if(reserved == "rogueType")
    {
        rogueType = availState;
        availState = "all";
        updateState("RogueSubnetSummaryView","filterValue",filterValue,true);
    }
    else if(reserved == "In AD")
    {
        availState = "all";
        partofaD = "true";
        updateState(uniqueId,"ADTYPE","In AD",true);
        updateState("SubnetPartofADReport","filterValue",filterValue,true);
    }
   else if(reserved == "Not in AD")
   {
        availState = "all";
        partofaD = "true";
        updateState(uniqueId,"ADTYPE","Not in AD",true);
        updateState("SubnetPartofADReport","filterValue",filterValue,true);
   }
      updateState(uniqueId,"STATUS",availState,true);
      updateState(uniqueId,"reservedStatus",reservedStatus,true);
      updateState(uniqueId,"filterValue",filterValue,true);
      updateState(uniqueId,"dnsFailure",dnsStat,true);
      updateState(uniqueId,"rogueType",rogueType,true);
      updateState(uniqueId,"inventryType",inventryType,true);
      updateState(uniqueId,"PARTOFAD",partofaD,true);
      refreshSubView(uniqueId);
  }
   function setReservedState(uniqueId , reservedStatus)
  {
      var availState = "All";
      updateState(uniqueId,"STATUS",availState,true);
      updateState(uniqueId,"reservedStatus",reservedStatus,true);
      refreshSubView(uniqueId);
  }

  function setSearchState(uniqueId , searchStr)
  {
      updateState(uniqueId,"SEARCH_VALUE",searchStr,true);
      refreshSubView(uniqueId);
      return false;
  }
  function divEle()
  {
     var x =scale1.offsetLeft;
     document.getElementById("pointer").style.left = x + 40 ;
     document.getElementById("pointer").style.display = "block";
  }

function showNextRange(val)
{
    var childTrees = tree.getAllSubItems(tree.getSelectedItemId())
    var netID = getChildIDs(childTrees);
    var t=val.split("?");
    var viewName = "IPAMSummarBarChart.cc?childNode=true&"+t[1]+"&"+document.getElementById("other").value;
    renderIPAMGraph (viewName , "ipamBarChartID" , netID);
}
function updateStateVaule(u)
{
    var u=t[1].split("&");
    for(var q=0;q<u.length;q++){

        var keyVal = u[q].split("=");

        updateState("IPAMSummaryChart",keyVal[0],keyVal[1],true);

    }
}
function submitGraphViewForm(f)
{
    var Range  = f.RANGE.value;
    var selID = tree.getSelectedItemId();
    var childTrees = tree.getAllSubItems(selID)
    var netID = getChildIDs(childTrees);
    var t = "PAGE_NUMBER=1&FROM_INDEX=1&TO_INDEX="+Range+"&RANGE="+Range+"&recordsPerPage="+Range;
    var viewName = "IPAMSummarBarChart.cc?childNode=true&"+t+"&"+document.getElementById("other").value;
    renderIPAMGraph (viewName , "ipamBarChartID" , netID);

	return false;

}

function getDeleteAllStatusMsg(resOptions, reqOptions)
{
    var treeID = tree.getSelectedItemId();
    var childTrees = tree.getAllSubItems(treeID)
    if(childTrees)
    {
        var temp = childTrees.split(",");
        for(var i =0; i< temp.length ; i++)
        {
            var childid = temp[i]
            var childids = childid.split("_");
            if(childids[0] == "SUBNET")
            {
                tree.deleteItem(childid);
            }
        }
    }
}
function getDeleteStatusMsg(resOptions, reqOptions)
{
    var msg = resOptions.responseText;
    if(msg != null)
    {
        var txtID =  msg.split("_");
        var gid = txtID[1].split(",");
        for(var i=0; i < gid.length-1; i++)
        {
            var gidName = trim(gid[i]);
            gidName = "SUBNET_"+gidName;
            tree.deleteItem(gidName);
        }
    }
    return false;
}
function closeAlertWithMsg(id,msgID,username,closingId) {
    document.getElementById(id).style.display='none';
    var url='/commonaction.do?actionFrom=CloseAlert&msgId='+msgID+'&username='+encodeURIComponent(username)+'&closingId='+closingId+'&uid='+new Date().getTime();//No I18N
    sendUrlForCloseAlert(url,"MsgBoard");
    document.getElementById('MsgshowStatusID').value = "ShowNext";
}

 function sendUrlForCloseAlert(url,flagMsg) {
    var req = null;
    if(window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
       isIE=true;
       req  = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.onreadystatechange = function() {
        if(req.readyState == 4) {
            if(req.status == 200) {
                var text=req.responseText;
                if(flagMsg == 'SubNetCount') {
                     document.getElementById('subnetCountMsg').innerHTML = text;
                 }
            }
            else {
                alert("Error");
            }
       }
    };
    req.open("POST",url, true);
    req.send(null);
}
function setIpUtilization(IpUsage,IpUtl) {
   showURLInDialog('/network/SPMAlertPolicy.jsp?IpUsage='+IpUsage+'&IpUtl='+IpUtl+"&Tool=IPAM",'position=relative,modal=yes,width=400,scrollbars=no,title=IP Utilization');
}
function showGivenValueIPAM(lowPortUtlSwitch,portUtl) {
    if(portUtl == 'LowUtl') {
        document.getElementById("lowIpUsageOfSubnet").innerHTML = lowPortUtlSwitch +'%';
    } else {
        document.getElementById("highIpUsageOfSubnet").innerHTML = lowPortUtlSwitch +'%';
    }
}

 function showallMask()
    {
        var tdValue = "<select class='ComboTextfield' value='255.255.255.0' onchange='calibrateSubnet(this.form)' size='1' name='mask' STYLE='width:130px;'>";
        tdValue +="<optgroup label='Class A'>";
        tdValue +="<option value='255.0.0.0' >255.0.0.0</option>";
        tdValue +="<option value='255.128.0.0' >255.128.0.0</option>";
        tdValue +="<option value='255.192.0.0' >255.192.0.0</option>";
        tdValue +="<option value='255.224.0.0' >255.224.0.0</option>";
        tdValue +="<option value='255.240.0.0' >255.240.0.0</option>";
        tdValue +="<option value='255.248.0.0' >255.248.0.0</option>";
        tdValue +="<option value='255.252.0.0' >255.252.0.0</option>";
        tdValue +="<option value='255.254.0.0' >255.254.0.0</option>";
        tdValue +="<optgroup label='Class B'>";
        tdValue +="<option value='255.255.0.0' >255.255.0.0</option>";
        tdValue +="<option value='255.255.128.0'>255.255.128.0</option>";
        tdValue +="<option value='255.255.192.0' >255.255.192.0</option>";
        tdValue +="<option value='255.255.224.0' >255.255.224.0</option>";
        tdValue +="<option value='255.255.240.0' >255.255.240.0</option>";
        tdValue +="<option value='255.255.248.0' >255.255.248.0</option>";
        tdValue +="<option value='255.255.252.0' >255.255.252.0</option>";
        tdValue +="<option value='255.255.254.0' >255.255.254.0</option>";
        tdValue +="<optgroup label='Class C'>";
        tdValue +="<option value='255.255.255.0' >255.255.255.0</option>";
        tdValue +="<option value='255.255.255.128' >255.255.255.128</opton>";
        tdValue +="<option value='255.255.255.192' >255.255.255.192</option>";
        tdValue +="<option value='255.255.255.224' >255.255.255.224</option>";
        tdValue +="<option value='255.255.255.240' >255.255.255.240</option>";
        tdValue +="<option value='255.255.255.248' >255.255.255.248</option>";
        tdValue +="<option value='255.255.255.252' >255.255.255.252</option>";
        tdValue +="<option value='255.255.255.254' >255.255.255.254</option>";
        tdValue +="<option value='255.255.255.255' >255.255.255.255</option>";
        tdValue +="</select>";
        tdValue +="<br><a href='javascript:defaultMask();' class='linktxt'><div style='padding-top:4px'>Show Default Mask</div></a>"
        document.getElementById("maskID").innerHTML = tdValue;
    }
     function defaultMask()
    {
        document.getElementById("maskID").innerHTML = "<select class='ComboTextfield' value='255.255.255.0' onchange='calibrateSubnet(this.form)' size='1' name='mask' STYLE='width:130px;'></select><br><a href='javascript:showallMask();' class='linktxt' ><div style='padding-top:4px'>Show all Masks</div></a>";
        var formName = document.subnetAddForm;
        if(!formName) {
            computeForm(document.approveForm);
        } else {
            computeForm(formName);
        }

    }
    function OpenSmtpSettingsLayer() {
        showURLInDialog('/framework/SmtpServerSettings.jsp','position=relative,modal=yes,width=400,scrollbars=no,title=SMTP server settings');
    }

     function showIpRange(f) {
         var subnetAddress = f.NETWORKADDRESS.value;
         var mask = f.mask.value;
         if(subnetAddress.length > 0 && mask.length > 0 && subnetAddress != '0.0.0.0') {
             var subnet = computeNetAddress(f.ipAddress.value , mask);
             f.ipAddress.value = subnet;
             sendUrlForCloseAlert("/IPAddressManager.do?actionFrom=getSubnetCount&subnetAddress="+subnetAddress+"&mask="+mask,"SubNetCount");
         }
     }

    function downloadErrorFile(moduleName,userName,fileUniqueStr)
	{
    	var urlCvs = '/ipam/DownloadErrorCsv.jsp?actionFrom=DownloadErrorCsv&moduleName='+moduleName+'&userName='+encodeURIComponent(userName)+'&fileUniqueStr='+fileUniqueStr;//No I18N
    	window.open(urlCvs);
    	return true;
	}

function PopUpMenuEvent(e , refId , index)
 	     {
 	        var tblModel = getTableModel(refId);

 	        var colInd1  = tblModel.getColumnIndex("BandWidthHost.IPADDRESS");
 	        var ipAddress = tblModel.getValueAt(index,colInd1);

 	        var colInd2  = tblModel.getColumnIndex("BandWidthHost.COMMUNITY");
 	        var community = tblModel.getValueAt(index,colInd2);
 	        if(!ipAddress)
 	            {
 	                colInd1  = tblModel.getColumnIndex("IPResources.IPADDRESS");
 	                ipAddress = tblModel.getValueAt(index,colInd1);
 	            }
 	         openPopupMenu(e,ipAddress);

 	     }


var disRouterRefreshInterval;
function dsRefreshStatus(isScanning)
{
    if(isScanning == 'true')
    {
            disRouterRefreshInterval = window.setTimeout("refreshdsView('RouterListView')",5000);
	}
}

function refreshdsView(viewName)
{
     refreshSubView(viewName,false,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
}

function editIPAMSchedular(menuItemName,refId,additionalParams,index)
{
    var tblModel = getTableModel(refId);

    var colInd5  = tblModel.getColumnIndex("GroupTaskName.TASK_NAME");//No I18N
    var colInd6  = tblModel.getColumnIndex("GroupTaskName.TASK_ID");//No I18N

    var groupID = tblModel.getValueAt(index,colInd6)
    var groupName = tblModel.getValueAt(index,colInd5)

    showURLInDialog('/network/IPAMSchedulerConfig.jsp?GROUP_NAME='+encodeURIComponent(groupName)+'&actionFrom=editSchedular&GROUP_ID='+groupID,'position=relative,modal=yes,width=480,scrollbars=no,title=Edit Subnet Scheduler Configuration');//No I18N
}

function editIPAMScheduler(menuItemName,refId,additionalParams,index)
{
    var tblModel = getTableModel(refId);

    var colInd5  = tblModel.getColumnIndex("GroupTaskName.TASK_NAME");//No I18N
    var colInd6  = tblModel.getColumnIndex("GroupTaskName.TASK_ID");//No I18N

    var groupID = tblModel.getValueAt(index,colInd6)
    var groupName = tblModel.getValueAt(index,colInd5)

    showURLInDialog('/ipam/SubnetSchedulerConfig.jsp?GROUP_NAME='+encodeURIComponent(groupName)+'&actionFrom=editSchedular&GROUP_ID='+groupID,'position=relative,modal=yes,width=480,scrollbars=no,title=Edit Subnet Group Scheduler');//No I18N

}

function ShowSubnetGroupAdd()
{
	document.getElementById('SubnetGrpErrMsgDiv').innerHTML="";
   var addSwitchElem = document.getElementById("addSwitchFiled");
   var addGroupElem = document.getElementById("AddSubnetGroupDiv");
   if(addSwitchElem.style.display =="none")
   {
        addSwitchElem.style.display="block";
        addGroupElem.style.display="none";
		if(document.getElementById('mcDialogTitle'))
		{
			document.getElementById('dialogTitle').innerHTML=document.getElementById('mcDialogTitle').value;
		}
    }
    else
    {

       addSwitchElem.style.display="none";
       addGroupElem.style.display="block";
        document.getElementById("GROUP_NAME").focus();
		if(document.getElementById('mcDialogTitle'))
		{
			document.getElementById('mcDialogTitle').value = document.getElementById('dialogTitle').innerHTML; //holds the original dialog title temporarily
			document.getElementById('dialogTitle').innerHTML='Add Subnet Group';//No I18N
		}
   }
}

function addOptionAndSelect(sel,val,txt)
{
	var opt = document.createElement('option');
	opt.value=val;
	opt.text=txt;
	opt.selected=true;

	try
	{
		sel.add(opt,null); //Other than IE
	}
	catch(ex)
	{
		sel.add(opt); //IE
	}
}

function saveNewSubnetGroupFromDialog(f,actionFromValue)
{
	document.getElementById('SubnetGrpErrMsgDiv').innerHTML="";
    var newGroupName = trim(f.GROUP_NAME.value);

    if(newGroupName.length == 0)
    {
        document.getElementById('SubnetGrpErrMsgDiv').innerHTML="Please enter Group Name";//No I18N
        document.getElementById('GROUP_NAME').focus();
        return false;
    }

    if(invalidCharsExist(newGroupName))
    {
	    document.getElementById('SubnetGrpErrMsgDiv').innerHTML='The following characters are not allowed : '+valueSpChars;//No I18N
	    document.getElementById('GROUP_NAME').focus();
	    return false;
    }

    f.actionFrom.value = actionFromValue;
    var adminStatus = f.adminStatus.value
    var SCHEDULE_TYPE = f.SCHEDULE_TYPE.value;
    var HOURLY_START_TIME_HOUR = f.HOURLY_START_TIME_HOUR.value;
    var HOURLY_START_TIME_MIN = f.HOURLY_START_TIME_MIN.value;
    var HOURLY_INTERVAL = f.HOURLY_INTERVAL.value;
    var url = '/IPAddressManager.do?actionFrom='+actionFromValue+'&GROUP_NAME='+encodeURIComponent(newGroupName)+'&adminStatus='+adminStatus+'&SCHEDULE_TYPE='+SCHEDULE_TYPE+'&HOURLY_START_TIME_HOUR='+HOURLY_START_TIME_HOUR+'&HOURLY_START_TIME_MIN='+HOURLY_START_TIME_MIN+'&HOURLY_INTERVAL='+HOURLY_INTERVAL+'&uid='+new Date().getTime();//No I18N

    AjaxAPI.sendRequest({URL:url,ONSUCCESSFUNC:addSubnetGroupSuccess});

    return false;
}

function addSubnetGroupSuccess(resOptions, reqOptions)
{
	document.getElementById('SubnetGrpErrMsgDiv').innerHTML='';
	var msg = trim(resOptions.responseText);
	if(!msg || msg==null)
	{
		msg='';
	}
	if(msg.indexOf('$grp$:')>-1)
	{
		var msgsplit = msg.split(':');
		var grpName = msgsplit[1];
		var grpID = msgsplit[2];
		addOptionAndSelect(document.getElementById('subnetGroupID'),grpID,grpName);
		ShowSubnetGroupAdd();
	}
	else
	{
		document.getElementById('SubnetGrpErrMsgDiv').innerHTML=msg;
		document.getElementById('GROUP_NAME').focus();
	}

	document.getElementById('GROUP_NAME').value='';
}
