// Add Services
var NITKServices_objAddServicesLoadingIndicatorId = "NITKServices_addServicesLoadingSpan";
var NITKServices_txtAddServicesLoadingIndicatorId = "NITKServices_addServicesLoadingText";

// Manange Services
var currentsvcvalue; 
var currentdataframes;
var numnongraphicresources;
var NITKServices_objManageServicesLoadingIndicatorId = "NITKServices_manageServicesLoadingSpan";
var NITKServices_txtManageServicesLoadingIndicatorId = "NITKServices_manageServicesLoadingText";

// Add Services
function NITKServices_HideMapServicePanels(panelids) {
  var panels = panelids.split(',');
  for (panel in panels) {
    NITKFramework_hide(panels[panel]);
  }
}

function NITKServices_CheckItem(chkboxid) {
  var chk = document.getElementById(chkboxid);
  chk.checked = true;
}

function NITKServices_ExecuteButtonState(selectBox, button) {
	var isSelected = false;
	for (i=0; i<selectBox.length; i++) {
		if (selectBox[i].selected) {
			isSelected = true;
		}
	}
	var btn = document.getElementById(button);
	btn.disabled = !isSelected;
}

function NITKServices_AddSelectedServices(fromid, toid) {
  var fromlst = document.getElementById(fromid);
  var tolst = document.getElementById(toid);
  var idxarr = new Array();
  var numadded = 0;
  for(var iloop=0; iloop<fromlst.length; iloop++) {
    if (fromlst.options[iloop].selected) {
      var bexisting = false;
      for(var j=tolst.options.length-1; j>=0; j--) {
        if (tolst.options[j].text == fromlst.options[iloop].text) {
          bexisting = true;
          break;
        }
      }
      if (!bexisting) {
        tolst.options[tolst.options.length] = new Option(fromlst.options[iloop].text, fromlst.options[iloop].value);
        tolst.options[tolst.options.length].title = fromlst.options[iloop].text;
        // record the index that needs to be removed
        idxarr[numadded] = iloop;
        numadded += 1;
      }
      else alert(fromlst.options[iloop].text + " already exists!")
    }
  }
  // remove from source list
  for(var iloop=numadded-1; iloop>=0; iloop--) {
    fromlst.remove(idxarr[iloop]);
  }
}

function NITKServices_MoveMapServiceUp(lstid) {
    var lst = document.getElementById(lstid);
    var lstopts= lst.options;
    var value;
    var text;
    for (var j=1; j<lstopts.length; j++) {
        if (lstopts[j].selected) {
            value = lstopts[j-1].value;
            text = lstopts[j-1].text;
            lstopts[j-1].value = lstopts[j].value;
            lstopts[j-1].text = lstopts[j].text;
            lstopts[j].value = value;
            lstopts[j].text = text;
            lstopts[j].selected = false;
            lstopts[j-1].selected = true;
        }
    }
}

function NITKServices_MoveMapServiceDown(lstid) {
    var lst = document.getElementById(lstid);
    var lstopts= lst.options;
    var value;
    var text;
    for (var j=lstopts.length-2; j>=0; j--) {
        if (lstopts[j].selected) {
            value = lstopts[j+1].value;
            text = lstopts[j+1].text;
            lstopts[j+1].value = lstopts[j].value;
            lstopts[j+1].text = lstopts[j].text;
            lstopts[j].value = value;
            lstopts[j].text = text;
            lstopts[j].selected = false;
            lstopts[j+1].selected = true;
        }
    }
}

function NITKServices_SwapMapServiceList(lstopts) {
    var value;
    var text;
    for (var j=lstopts.length-1; j>=(lstopts.length/2); j--) {
        value = lstopts[j].value;
        text = lstopts[j].text;
        lstopts[j].value = lstopts[lstopts.length-1-j].value;
        lstopts[j].text = lstopts[lstopts.length-1-j].text;
        lstopts[lstopts.length-1-j].value = value;
        lstopts[lstopts.length-1-j].text = text;
    }
}

function NITKServices_RemoveSelectedServices(removeFromId, executeButtonId) {
    var tolst = document.getElementById(removeFromId);
    for(var iloop=tolst.length-1; iloop>=0; iloop--) {
        if (tolst.options[iloop].selected) {
            tolst.remove(iloop);
	        var button = document.getElementById(executeButtonId);
	        button.disabled = true;
        }
    }
}

