//This is an example of an external function that is registered in the config file. It is called whenever the selection changes
//
//Each time the user changes the selection, this function is called to update the external component (in this case...a text box)
//This function would be created by someone, and included in the CONFIG file, in "updateSelectionFunctionList" (comma separated list of function names)
//the function would be called everytime the selection changes.

var compLog = log4javascript.getLogger("ComponentFilter");
compLog.setLevel(log4javascript.Level.ERROR);

function initPBOCallbacksLogging(appender, level) {
    // Should add failure logic
    if (level != null) {
        compLog.setLevel(level);
    }
    if (appender == null) {
        appender = new log4javascript.AlertAppender();
    }
    compLog.addAppender(appender);

}

function updateSelectionBox() {
	//Create a variable to concatenate the attribute values
	var newtext = "";
	//Empty the textbox
	document.external.inputtext.value="";
	
	//Loop through the point selection "id" array, which has a corresponding "sister" array, with the same number of elements
	//The statSelXMLArray has an actual DOM doc for each selected feature.
	for (i=0;i<statSelArray.length;i++) {
		//Get the attributes (stored in string format) and store it as XML in the xml dom object. Here we use the same index number to access the proper feature xml
        var feature = featureManager.getPoint(statSelArray[i]);
		//Get a nodelist of the feature attributes/values.
		var featureAttributeNodes = feature.getNode().childNodes;
		//Loop through the feature node list
	    for (j=0;j<featureAttributeNodes.length;j++) {
		//If it is a regular node, not a text or comment node...and NOT the geometry node.
			if ((featureAttributeNodes[j].nodeType != 3)&&(featureAttributeNodes[j].nodeType != 8)&&(featureAttributeNodes[j].nodeName.toUpperCase()!="THEGEOMETRY")) {
                //Append to the text, the attribute value and a comma
                newtext+=Sarissa.getText(featureAttributeNodes[j])+",";
			}//end if node is neither "text" nor "comment" or geometry nodeType
		}//end for each point attribute node
	   
	   //Before the end of each feature, add a carriage return
	    newtext += "\n";
	}
	//After all loops are finished, insert the text
	document.external.inputtext.value=newtext;
}

function clearSelect(elSel) {
    while (elSel.options.length) {
        elSel.remove(0);
    }
    compLog.debug("Cleared selection");
}

function addStation(elSel, stnId, pointIdx) {
    try {
        var elOptNew = document.createElement('option');
        elOptNew.value = stnId;
        var feature = featureManager.getPoint(stnId);
        compLog.debug("addStation: " + feature + " - " + feature.getId());
        //Get a nodelist of the feature attributes/values.
        elOptNew.text = feature.getAttribute('code');
        //var featureAttributeNodes = feature.getNode().childNodes;
        //for (j=0;j<featureAttributeNodes.length;j++) {
            //if (featureAttributeNodes[j].nodeName.toUpperCase().indexOf("CODE") > -1) {
                //Append to the text, the attribute value and a comma
            //    elOptNew.text = Sarissa.getText(featureAttributeNodes[j]);
            //    break;
            //}//end if node is neither "text" nor "comment" or geometry nodeType
        //}//end for each point attribute node
    
    } catch(ex) {
        compLog.error("Failure adding " + stnId + " at idx " + pointIdx + " - " + ex);
        //alert("Failure adding " + stnId + " at idx " + pointIdx + " - " + ex);
    }
    
    try {
      elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
    } catch(ex) {
      elSel.add(elOptNew); // IE only
    }
    compLog.debug("Added station with id " + stnId + " and feature index " + pointIdx);
    //}
}

// Adapted from http://www.mredkj.com/tutorials/tutorial005.html
function updateStationListSelect(type, stnId, pointIdx) {
    compLog.debug("updateStationListSelect: " + type + ", " + stnId + ", " + pointIdx);
    var elSel = document.getElementById('stationSelect');
    if ("Remove" == type) {
        removeOptionByValue(stnId);
    } else if ("Clear" == type) {
        clearSelect(elSel);
    } else if ("Add" == type) {
        addStation(elSel, stnId, pointIdx);
    } else if ("AddAll" == type) {
        clearSelect(elSel);
        for (i=0;i<statSelArray.length;i++) {
            addStation(elSel, statSelArray[i], i);
        }
    } else {
        //Ignore unknown/unsupported
        //alert("Ignoring unknown type: " + type);
        compLog.warn("Ignoring unknown type: " + type);
    }
    document.getElementById('stationSelectCount').innerHTML = elSel.options.length;
    if (elSel.options.length > 0) {
        elSel.style.visibility="visible";
    } else {
        elSel.style.visibility="hidden";
    }
    compLog.debug("Updated stations(" + type + ") with id " + stnId + " and feature index " + pointIdx);
}

function updateBBox(mapLeft, mapTop, mapRight, mapBottom) {
    var bboxString = Math.floor(mapLeft*100)/100 + ", " + Math.floor(mapTop*100)/100 + " " + Math.floor(mapRight*100)/100 + ", " + Math.floor(mapBottom*100)/100;
    //alert(bboxString);
    var bboxDisplay = document.getElementById('bboxDisplay');
    if (bboxDisplay != null) {
        bboxDisplay.innerHTML = bboxString;
        compLog.debug("Updated BBox: " + bboxString);
    } else {
        compLog.debug("No bbox display to update");
    }
}

function updateFeatureCount(count) {
    var featureCountDisplay = document.getElementById('featureCount');
    if (featureCountDisplay != null) {
        featureCountDisplay.innerHTML = count;
        compLog.debug("Updated feature count: " + count);
    } else {
        compLog.debug("No feature count display to update");
    }
}


// Adapted from http://www.mredkj.com/tutorials/tutorial005.html
var count1 = 0;
var count2 = 0;

function insertOptionBefore(num)
{
  var elSel = document.getElementById('selectX');
  if (elSel.selectedIndex >= 0) {
    var elOptNew = document.createElement('option');
    elOptNew.text = 'Insert' + num;
    elOptNew.value = 'insert' + num;
    var elOptOld = elSel.options[elSel.selectedIndex];  
    try {
      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew, elSel.selectedIndex); // IE only
    }
  }
}

function removeOptionByValue(remValue)
{
  var elSel = document.getElementById('stationSelect');
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].value == remValue) {
      elSel.remove(i);
      return
    }
  }
}

function appendOptionLast(num)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = 'Append' + num;
  elOptNew.value = 'append' + num;
  var elSel = document.getElementById('selectX');

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}

function removeOptionLast()
{
  var elSel = document.getElementById('selectX');
  if (elSel.length > 0)
  {
    elSel.remove(elSel.length - 1);
  }
}

