///////////////////////////////////////
// mitigation.js
//
//  Rob Christie
//  $Revision: 7787 $ $Date: 2006-11-28 00:53:40 -0500 (Tue, 28 Nov 2006) $
//////////////////////////////////////

/**
 * Loads the dynamically generated javascript... our own mini RPC.
 *
 */
function loadScript(src, id) {
  //  alert ("in load script");
  // alert ("document "+document);
  
  var head = document.getElementsByTagName('head').item(0);
  // alert("head" + head);
  var old  = document.getElementById(id);
  if (old) head.removeChild(old);

  script = document.createElement('script');
  script.src = src;
  script.type = 'text/javascript';
  script.defer = true;
  script.id = id;
  // alert ("about to append the child");
  void(head.appendChild(script));
  // alert ("finished adding child");
}

/**
 * Shades a state by changing the opacity level and also maintains the opacity of the 
 * state name.
 *
 */
function shadeState(stateid, shadingLevel){
  //   setStyleProperty(document.getElementById('svgMain').getSVGDocument().getElementById('State' + stateid), 
  //                 'fill-opacity', (shadingLevel * 0.9) +0.1);
   setStyleProperty(document.getElementById('svgMain').getSVGDocument().getElementById('State' + stateid), 
                   'fill-opacity', (shadingLevel * 0.95)+ 0.05 );
  // this sets the state name back to the appropriate opacity since it is a child of the state element
  setStyleProperty(document.getElementById('svgMain').getSVGDocument().getElementById('stateName-State' + stateid), 
                   'fill-opacity', 1);
}

/**
 * Sets a style attriburte for a given element to specified value
 *
 */
function setStyleProperty(element, property, value){
  if(null!=property && null!=value && null!=element){
    style = element.getStyle();
    if(null!=style){
      style.setProperty(property,value);
    }
  }
}


/**
 * Event handler that is called when a select box has a change in state.
 *
 */
function redrawForSelectedView(statistic, hazard, project, sector, keywords){
  loadScript("/mitigationbp/shadeNation.do?selectedStatistic="+statistic+"&selectedHazardType=" + hazard + "&selectedSectorType=" + sector +"&selectedProjectType="+ project + "&keywords="+ escape(keywords), "scriptShadeStates");
}

/**
 * Event handler that is called when a state is clicked on the SVG map. This generates the search query
 * that is used to find the mitigation Best Practice stories.
 *
 */
function stateClick(state) {
  var selectedHazard = "";
  var selectedProject = "";
  var selectedSector = "";
  var formatted_keywords = "";
  if (selectedValue(document.mitigationForm.selectedHazardType) == 'all') {
    selectedHazard = "";
  }
  else {
    selectedHazard = selectedValue(document.mitigationForm.selectedHazardType);
  }
  if (selectedValue(document.mitigationForm.selectedProjectType) == 'all') {
    selectedProject = "";
  }
  else {
    selectedProject = selectedValue(document.mitigationForm.selectedProjectType);
  }
  if (selectedValue(document.mitigationForm.selectedSectorType) == 'all') {
    selectedSector = "";
  }
  else {
    selectedSector = selectedValue(document.mitigationForm.selectedSectorType);
  }

  formatted_keywords= document.mitigationForm.keywords.value;

  var url = "/mitigationbp/sstoryFind.do?ff_project_state="+state+"&ff_project_county=&q_hazard_types="
          + selectedHazard
          + "&ff_project_type="
          + selectedProject
          + "&q_sector_types="
          + selectedSector
          + "&p_sort_by=7"
          + "&ff_keyword="
          + escape(formatted_keywords)
          + "&submit=submit";
  window.name="svgSearchForm";
  window.open(url,window.name);
}


/**
 * A hack for the adobe svg viewer to get it to rerender the
 * svg doc.
 *
 */
function bugRerender(svgDoc){
  var currentScale = svgDoc.getElementById("svg").currentScale;
  svgDoc.getElementById("svg").currentScale= currentScale/2;
  svgDoc.getElementById("svg").currentScale= currentScale;
}

/**
 * Returns a reference to the main svg document that is reference by
 * the id, svgMain, throughout the entire web app.
 * 
 */
function getSVGDocument(){
  var doc = null;
  var svgMain = document.getElementById('svgMain');
  if (svgMain != null) {
    doc = svgMain.getSVGDocument();
    if(null==doc){
      doc = document;
    }
    if(null!=doc){
      if("[object SVGDocument]"!=(""+doc)){
        doc=null;
      }
    }
  }
  return doc;
}


function getSVGLegend(){
  var doc = null;
  var svgLegend = document.getElementById('svgLegend');
  if (svgLegend != null) {
    doc = svgLegend.getSVGDocument();
    if(null==doc){
      doc = document;
    }
    if(null!=doc){
      if("[object SVGDocument]"!=(""+doc)){
        doc=null;
      }
    }
  }
  return doc;
}



/**
 * Sets the legend values for min, avg, and max.
 *
 */
function setLegend(none,half,full){
  svgDoc = getSVGLegend();
  svgDoc.getElementById("txtLegendShadingNone").firstChild().setData(none);
  svgDoc.getElementById("txtLegendShadingHalf").firstChild().setData(half);
  svgDoc.getElementById("txtLegendShadingFull").firstChild().setData(full);
}