function NITKServices_DisplayMapServicePanel(lstid, panelids) {
  var lst = document.getElementById(lstid);
  var contype = lst.value;
  NITKServices_HideMapServicePanels(panelids);
  if (contype > 0) {
    var panels = panelids.split(',');
    var pnl = document.getElementById(panels[contype-1]);
    pnl.style.display = 'block';
  }
}

function NITKServices_FinalizeMapServiceTask(svclstid, callbackFunctionString, transchkid) {
  NITKFramework_show(NITKServices_objAddServicesLoadingIndicatorId);
  NITKFramework_setText(NITKServices_txtAddServicesLoadingIndicatorId, "Adding chosen service to map...");
  
  // create parameter pairs
  var svclst = document.getElementById(svclstid);
  var svclstopts = svclst.options;
  var arguments = ""; 
  var added = false;
  for(var iloop=0; iloop<svclstopts.length; iloop++) {
    if (svclstopts[iloop].selected) {
      if (added) {
        arguments = arguments + "," + svclstopts[iloop].value;
      }
      else {
        added = true;
        arguments += svclstopts[iloop].value;
      }
    }
  }
//alert(arguments);  
  var transchk = document.getElementById(transchkid);
  if (transchk.checked) {
    if (arguments.length > 0) arguments = "true," + arguments;
  }
  else {
    if (arguments.length > 0) arguments = "false," + arguments;
  }
  
  var message = "";
  if (arguments.length > 0) {
    arguments = "arguments=" + arguments;
    message = "&" + arguments;
  }
  
  var context = "Process_CustomCallback";
  NITKFramework_executeTask(message, callbackFunctionString);
}

function NITKServices_ASProcessIndicator(hide, text) {
  var indicator = document.getElementById("NITKServices_Task_Indicator");
  if (hide) {
    indicator.style.display = 'none';
  }
  else {
    var txt = document.getElementById("NITKServices_Task_Indicator_Text");
    txt.innerHTML = text;
    indicator.style.display = 'block';
  }
}

function NITKServices_SendMapServiceRequest(arg, ctx, callbackArguments, callbackFunctionString){
  NITKFramework_show(NITKServices_objAddServicesLoadingIndicatorId);
  NITKFramework_setText(NITKServices_txtAddServicesLoadingIndicatorId, "Getting services...");
  
  var message = "EventArg=" + arg;
  if (callbackArguments.length > 0) message += "&" + callbackArguments;
  var context = ctx;
	eval(callbackFunctionString);
}

function NITKServices_HandleMapServiceResponse(returnvalue, context){
    NITKFramework_hide(NITKServices_objAddServicesLoadingIndicatorId);
    
    if (context == "GetMap_CustomCallback"){
      if(returnvalue.indexOf("Error:") > -1) {
        // error info contains the id of the service list 
        //    box that needs to be cleared
        var arr = returnvalue.split(",");
        alert(arr[0]);
        if (arr[1].length > 0) 
        {
          var lstsvc = document.getElementById(arr[1]);
          for(var iloop=lstsvc.length-1; iloop>=0; iloop--) {
            lstsvc.remove(iloop);
          }
        }
      }
      else {
//alert(returnvalue);
        var returnvalues = returnvalue.split(":--:");
        if (returnvalues[0].length >0) {
            // remove all existing items first
            var svclst = document.getElementById(returnvalues[0]);
            if (svclst != null) 
            {
                for(var iloop=svclst.length-1; iloop>=0; iloop--) {
                  svclst.remove(iloop);
                }
            }
            
            // then add found services
            for (j=0;j<returnvalues.length;j++){
              var lstsvcs = document.getElementById(returnvalues[0]); 
              var svcs = returnvalues[1].split(',');
              for(idx in svcs) {
                lstsvcs.options[idx] = new Option(svcs[idx].split('^')[0], svcs[idx]);
                lstsvcs.options[idx].title = svcs[idx].split('^')[0];
              }
            }
        }
      }
    }
    else {
      if(returnvalue.indexOf("Error:") > -1) {
        alert(returnvalue);
      }
      else { 
        processCallbackResult(returnvalue, context);
      }
    }
}

