//$Id: configFileViewer.js,v 1.11 2011/07/15 04:25:57 aruljose Exp $

function configWindow1(menuItemName,refId,additionalParams,index)
{
  var menuItemObj = getMenuItemObj(menuItemName);
  var actUrl = menuItemObj.getActionURL(refId,additionalParams,index);  
  menuItemObj.invokeActionURL(actUrl,refId);

}
function showPass(val) {
     window.document.getElementById("errorAnchor").innerHTML="";
     window.document.getElementById("resultAnchor").innerHTML="";
     var passwordchangeElem = document.getElementById('settings');
     if(passwordchangeElem.style.visibility =="hidden") {
       passwordchangeElem.style.visibility="visible";
       var url = '/ConfigFileViewer.do?&actionFrom='+val+'&uid='+new Date().getTime();
       persistSettings(url);
     } else {
	if(val == "setTftpRootDir"){
		var newTftpRootDir = document.getElementById("newTftpRootDir").value;
		var url = '/ConfigFileViewer.do?&actionFrom='+val+'&newTftpRootDir='+newTftpRootDir+'&uid='+new Date().getTime();
       		persistSettingsForSet(url);
	}
       passwordchangeElem.style.visibility="hidden";
     }
}
var req1;
function persistSettings(url)
{
        if (window.XMLHttpRequest)
        {
                      req1 = new XMLHttpRequest();
                      req1.onreadystatechange = processReqChangeSettings;
                      req1.open("GET", url, true);
                      req1.send(null);
        }
        else if (window.ActiveXObject)
        {
                      isIE = true;
                      req1 = new ActiveXObject("Microsoft.XMLHTTP");
                      if (req1)
                      {
                              req1.onreadystatechange = processReqChangeSettings;
                              req1.open("GET", url, true);
                              req1.send(null);
                      }
        }
}
function processReqChangeSettings()
{
      if (req1.readyState == 4)
      {
             if (req1.status == 200)
             {
		var x = req1.responseXML.getElementsByTagName('tftpInfo');
		document.getElementById("rootDir").innerHTML = x[0].getAttribute("dir");
             }
             else
             {
                alert("There was a problem retrieving the data" +req.statusText);
             }
      }
}
var req2;
function persistSettingsForSet(url)
{
        if (window.XMLHttpRequest)
        {
                      req2 = new XMLHttpRequest();
                      req2.onreadystatechange = processReqForSet;
                      req2.open("GET", url, true);
                      req2.send(null);
        }
        else if (window.ActiveXObject)
        {
                      isIE = true;
                      req2 = new ActiveXObject("Microsoft.XMLHTTP");
                      if (req2)
                      {
                              req2.onreadystatechange = processReqForSet;
                              req2.open("GET", url, true);
                              req2.send(null);
                      }
        }
}
function processReqForSet()
{
      if (req2.readyState == 4)
      {
             if (req2.status == 200)
             {
		if(req2.responseText != "Successfully changed")
		{
			showPass("getTftpRootDir");
		}
		document.getElementById("newTftpRootDir").value = "";
		alert(req2.responseText);
             }
             else
             {
                alert("There was a problem retrieving the data" +req.statusText);
             }
      }
}