/**
 * Sets the legend title 
 *
 */
function setLegendTitle(titleLine1, titleLine2){
  svgDoc = getSVGLegend();
  svgDoc.getElementById("txtLegendTitle1").firstChild().setData(titleLine1);
  svgDoc.getElementById("txtLegendTitle2").firstChild().setData(titleLine2);
}


/**
 * Sets the initial map opacity levels
 * ISSUE: this is not clean... should not reference the document within the init
 * Need to change.
 */
function initStateShading(){
  // alert("In init Shading");
   
   redrawForSelectedView(document.mitigationForm.selectedStatistic.value,
                         selectedValue(document.mitigationForm.selectedHazardType),
                         selectedValue(document.mitigationForm.selectedProjectType),
                         selectedValue(document.mitigationForm.selectedSectorType),
                         document.mitigationForm.keywords.value);
}


/**
 * Pops a window
 */
function popWindow(url,winName, width, height,fixedSize)
{
  if (fixedSize == true) {
    newwindow=open(url,winName,"scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=no,status=no,width="+ width +",height="+height);
  }
  else {
    newwindow=open(url,winName,"scrollbars=yes,toolbar=yes,directories=yes,menubar=yes,resizable=yes,status=yes,width="+ width +",height="+height);
  }

}

/**
 *  Dynamic Version by: Nannette Thacker 
 * http://www.shiningstar.net 
 * Original by :  Ronnie T. Moore 
 * Web Site:  The JavaScript Source 
 * Use one function for multiple text areas on a page 
 * Limit the number of characters per textarea 
 */
function textCounter(field,cntfield,maxlimit) {
  if (field.value.length > maxlimit) {
    // if too long...trim it!
    field.value = field.value.substring(0, maxlimit);
    // otherwise, update 'characters left' counter
  }
  else {
    cntfield.value = maxlimit - field.value.length;
  }
}


function updateElementHtmlById(elementId, newHtml) {
  var el = document.getElementById(elementId); 
  if (el != null) {
    el.innerHTML = newHtml;
  }
}




function changeSelectBoxAttributes(field, isMultiple, size) {
  if (document.all || document.getElementById) {
    if (field) {
      field.multiple = isMultiple;
      field.size = size;
    }
  }
}

function resetSelectBoxOptions(optionEl, defaultName, defaultValue) {
  optionEl.selectedIndex = -1;
  optionEl.options.length = 0;
  if ((defaultName != null) && (defaultValue != null)) {
    optionDefault= new Option(defaultName, defaultValue);
    optionEl.options.length = optionEl.options.length + 1;
    optionEl.options[0]= optionDefault;
  }
}


function disableTextField (field, keepValue) {
  if (document.all || document.getElementById) {
    field.disabled = true; 
    field.style.backgroundColor = "#EBEBE4";
    field.style.borderStyle="solid";
    field.style.borderColor="#7f9db9";
    field.style.borderWidth="1px"; 
  }
  if (keepValue != true) {
    field.value="";
  }
} 

function enableTextField (field) { 
  if (document.all || document.getElementById) {
    field.disabled = false; 
    field.style.backgroundColor = "white";
  }
  else { 
    field.onfocus = field.oldOnFocus; 
  }
} 


function disableField(field) {
 if (document.all || document.getElementById) {
    field.disabled = true; 
  }
}

function enableField(field) {
  if (document.all || document.getElementById) {
    field.disabled = false;
  }
}


function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
      num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + '$' + num + '.' + cents);
}



function selectedValue(selectBox) {
  value = '';
  if (selectBox.selectedIndex > -1) {
    value = selectBox.options[selectBox.selectedIndex].value;
  }
  return value;
}

function selectedText(selectBox) {
  text = '';
  if (selectBox.selectedIndex > -1) {
    text = selectBox.options[selectBox.selectedIndex].text;
  }
  return text;
}

function getSelectedCount(selectBox) {
  var count = 0;
  if (selectBox != null) {
    if (selectBox.multiple) {
      if (selectBox.options != null) {
        for (var i = 0; i < selectBox.options.length; i++) {
          if (selectBox.options[i] != null && selectBox.options[i].selected) {
            count++;
          }
        }
      }
    }
    else {
      if (selectBox.selectedIndex > 0 || 
          (selectBox.selectedIndex == 0 && selectBox.options[0].value != "")) {
        count = 1;
      }
    }
  }
  return count;
}

function toggleOptionSelection(select, label) {
  //alert("toggleOptionSelection");

  if (select.selectedIndex > -1) {
    // need to deselect
    select.selectedIndex = -1;
  }
  else {
    // need to select 
    for (x = 0; x < select.options.length; x++) 
      select.options[x].selected = true;
  }

  toggleLabelText(select, label);
}

function toggleLabelText(select, label) {
  //alert("toggleLabelText");

  if (select.options.length == 0 || (select.options.length == 1 && select.options[0].value == ''))
    updateElementHtmlById(label, '');
  else {
    numSelected = getSelectedCount(select);
    if (numSelected > 0)    
      updateElementHtmlById(label, 'Clear');
    else
      updateElementHtmlById(label, 'All');
  } 
}