// Manage Services
function NITKServices_SendManageMapServiceRequest(arg, ctx, callbackArguments, callbackFunctionString)
{
  NITKFramework_show(NITKServices_objManageServicesLoadingIndicatorId);
  NITKFramework_setText(NITKServices_txtManageServicesLoadingIndicatorId, "Getting services...");
  
  var message = "EventArg=" + arg;
 if (callbackArguments.length > 0) message += "&" + callbackArguments;
  var context = ctx;
	eval(callbackFunctionString);
}

function NITKServices_HandleManageMapServiceResponse(returnvalue, context){
   NITKFramework_hide(NITKServices_objManageServicesLoadingIndicatorId);
   if (context != "Process_CustomCallback"){
        var pairs = returnvalue.split(":--:");
        for(idx in pairs) {
            returnvalues = pairs[idx].split("^^");
            var ctrl = document.getElementById(returnvalues[0]);
            ctrl.outerHTML = returnvalues[1];
        }
    }
    else 
      processCallbackResult(returnvalue, context);
}

function NITKServices_ApplyButtonState(selectBox, button) {
	var isSelected = false;
	for (i=0; i<selectBox.length; i++) {
		if (selectBox[i].selected) {
			isSelected = true;
		}
	}
	var btn = document.getElementById(button);
	btn.disabled = !isSelected;
}

function NITKServices_PopulateMapServiceProperty(svclstid, relatedids, pnlid) 
{
  var relids = relatedids.split(',');
  var ctrl = document.getElementById(svclstid);
  currentsvcvalue = ctrl.value;
  var relvalues = currentsvcvalue.split('^');
  if (relvalues[0] == "1" || relvalues[0] == "2" || relvalues[0] == "3"  || relvalues[0] == "8"  || relvalues[0] == "9" ) {
    // only handles ArcGIS Server and ArcIMS and Graphic Layer now
    if (relvalues[0] == "1" || relvalues[0] == "2" ) {
      currentdataframes = relvalues[relvalues.length-1];
      // remove all options in dataframe dropdown
      var df = document.getElementById(relids[relids.length-1]);
      for(var idx=df.length-1; idx>=0; idx--) {
        df.remove(idx);
      }
      // then populate the new dataframes
      var dataframes = currentdataframes.split('*');

      for(idx in dataframes) {
          df.options.add(new Option(dataframes[idx], dataframes[idx]));
      }
    }
    // now set values of all related controls
    /*
    for(var idx=1; idx<relids.length; idx++) {
      document.getElementById(relids[idx-1]).value = relvalues[idx];
    }
    */
    var ctrl1 = document.getElementById(relids[0]);
    ctrl1.value = relvalues[1];
    var transp = document.getElementById(relids[1]);
    transp.options[0].selected = true;
    for (var i=0; i<transp.options.length; i++) {
        if (parseInt(transp.options[i].value) >= parseInt(relvalues[2])) {
            transp.options[i].selected = true;
            break;
        }
    }
    
    
    // hide data frame div if not ArcGIS Server map resource; otherwise display it
    var pnl = document.getElementById(pnlid);
    if (relvalues[0] == "1" || relvalues[0] == "2" ) {
      pnl.style.display = "block"; 
    }
    else {
      pnl.style.display = "none"; 
    }
   }
}

function NITKServices_SetMapServiceProperty(svclstid, relatedids) 
{
  // generate the new value string first
  var relids = relatedids.split(',');
  var delimiter = '^';
  var relvalues = '';
  for(var idx=0; idx<relids.length; idx++) {
    relvalues = relvalues + document.getElementById(relids[idx]).value + delimiter;
  }

  relvalues = relvalues + currentdataframes;

  // set the generated value to the current item
  var lstsvc =  document.getElementById(svclstid);
  for (var idx=0; idx<lstsvc.length; idx++) {

    if (lstsvc.options[idx].value == currentsvcvalue) {
        var parts = currentsvcvalue.split(delimiter);
        // we need to add type information here
        currentsvcvalue = parts[0] + delimiter + relvalues;
        lstsvc.options[idx].value = currentsvcvalue;
        break;
    }
  }
}