function  modifyCommunity(menuItemName,refId,additionalParams,index) 
{
    var modifyFlag = "ModifyMain";
    var menuItemObj = getMenuItemObj(menuItemName);
    var tblModel = getTableModel(refId);
    var colInd1  = tblModel.getColumnIndex("ConfigFileInputConfig.DEVICEID");
    var colInd2  = tblModel.getColumnIndex("ConfigFileInputConfig.COMMUNITY");
    var colInd3  = tblModel.getColumnIndex("ConfigFileInputConfig.TFTPSERVERIP");
    var colInd5  = tblModel.getColumnIndex("ConfigFileInputConfig.SNMP_VERSION");//No I18N
    var colInd6  = tblModel.getColumnIndex("ConfigFileInputConfig.IPADDRESS");//No I18N
    
    var id = tblModel.getValueAt(index,colInd1);
    var comm = tblModel.getValueAt(index,colInd2);
    var tftpServerIP = tblModel.getValueAt(index,colInd3);
    var version = tblModel.getValueAt(index,colInd5);
    var deviceAddress = tblModel.getValueAt(index,colInd6);
    var deviceName = "none";
    
    if(!id) {
        modifyFlag = "ModifyFailed";
        colInd1  = tblModel.getColumnIndex("CFMCSVInputConfig.ID");
        colInd2  = tblModel.getColumnIndex("CFMCSVInputConfig.WRITECOMMUNITY");
        colInd3  = tblModel.getColumnIndex("CFMCSVInputConfig.TFTPSERVERIP");
        colInd4  = tblModel.getColumnIndex("CFMCSVInputConfig.DEVICENAME");
        id = tblModel.getValueAt(index,colInd1);
        comm = tblModel.getValueAt(index,colInd2);
        tftpServerIP = tblModel.getValueAt(index,colInd3);
        deviceName = tblModel.getValueAt(index,colInd4);
    }
    showURLInDialog('/CFMModifyView.cc?id='+id+'&comm='+comm+'&tftpServerIP='+tftpServerIP+'&deviceName='+deviceName+'&modifyFlag='+modifyFlag+"&version="+version+"&deviceAddress="+deviceAddress,'position=relative,modal=yes,width=580,scrollbars=no,title=Modify Device')//No I18N
    
    /*document.cfmModifyForm.rId.value=id;
    document.cfmModifyForm.community.value=comm;
 
    var tblDomModel = TableModel.getInstance(refId);
    tblDomModel.appendDetails(index,document.getElementById("cfm_div"));
    */
}
function cancelModifiedAction()
{
   var formDiv = document.getElementById("cfm_div");
   document.getElementById("cfm_container").appendChild(formDiv);
}
function cfmModifiedAction(response,reqOptions)
{
     var error = trim(response.responseText);
    var erFlag;
     if(error.length > 0) {
        document.getElementById("loadingImgID").style.display='none';
        document.getElementById("InImgID").innerHTML = '';
        var resFlag = error.split(",");
        error = resFlag[0];
        if(resFlag.length > 0) {
            resFlag = resFlag[1];
        }
        erFlag = resFlag;
        if(resFlag == 'true') {
            document.getElementById("errorDiv").className = "successMsg";
        } else if(resFlag == 'false') {
           document.getElementById("errorDiv").className = "failureMsg"
        }
        document.getElementById("errorDiv").style.display='block';
        document.getElementById("errorTD").innerHTML = error;
     }


   var modifyFlag = document.getElementById('modifyFlag').value;
   var viewName = 'CFMView1';
   if(modifyFlag == 'ModifyFailed') {
        viewName = 'CFMImportFailedView';
   }
   if(erFlag == 'true') {
     closeDialog();
   }
   refreshSubView(viewName,true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
}

function configWindow(linkParams)
{
      if (navigator.appName == 'Netscape')
      {
                newwin=window.open("/cisco/ConfigFileViewer.jsp?"+linkParams,"ConfigViewer","screenX=300,screenY=250,scrollbars=yes,toolbar=no,width=650,height=500","centre")
      }
      else
      {
                newwin=window.open("/cisco/ConfigFileViewer.jsp?"+linkParams,"ConfigViewer","scrollbars=yes,toolbar=no,width=540,height=500","centre")
      }
}

function uploadThisFile(rId, dt, type)
{

if(confirm("Are you sure you want to upload this config file to the device?"))
{
//	document.getElementById("statusImg").src = "/images/loading_img.gif";
//	document.getElementById("statusImg").width = "15";
//	document.getElementById("statusImg").height = "15";
//	document.getElementById("message").innerHTML = "Uploading to the device. please wait...";
        document.getElementById("statusId").innerHTML="<img src='/images/loading_img.gif' width='15' height='15'><span class='greentxt'> Uploading please wait...</a>"; 
        var url ="/ConfigFileViewer.do?actionFrom=uploadGivenFile&rId="+rId+"&dt="+dt+"&type="+type;//No I18N
        persist(url);
}
}

var req;
function persist(url)
{
        if (window.XMLHttpRequest)
        {
                      req = new XMLHttpRequest();
                      req.onreadystatechange = processReqChange;
                      req.open("GET", url, true);
                      req.send(null);
        }
        else if (window.ActiveXObject)
        {
                      isIE = true;
                      req = new ActiveXObject("Microsoft.XMLHTTP");
                      if (req)
                      {
                              req.onreadystatechange = processReqChange;
                              req.open("GET", url, true);
                              req.send(null);
                      }
        }
}
function processReqChange()
{
      if (req.readyState == 4)
      {
             if (req.status == 200){
                var res = req.responseText;
//                res = res.replace(/\s/g,'');
                
                var splitRes = res.split(",");
                var resp = splitRes[1].replace(/\s/g,'');
                if(resp == 'true') {
                    document.getElementById("statusId").innerHTML = "<span class='greentxt'>" +splitRes[0] + "</span>";
                } else {
                    document.getElementById("statusId").innerHTML = "<span class='redtxt'>" +splitRes[0] + "</span>";
                }
//		document.getElementById("statusImg").src = "";
//	        document.getElementById("statusImg").width = "1";
//        	document.getElementById("statusImg").height = "1";
//	     	document.getElementById("message").innerHTML = "Uploaded to the device successfully.";
             }
             else
             {
                alert("There was a problem retrieving the data" +req.statusText);
             }
      }
}

function selectAllDevice()
{
        var status = document.InputForm1.selectAll.checked;

        if(!eval("document.InputForm1.deviceID.length"))
        {
                document.InputForm1.deviceID.checked = status;
                ToggleStyle(document.InputForm1.deviceID, status);
        }
        else
        {
                var len = document.InputForm1.deviceID.length;
                for(var i=0; i<len; i++)
                {
                        document.InputForm1.deviceID[i].checked = status;
                        ToggleStyle(document.InputForm1.deviceID[i], status);
                }
        }
}
function Toggle(e)
{
        ToggleStyle(e);
        if (e.checked)
        {
                document.InputForm1.selectAll.checked = AllChecked();
        }
        else
        {
                document.InputForm1.selectAll.checked = false;
        }
}
function AllChecked()
{
        ml = document.InputForm1.deviceID;
        len = ml.length;
        for(var i = 0 ; i < len ; i++)
        {
                if (!ml[i].checked)
                {
                        return false;
                }
        }
        return true;
}



function ToggleStyle(e, status)
{
        var r = null;
        if (e.parentNode && e.parentNode.parentNode)
        {
                r = e.parentNode.parentNode;
        }
        else if (e.parentElement && e.parentElement.parentElement)
        {
                r = e.parentElement.parentElement;
        }
        if (r)
        {
                if (r.className == "oddRow")
                {
                        r.className = "selectedRowOdd";
                }
                else if(r.className == "selectedRowOdd" & !status)
                {
                        r.className = "oddRow";
                }
                else if (r.className == "evenRow")
                {
                        r.className = "selectedRowEven";
                }
                else if(r.className == "selectedRowEven" & !status)
                {
                        r.className = "evenRow";
                }
        }
}
var intervalID = "";

function checkStatus()
{
	var scanStatus = "";
	if(document.InputForm1.deviceID != undefined){
	if(document.InputForm1.deviceID.length != undefined){
	for(var k=0;k<document.InputForm1.deviceID.length;k++)
	{
		if(document.getElementById(document.InputForm1.deviceID[k].value+"statusVal").value == '1')
		{
			scanStatus = "true";
			break;
		}
	}
	}
	else
	{
		if(document.InputForm1.deviceID !=  undefined)
		{
			if(document.getElementById(document.InputForm1.deviceID.value+"statusVal").value == '1')			      {
				scanStatus = "true";
			}
		}
	}
	}
	if(scanStatus == "true")
	{
		intervalID = window.setInterval('getStatus()',8000);

	}
}
	
function getStatus()
{
	var action = "checkUploadStatus";
	var selectedDeviceList = "";
	if(document.InputForm1.deviceID.length != undefined)
	{
	for(var k=0;k<document.InputForm1.deviceID.length;k++)
	{
		if(document.getElementById(document.InputForm1.deviceID[k].value+"statusVal").value == '1')
		{
			if(selectedDeviceList!='')selectedDeviceList+=",";
			selectedDeviceList+=document.InputForm1.deviceID[k].value;
		}
	}
	}
	else
	{
		if(document.InputForm1.deviceID !=  undefined)
		{
			if(document.getElementById(document.InputForm1.deviceID.value+"statusVal").value == '1')			      {
				selectedDeviceList = document.InputForm1.deviceID.value;
			}
		}
	}
	if(selectedDeviceList!=''){
		update(action, selectedDeviceList);
	}
	else {
		window.clearInterval(intervalID);
	}	
}

function update(actionFrom, selList)
{
	var req1;
	var url = '/ConfigFileViewer.do?actionFrom='+actionFrom+'&selectedIdList='+selList+'&uid='+new Date().getTime();
	if(window.XMLHttpRequest)
	{
		req1 = new XMLHttpRequest();
		req1.open("GET", url, true);
                req1.send(null);
		req1.onreadystatechange = function() {
				if (req1.readyState == 4)
				{
					if (req1.status == 200)
					{
						var x = req1.responseXML.getElementsByTagName('statusInfo');
						for(var i=0;i<x.length;i++)
						{
						if((x[i].getAttribute("status")) == 3)
						{

							document.getElementById(x[i].getAttribute("deviceID")+"statusVal").value = x[i].getAttribute("status");
							document.getElementById(x[i].getAttribute("deviceID")+"statusImg").src = "/images/up.gif";
							document.getElementById(x[i].getAttribute("deviceID")+"statusImg").title = "Success";
						}
						else if((x[i].getAttribute("status")) == 4)
						{
							document.getElementById(x[i].getAttribute("deviceID")+"statusVal").value = x[i].getAttribute("status");	
							document.getElementById(x[i].getAttribute("deviceID")+"statusImg").src = "/images/down.gif";
							document.getElementById(x[i].getAttribute("deviceID")+"statusImg").title = "Failure";
						}
						}
					}
					else
					{
						alert("There was a problem");
					}
				}
			}; 
		}
		else if(window.ActiveXObject)
        	{
                	isIE = true;
                	req1 = new ActiveXObject("Microsoft.XMLHTTP");
                	if(req1)
                	{
				req1.onreadystatechange = function() {
					if (req1.readyState == 4)
					{
						if (req1.status == 200)
						{
						var x = req1.responseXML.getElementsByTagName('statusInfo');
						for(var i=0;i<x.length;i++)
						{
							document.getElementById(x[i].getAttribute("deviceID")+"statusVal").value = x[i].getAttribute("status");	
						}

					}
					else
					{
						alert("There was a problem");
					}
				}
			}; 
		req1.open("GET", url, true);
                req1.send();
		}
	}
}
function ShowHideTab(tdName) {
    var tdName2 = 'addImportCFM';
    var id1 = document.getElementById('addManCFMDevice');
    var id2 = document.getElementById('ImportCFMDevice');
    if(tdName == 'addManCFM') {
        id1.style.display = 'block';
        id2.style.display = 'none';
    } else if(tdName == 'addImportCFM') {
        tdName2 = 'addManCFM';
        id1.style.display = 'none';
        id2.style.display = 'block';
    }
    changeBackgroundNone(tdName2);
    changeBackgroundBlock(tdName);
}
var timeToRefresh;
function onSuccessResponseForCfm(resOptions, reqOptions) {
    var error = trim(resOptions.responseText);
    if(error.length > 0) {
        document.getElementById("loadingImgID").style.display='none';
        document.getElementById("InImgID").innerHTML = '';
        var resFlag = error.split(",");
        error = resFlag[0];
        if(resFlag.length > 0) {
            resFlag = resFlag[1];
        }
        if(resFlag == 'true') {
            document.getElementById("errorDiv").className = "successMsg" 
            document.AddCFMForm.RouterName.value = "";
            //document.AddCFMForm.Community.value = "";
            document.AddCFMForm.RouterName.focus();
            timeToRefresh = window.setInterval('refreshCFM()',2000);
        } else {
            document.getElementById("errorDiv").className = "failureMsg"
        }
        if(resFlag == 'true' || resFlag == 'false') {
            document.getElementById("errorDiv").style.display='block';
            document.getElementById("errorTD").innerHTML = error;
        } else {
            document.getElementById("errorDiv").style.display='none';
            closeDialog();
        }
    }
}
function refreshCFM() {
    window.clearInterval(timeToRefresh);
    refreshSubView("CFMView1",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}))
}
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 validateCfm(f,modify) {
    if(!f) {
        f = document.AddCFMForm;
    }
    var version1 = f.snmpV1Id.checked;
    var version2 = f.snmpV2Id.checked;
    var version3 = f.snmpV3Id.checked;

    var comm = "";
    if(modify != 'modify') {
        comm = document.AddCFMForm.Community.value;
    } else {
        comm = f.community.value;
    }
    if(modify != 'modify') {
        var device = document.AddCFMForm.RouterName.value;
        if(device.length == 0) {
            alert("Please enter a valid Cisco device name or an IP Address.")
            document.AddCFMForm.RouterName.focus();
            return false;
        }
    }
    if((version1 || version2) && comm.length == 0) {
        alert("Please enter the SNMP community string.")
        if(modify != 'modify') {
            document.AddCFMForm.Community.focus();
        } else {
            f.community.focus();
        }
        return false;
    } else if(version3) {
        return snmpV3Validation(f);
    }
    return true;
}
function validatecfmInput() {
    var ret = validateCfm();
    if(ret) {
        document.getElementById("loadingImgID").style.display='block';
        document.getElementById("InImgID").innerHTML = '<img src="/images/loading_img.gif"/>';
        document.getElementById("errorDiv").style.display='none';
    }
    return ret;
}
function ShowCfmInputField() {
    showURLInDialog('/cisco/ConfigFileInputPage.jsp','modal=yes,width=580,scrollbars=no,title=Add Device');//No I18N
}
function ShowCfmInputFieldMsg(addOrImport) {
    showURLInDialog('/cisco/ConfigFileInputPage.jsp?addOrImport='+addOrImport,'modal=yes,width=580,scrollbars=no,title=Add Device');//No I18N
}
function validateCfmImport() {
    var button = document.ImportCFMForm.actionFrom.value
    document.ImportCFMForm.actionFrom.value = 'importCfmInput';
    if(button == "importCfmInput") {
        var path = trim(document.ImportCFMForm.csvCfmPath.value)
        if(path.length == 0) {
               alert("Select a CSV file ");
               return false;
        } else {
            var splitFile = path.split(".");
            var fileType = splitFile[splitFile.length - 1];
            if( fileType == 'csv' || fileType == 'CSV') { 
              return true;
            } else {
               alert("Please Select a \".CSV\" file ");
               return false;
            }
            return true;
        }
    }
    return false;
}
function LoadFailedDeviceView() {
    refreshSubView("CFMImportFailedView",true,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}))
}
var cfmRefreshInterval;
function cfmRefreshStatus(isScanning)
{
         if(isScanning == 'true') {
            cfmRefreshInterval = window.setInterval("refreshCFMView('CFMView1')",5000);
	}else{    
            window.clearInterval(cfmRefreshInterval);
	}
           return;
}
function refreshCFMView(viewName) {
     window.clearInterval(cfmRefreshInterval);
     refreshSubView(viewName,false,new AjaxOptions({USEXMLHTTPFORREFRESH:true,NAVIGABLE:false}));
}
function validateUpload() {
    var ipAddr = document.uploadform.ipAddress.value;
    var comm = document.uploadform.community.value;
    var type = "startUp" //No I18N
    if(document.uploadform.fileType1[0].checked == true) {
        type = "startUp"; //No I18N
    } else if(document.uploadform.fileType1[1].checked == true) {
        type = "running"; //No I18N
    }
    document.uploadform.type.value = type;
    if(ipAddr.length == 0) {
        alert("IP Address cannot be empty..");//No I18N
        return false;
    }
    if (comm.length == 0) {
        alert("Community cannot be empty..");//No I18N
        return false;
    }
    document.getElementById('uploadStatusId').innerHTML="<img src='/images/loading_img.gif' width='15' height='15'><span class='greentxt'> Uploading please wait...</a>"; //No I18N
    return true;
}
function onSuccessConfigUpload(resOptions, reqOptions) {
    var res = resOptions.responseText;
    trim(res);
    var splitRes = res.split(",");
    var resp = trim(splitRes[1]);
    if(resp == 'true') {
        document.getElementById("uploadStatusId").innerHTML = "<span class='greentxt'>" +splitRes[0] + "</span>";
    } else {
        document.getElementById("uploadStatusId").innerHTML = "<span class='redtxt'>" +splitRes[0] + "</span>";
    }
}