function NITKServices_MoveManageMapServiceUp(lstid) {
    var lst = document.getElementById(lstid);
    var lstopts= lst.options;
    var value;
    var text;
    for (var j=1; j<lstopts.length; j++) {
        if (lstopts[j].selected) {
            value = lstopts[j-1].value;
            text = lstopts[j-1].text;
            lstopts[j-1].value = lstopts[j].value;
            lstopts[j-1].text = lstopts[j].text;
            lstopts[j].value = value;
            lstopts[j].text = text;
            lstopts[j].selected = false;
            lstopts[j-1].selected = true;
        }
    }
    
}

function NITKServices_MoveManageMapServiceDown(lstid) {
    var lst = document.getElementById(lstid);
    var lstopts= lst.options;
    var value;
    var text;
    for (var j=lstopts.length-2; j>=0; j--) {
        if (lstopts[j].selected) {
            value = lstopts[j+1].value;
            text = lstopts[j+1].text;
            lstopts[j+1].value = lstopts[j].value;
            lstopts[j+1].text = lstopts[j].text;
            lstopts[j].value = value;
            lstopts[j].text = text;
            lstopts[j].selected = false;
            lstopts[j+1].selected = true;
        }
    }
    
}

function NITKServices_ClearControls(ctrlids) {
  var ctrls = ctrlids.split(',');
  for (ctrlid in ctrls) {
    var ctrl = document.getElementById(ctrls[ctrlid]);
    // for dropdown, we remove all
    if (ctrl.options != null) {
      for(var idx=ctrl.length-1; idx>=0; idx--) {
        ctrl.remove(idx);
      }
    }
    // text control, clear the text; we may need to add handling for other types of controls
    else ctrl.value = "";
  }
}

function NITKServices_IsNonGraphicLayer(val) {
  return val.substring(0,1)=='9'?false:true;
}

function NITKServices_GetNumNonGraphicLayers(lst){
  var num = 0;
  for(var iloop=lst.length-1; iloop>=0; iloop--) {
    if (NITKServices_IsNonGraphicLayer(lst.options[iloop].value)) num++;
  }
  return num;
}

function NITKServices_RemoveManagedMapService(lstid, extentlstid, clearids, applyButtonId) {
  var lst = document.getElementById(lstid);
  numnongraphicresources = NITKServices_GetNumNonGraphicLayers(lst);

  for(var iloop=lst.length-1; iloop>=0; iloop--) {
    var bAllowDelete = false;
    if (lst.options[iloop].selected) {
      if (NITKServices_IsNonGraphicLayer(lst.options[iloop].value)) {
        if (numnongraphicresources > 1) {
          bAllowDelete = true;
        }
      }
      else {
          bAllowDelete = true;
      }
      if (bAllowDelete) {
        if (confirm("Do you really want to delete the map layer " + lst.options[iloop].text + "?")) {
          // we need to remove it from the extent list too
          var ctrl = document.getElementById(extentlstid);
          for(var jloop=ctrl.length-1; jloop>=0; jloop--) {
              if(ctrl.options[jloop].text == lst.options[iloop].text) {
                  ctrl.remove(jloop);
                  break;
              }
          }
          lst.remove(iloop);
          numnongraphicresources--;
          var button = document.getElementById(applyButtonId);
          button.disabled = true;
          NITKServices_ClearControls(clearids);
          break;
        }
      }
      else {
        alert("Cannot delete map " + lst.options[iloop].text + ". It requires at least one non-graphic layer in the map.");
      }
    }
  }
}

function NITKServices_FinalizeManageMapServiceTask(svclstid, extentlstid, callbackFunctionString) {
  NITKFramework_show(NITKServices_objManageServicesLoadingIndicatorId);
  NITKFramework_setText(NITKServices_txtManageServicesLoadingIndicatorId, "Refreshing map...");
  
  // create parameter pairs
  var svclst = document.getElementById(svclstid);
  var svclstopts = svclst.options;
  var ctrl = document.getElementById(extentlstid);
  var arguments = ctrl.value + ","; 
  for(var idx=0; idx<svclstopts.length; idx++) {
    if (idx != svclstopts.length -1)
      arguments = arguments + svclstopts[idx].value + ",";
    else
      arguments += svclstopts[idx].value;
  }
  
  var message = "";
  if (arguments.length > 0) {
    arguments = "arguments=" + arguments;
    message = "&" + arguments;
  }
  
  var context = "Process_CustomCallback";
  NITKFramework_executeTask(message, callbackFunctionString);
}

