/*------------------------------------------------------*
 * File: anCMS.js
 * Desc:
 * Notes:
 * Author: Nishikant Kapoor
 *------------------------------------------------------*/
  var xmlHttp; var modSpanId; var modDetailSpanId; var ratingSpanId;
  var tagSpan0Id; var tagSpan1Id; var tagSpan2Id;
  var tagSpan3Id;
  var stateToggle = 0;
  var gmarker;

/*------------------------------------------------------*
 * Function: redirectTo()
 * Desc:
 * Notes:
 *------------------------------------------------------*/
  function redirectTo (destination) {
    window.location=destination;

  } // end of redirectTo()

  /*------------------------------------------------------*
   * Function: submitForm()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function submitForm(action, form, param) {
    form.action.value = action;
    form.submit();

  } // end of submitForm()

  /*------------------------------------------------------*
   * Function: submitModConfig()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function submitModConfig(action, form, param, mSpanId, modId) {
    var itemCount = form.itemCount.value;
    var script = param;
    modSpanId = mSpanId; //set it so that doModConfig() can access it

    //strip off the args for cetain mods - syndicated news
    var txt = '?';
    var i = script.indexOf(txt);
    if (i != -1) {script = script.substring(0,i);}

    var url = "/cgi-bin/hk/" + script;
        url += "?action=" + action + "&itemCount=" + itemCount;
        url += "&modId=" + modId;

    xmlHttp = getXmlHttpObject(doModConfig);
    xmlHttp.open("GET", url , true);
    xmlHttp.send(null);
    return;

  } //end of submitModConfig()

  /*------------------------------------------------------*
   * Function: submitModConfigDetail()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function submitModConfigDetail(action, form, param, mSpanId) {
    var itemCount = form.itemCount.value;
    var script = param;
    modDetailSpanId = mSpanId; //set it so that doModConfigDetail() can access it

    /*********
    if (itemCount == 0) {
      var msg = "\nSelecting zero items will disable this block!" + 
            "\n\nYou can enable it from 'Preferences' under 'Personalize' menu.";
      if (!confirm(msg)) return (false);
    }
    ***********/

    //alert("action=" + action + " form=" + form + " itemCount=" + itemCount + " script=" + script);

    var url = "/cgi-bin/hk/" + script;
        url += "?action=" + action + "&itemCount=" + itemCount;

    xmlHttp = getXmlHttpObject(doModConfigDetail);
    xmlHttp.open("GET", url , true);
    xmlHttp.send(null);
    return;

  } //end of submitModConfigDetail()

  /*------------------------------------------------------*
   * Function: submitRating()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function submitRating(action,form,itemSpanId,itemId,
                        modId,rating,sideBySide) {
    ratingSpanId = itemSpanId; //set it so that doRating() can access it

    /***
    var rating = 0;
    for (var i=1; i <= 5; i++) {
      if (eval("form.rating[" + (i-1) + "].checked") == true) {
        rating = i;
        break;
      }
    }
    ***/

    var url = "/cgi-bin/hk/rating.cgi";
        url += "?action=" + action + "&iId=" + itemId;
        url += "&rating=" + rating + "&modId=" + modId;
        url += "&sideBySide=" + sideBySide;

    xmlHttp = getXmlHttpObject(doRating);
    xmlHttp.open("GET", url , true);
    xmlHttp.send(null);
    return;

  } //end of submitRating()

  /*------------------------------------------------------*
   * Function: stripSpaces()
   *
   *------------------------------------------------------*/
  function stripSpaces(str) {
    if ( (!isBlank(str)) && (str != null) ) {
      // this will get rid of leading spaces
      while (str.substring(0,1) == ' ')
        str = str.substring(1);

      // this will get rid of trailing spaces
      while (str.substring(str.length-1, str.length) == ' ')
        str = str.substring(0,str.length-1);
    }

    return (str);

  } // end of stripSpaces()

  /*------------------------------------------------------*
   * Function: isBlank()
   *
   *------------------------------------------------------*/
  function isBlank(s) {
    return (s == "");

  } // end of isBlank()

  /*------------------------------------------------------*
   * Function: isInteger()
   *
   *------------------------------------------------------*/
  function isInteger (contents) {
  /***
    if (((contents / contents) != 1) && (contents != 0)) {
      return false;
    }
    return true;
  ***/

    /***
    //var objRegExp  = /(^\d*$)/;
    var objRegExp  = /(^-?\d\d*$)/;

    //check for integer characters
    return objRegExp.test(contents);
    ***/

   var ints = "0123456789.";
   
   for (var i = 0; i < contents.length; i++) {
     if (ints.indexOf(contents.charAt(i)) == -1)
       return false;
   }
   return true;

  } // end of isInteger()

  /*------------------------------------------------------*
   * Function: openCal()
   * Desc:
   * Notes: In the generated cal, each date should be a link to a JS fn
   #      : that would set the particular field's value to clicked date
   #      : <a href="javascript:returnDate('2006-03-27',form,fld)">27</a>
   *------------------------------------------------------*/
    /*****************************
  function openCal(action, form, param) {

    //var login = form.login.value;
    //param is the field that needs to be populated

    var cgi = "/cgi-bin/hk/cal.cgi";
    var str = cgi + "?action=" + action + "&fld=" + param;

    var winWidth      = 100;
    var winHeight     = 100;
    var winScrollbars = 'no';

    var winStr = 'width='+winWidth+',height='+winHeight+',scrollbars='+winScrollbars;
    winStr += ',menubar=no,resizable=yes,location=no,statusbar=no,screenX=150,screenY=150,top=150,left=150';

    window.open(str,'Calendar',winStr);

  } // openCal()
*********************************/

  /*------------------------------------------------------*
   * Function: returnDate()
   * Desc: /var/www/html/admin/phpMyAdmin/libraries
   * Notes: vi tbl_change.js ../calendar.php
   *------------------------------------------------------*/
/*****************************
  function returnDate(d, form, fld) {
    txt = d;
    if (window.opener.dateType != 'date') {
        // need to get time
        h = parseInt(document.getElementById('hour').value,10);
        m = parseInt(document.getElementById('minute').value,10);
        s = parseInt(document.getElementById('second').value,10);
        if (window.opener.dateType == 'datetime') {
            txt += ' ' + formatNum2(h, 'hour') + ':' + formatNum2(m, 'minute') + ':' + formatNum2(s, 'second');
        } else {
            // timestamp
            txt += formatNum2(h, 'hour') + formatNum2(m, 'minute') + formatNum2(s, 'second');
        }
    }
    window.opener.fld.value = txt;
    window.close();
} // returnDate()

*********************************/

  /*------------------------------------------------------*
   * Function: openPrfAssign()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function openPrfAssign(action, form, param) {
    //alert("action=" + action + " form=" + form + " param=" + param);

    var url = "/cgi-bin/hk/prf.cgi";
        url += "?action=" + action + "&prfId=" + param;

    xmlHttp = getXmlHttpObject(stateChanged);
    xmlHttp.open("GET", url , true);
    xmlHttp.send(null);
    return;
  } // end of openPrfAssign()

  /*------------------------------------------------------*
   * Function: getXmlHttpObject()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function getXmlHttpObject(handler) { 
    var objXmlHttp = null;

    if (navigator.userAgent.indexOf("Opera")>=0) {
      alert("This option doesn't work in Opera");
      return;
    }

    if (navigator.userAgent.indexOf("MSIE")>=0) { 
      var strName="Msxml2.XMLHTTP";
      if (navigator.appVersion.indexOf("MSIE 5.5")>=0) {
        strName = "Microsoft.XMLHTTP";
      } 

      try { 
        objXmlHttp = new ActiveXObject(strName);
        objXmlHttp.onreadystatechange = handler;
        return objXmlHttp;
      }
      catch(e) { 
        alert("Error! Scripting for ActiveX might be disabled");
        return;
      } 
    } //if (navigator.userAgent.indexOf("MSIE")>=0)

    if (navigator.userAgent.indexOf("Mozilla")>=0) {
      objXmlHttp = new XMLHttpRequest();
      objXmlHttp.onload = handler;
      objXmlHttp.onerror = handler;
      return objXmlHttp;
    }
  } //end of getXmlHttpObject()

  /*------------------------------------------------------*
   * Function: stateChanged()
   *
   *------------------------------------------------------*/
  function stateChanged() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
      //document.getElementById("paName").innerHTML =  'Welcome';
      //document.getElementById("paId").innerHTML =  'Welcome';
      //alert("xmlHttp.responseText=" + xmlHttp.responseText);

      var wWd=500; var wHt=350; var wSb='yes';
      var winStr = 'width='+wWd+',height='+wHt+',scrollbars='+wSb;
      winStr += ',menubar=no,resizable=yes,location=no,statusbar=no';
      winStr += ',screenX=150,screenY=150,top=150,left=150';

      var winH;
      //if (winH.opener == null) {
        winH = window.open('','PRF Assignments',winStr);
        winH.document.write(xmlHttp.responseText);
        winH.focus();
      //}
    }
    return;

  } //end of stateChanged()

  /*------------------------------------------------------*
   * Function: submitPrfMaint()
   *
   *------------------------------------------------------*/
  function submitPrfMaint() {
    var form = document.prfMaintForm;

    form.paId.value = document.getElementById("paId").innerHTML;

    //alert("document.getElementById(paId).innerHTML=" + document.getElementById("paId").innerHTML);

    return true;

  } // end of submitPrfMaint()

  /*------------------------------------------------------*
   * Function: doModConfig()
   * Desc: whoever calls modConfig() passes its spanId, which is 
   *     : then copied into the global modSpanId, which is what this
   *     : fn() populates with AJAX response.
   *------------------------------------------------------*/
  function doModConfig() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
      var elem = document.getElementById(modSpanId);
      elem.innerHTML = xmlHttp.responseText;
    }
    return;

  } //end of doModConfig()

  /*------------------------------------------------------*
   * Function: doRating()
   * Desc: whoever calls doRating() passes its spanId, which is 
   *     : then copied into the global ratingSpanId, which is what this
   *     : fn() populates with AJAX response.
   *------------------------------------------------------*/
  function doRating() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
      var elem = document.getElementById(ratingSpanId);
      //alert("doRating():xmlHttp.responseText=" + xmlHttp.responseText);
      elem.innerHTML = xmlHttp.responseText;
    }
    return;

  } //end of doRating()

  /*------------------------------------------------------*
   * Function: doModConfigDetail()
   * Desc: Detailed listing for News module
   *------------------------------------------------------*/
  function doModConfigDetail() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
      var elem = document.getElementById(modDetailSpanId);
      //elem.style.display = 'Block';
      //elem.style.visibility = 'hidden';
      //elem.style.display = 'None';
      elem.innerHTML = xmlHttp.responseText;

      //alert("xmlHttp.responseText=" + xmlHttp.responseText);
    }
    return;

  } //end of doModConfigDetail()

  /*------------------------------------------------------*
   * Function: submitPayPal()
   *
   *------------------------------------------------------*/
  function submitPayPal() {
    var valid = true;
    var msg = "Form Submission:\n\n";

    var form = document.payPalForm;

    var feeAmt = stripSpaces(form.memberFee.value);
    if (!isBlank(feeAmt)) {
      if (! isInteger(feeAmt)) { // make sure it is all numeric
        msg += "Invalid fee amount !\n";
        valid = false;
      }
      else {
        feeAmt = parseInt(feeAmt);
      }
    }
    else {
      feeAmt = 0; // fee is blank
    }

    var contribAmt = stripSpaces(form.memberContrib.value);
    if (!isBlank(contribAmt)) {
      if (! isInteger(contribAmt)) { // make sure it is all numeric
        msg += "Invalid contribution amount !\n";
        valid = false;
      }
      else {
        contribAmt = parseInt(contribAmt);
      }
    }
    else {
      // contrib is blank
      contribAmt = 0;
    }

    // validate currency code
    var sIndex = form.currency_code.selectedIndex;
    var cc = form.currency_code[sIndex].value;
    if (cc == "INR") {
      msg += "At present, PayPal does not allow payments in " + cc + " !\n";
      msg += "Please choose one of the other acceptable currencies.\n";
      valid = false;
    }

    if (!valid) {
      alert (msg);
      return false;
    }

    form.amount.value = feeAmt + contribAmt;

    var yrIdx = form.years.selectedIndex;
    var yrs = form.years[yrIdx].value;
    form.cn.value = "Membership for " +  yrs + " years"; //comments

    // avoid putting in email in .shtml or else spammers get it
    form.business.value = "treasurer@wpaa.org";

    return true;

  } // end of submitPayPal()

  /*------------------------------------------------------*
   * Function: changePayPal()
   *
   *------------------------------------------------------*/
  function changePayPal(form, source) {
    var ccArr = new Array(); var i=0;
    ccArr[i] = 12;  i++; //USD
    ccArr[i] = 100; i++; //INR
    //ccArr[i] = 15; i++; //CAD
    ccArr[i] = 10; i++; //EUR
    //ccArr[i] = 20; i++; //GBP
    //ccArr[i] = 20; i++; //Yen

    var ccIdx = form.currency_code.selectedIndex;
    var yrIdx = form.years.selectedIndex;
    var amt = 0;

    var yrs = form.years[yrIdx].value;

    if ((source == 1) || (source == 2)) { // 1/years  2/currency_code
      amt = yrs * ccArr[ccIdx];
    }
    else {
      alert ("Invalid source: " + source);
      return;
    }
  
    //alert ("ccIdx=" + ccIdx + " yrIdx=" + yrIdx + " amt=" + amt);
    form.memberFee.value = amt;
    return;
  } //end of changePayPal()

  /*------------------------------------------------------*
   * Function: toggleAll()
   * Description:
   *------------------------------------------------------*/
  function toggleAll (form, source) {

    //alert("toggleAll(): source=" + source);

    if (!source) {source = form.toggleCB;}

    if (source) {
      var state = source.checked;
      for (var i = 0; i < form.elements.length; i++) {
        if ((form.elements[i].name.indexOf('cb') > -1)) {
          form.elements[i].checked = state; //found a checkbox
        }
      }
    }

    return;

  } //end of toggleAll()

/*------------------------------------------------------*
 * Function: toggleCB()
 * Description: toggle check boxes
 *------------------------------------------------------*/
function toggleCB (form, source) {
  //alert("toggleCB(anCMS.js):form=" + form + " source=" + source);

  if (source == 0) {  //called from users.tmpl
    if (form.toggleCB) {
      var state = form.toggleCB.checked;
      for (var i = 0; i < form.elements.length; i++) {
        if ((form.elements[i].name.indexOf('cb') > -1)) {//found checkbox
          form.elements[i].checked = state;
        }
      }
      return;
    }
  } //if (source == 0)

  if (source == 1 || source == 2) { //from PF selections in TL search
    var state;
    if (source == 1) {
      state = document.pfSelectForm1.toggleCB1.checked;
      document.pfSelectForm2.toggleCB2.checked = state;
    }

    if (source == 2) {
      state = document.pfSelectForm2.toggleCB2.checked;
      if (document.pfSelectForm1) {
        if (document.pfSelectForm1.toggleCB1) {
          document.pfSelectForm1.toggleCB1.checked = state;
        }
      }
    }

    for (var i=0; i < document.forms.length; i++) {
      var form = document.forms[i];
      if ((form.name.indexOf('artForm') > -1)) {
        for (var j = 0; j < form.elements.length; j++) {
          if ((form.elements[j].name.indexOf('cb') > -1)) {
            form.elements[j].checked = state;  //found a checkbox
          }
        }
      } //if ((form.name.indexOf('artForm') > -1))
    } //for (var i = 0; i < document.forms.length; i++)

    return;
  } //if ((source == 1) || (source == 2)

  if (source == 3) {
    for (var i = 0; i < form.elements.length; i++) {
      if ((form.elements[i].name.indexOf('cb') > -1)) {
        //found a checkbox
        form.elements[i].checked = stateToggle;
      }
    }
    stateToggle = !stateToggle;
    return;
  } //if (source == 3)

  if (source == 4) { //from pics pending approval
    var state = document.picsListF.toggleCB1.checked;

    for (var i=0; i < document.forms.length; i++) {
      var form = document.forms[i];
      if ((form.name.indexOf('picsListForm') > -1)) {
        for (var j = 0; j < form.elements.length; j++) {
          if ((form.elements[j].name.indexOf('cb') > -1)) {
            form.elements[j].checked = state;  //found a checkbox
          }
        }
      } //if ((form.name.indexOf('picsListForm') > -1))
    } //for (var i = 0; i < document.forms.length; i++)

    return;
  } //if ((source == 4)

} //end of toggleCB()

  /*------------------------------------------------------*
   * Function: submitComment()
   *
   *------------------------------------------------------*/
  function submitComment() {
    var valid = true;
    var msg = "Form Submission:\n\n";

    var form = document.commentForm;

    var comText = stripSpaces(form.comText.value);
    if (isBlank(comText)) {
        msg += "Please enter some valid text!\n";
        valid = false;
    }

    if (!valid) {
      alert (msg);
      return false;
    }

    return true;

  } // end of submitComment()

/*------------------------------------------------------*
 * Function: changed()
 *
 *------------------------------------------------------*/
function changed(form) {
  if (form.tMode.options[form.tMode.selectedIndex].text == 'PayPal') {
    //PayPal transactions have a fee = some % of transaction amount
    amount = (((form.tAmt.value - 0) * (form.payPalStdRate.value - 0))/100) +
             (form.payPalStdFee.value - 0);

    /***
    alert ("amount=" + amount + " tAmt=" + form.tAmt.value
         + " stdRate=" + form.payPalStdRate.value 
         + " payPalStdFee=" + form.payPalStdFee.value);
    ***/

    amount = (Math.round(amount*100))/100;
    fee = (amount == Math.floor(amount)) ? amount + '.00' : (  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);

    form.tOverheads.value = fee;

    //alert ("fee=" + fee);
  } //if (form.tMode.options[form.tMode.selectedIndex].text == 'PayPal')
  else {
    form.tOverheads.value = '';
  }

} //end of changed()

/*------------------------------------------------------*
 * Function: popup()
 * Desc: 
 * Notes: 
 *------------------------------------------------------*/
function popup(action) {
  var msg = '';

  /*******************************************
  var str="";
  var tmpValue = "oneword (5)";
  str += " (0)tmpValue=" + tmpValue;
  var words = tmpValue.split(/\s/g);
  //tmpValue = words[0];
  str += " Selected=";
  for (var i=0; i< words.length-1; i++) {
    if (i > 0) {str += " ";}
    str += words[i];
  }
  str += " (1)tmpValue=" + tmpValue + " len=" + words.length + " \n";

  tmpValue = "two words (7)";
  str += " (0)tmpValue=" + tmpValue;
  words = tmpValue.split(/\s/g); 
  //tmpValue = words[0];
  str += " Selected=";
  for (var i=0; i< words.length-1; i++) {
    if (i > 0) {str += " ";}
    str += words[i];
  }
  str += " (1)tmpValue=" + tmpValue + " len=" + words.length + " \n";

  alert(str); return;
  *****************************************************/

  if (action == "cookie") {
    msg = "Cookies are small data structures used by a web site (server)\nto deliver data to a web client (user); request that the\nclient store the information; and in certain circumstances,\nreturn the information to the web site. Contrary to popular\nfears and misconceptions, cookies were not created to spy on or\notherwise invade the privacy of Internet users. Cookies\ncontain only information that users volunteer, and they do not\nhave the capability of infiltrating a user`s hard drive and\nsneaking away with personal information. The client stores\ncookie data in one or more flat files on its local hard drive.";
  }

  if (action == "overheads") {
    msg = "Payments made through PayPal carry a surcharge which is deducted\n from the actual amount. For example, if you deposit $12,\n WPAA receives only $11.35.\n Remaining .65 goes to PayPal as service charge. This is the overheads.";
  }

  if ( (action == "resPhone") || (action == "resFax") ||
       (action == "resUrl") || (action == "resEmail") ) {
    msg = "Use space to separate multiple entries in this field.";

    if ( (action == "resPhone") || (action == "resFax") ) {
      msg += "\nFormat: ###-###-####";
    }

    if (action == "resEmail") {
      msg += "\nIf you want to be notified when this resource is rated or reviewed,";
      msg += "\nyou must provide your email address.";
    }
  }

  if (action == "youAreNotLoggedOn") {
    msg  = "You are not logged on!\n\n";
    msg += "Please log on to access this feature.";
  }

  alert(msg);

  } // end of popup()

/*------------------------------------------------------*
 * Function: getCapImg()
 * Desc:
 * Notes:
 *------------------------------------------------------*/
function getCapImg(form) {
  var maxId=10;

  var randomNum = Math.floor(Math.random()*maxId);

  //alert("getCapImg():randomNum=" + randomNum);
  document.mainForm.capImg.src = "pics/cap/" + randomNum + ".png";
  return;

} //end of getCapImg()

/*------------------------------------------------------*
 * Function: samplePopup()
 * Desc: Pops open a window to display sample items for a News channel
 * Notes:
 *------------------------------------------------------*/
function samplePopup(action, form, param) {
  var cgi = "/cgi-bin/hk/synd.cgi";
  var str = cgi + "?action=" + action + "&modId=" + param;

  var winWidth      = 300;
  var winHeight     = 500;
  var winScrollbars = 'yes';

  var winStr = 'width='+winWidth+',height='+winHeight+',scrollbars='+winScrollbars;
  winStr += ',menubar=no,resizable=yes,location=no,statusbar=no,screenX=150,screenY=150,top=150,left=150';

  //alert("samplePopup():str=" + str);

  window.open(str,'Sample',winStr);

} //end of samplePopup()

/*------------------------------------------------------*
 * Function: submitSsAccessUpdate()
 * Description:
 * Notes: we are not expecting any text back from this AJAX call
 *------------------------------------------------------*/
function submitSsAccessUpdate(action, form, param) {
  var cbVar = 'cb' + param + 'a';
  var state = eval ("form." + cbVar + ".checked"); // shows final state
  //if cb goes from unchecked to checked, state is true
  //if cb goes from checked to unchecked, state is false

  var msg = "Form Submission:\n\n";
  msg += "action=" + action + " form=" + form + " param=" + param;
  msg += " state=" + state;
  //alert(msg);

  var url = "/cgi-bin/hk/ss.cgi";
      url += "?action=" + action + "&ssId=" + param;
      url += "&state=" + state;

  xmlHttp = getXmlHttpObject(); //we're not expecting any text back
  xmlHttp.open("GET", url , true);
  xmlHttp.send(null);

  return;
} // end of submitSsAccessUpdate()

/*------------------------------------------------------*
 * Function: submitSS()
 * Description: Saved Search selection for updates
 * Notes:
 *------------------------------------------------------*/
function submitSS(action, form, param) {
  var ok = true;
  var msg = "Form Submission:\n\n";

  var dupArr = new Array();
  var ssList = ''; var cbStr = 'cb';
  for (var j=0; j < form.elements.length; j++) {
    var formElem = form.elements[j];
    var idx = formElem.name.indexOf(cbStr);
    if (idx > -1) {
      var ssId = formElem.name.substring(cbStr.length);
      if (isInteger(ssId)) { // make sure ssId is numeric
        var ssIdProcessed = false;  //to handle duplicates
        for (var i in dupArr) {
          if (dupArr[i] == ssId) {ssIdProcessed = true; break;}
        }
        if (!ssIdProcessed) {
          if (eval("form." + cbStr + ssId + "[0].checked") == true) {
            if (ssList != '') {ssList += ',';}
            ssList += ssId + 'd'; //Del
          }
          else {
           if (eval("form." + cbStr + ssId + "[1].checked") == true) {
              if (ssList != '') {ssList += ',';}
              ssList += ssId + 'e'; //Empty
            }
          }
        }
        dupArr[j] = ssId;
      } //if (isInteger(ssId))
    }
  } //for (var j=0; j < form.elements.length; j++)

  //alert("submitSS(): action=" + action + " form=" + form + " param=" + param + " ssList=" + ssList);

  form.cbSsList.value = ssList;
  form.action.value = action;
  form.submit();

} // end of submitSS()

/*------------------------------------------------------*
 * Function: submitTE()
 * Description: validate team selection from the dropdown
 * Notes:
 *------------------------------------------------------*/
function submitTE(action, form, param) {
  var ok = true;
  var msg = "Form Submission:\n\n";

  if (param != 'showItem') {
    var authList = ''; var cbStr = 'cb';
    var ppStr = 'P'; //most authors begin with PP, some with just P
    for (var j=0; j < form.elements.length; j++) {
      var formElem = form.elements[j];
      var idx = formElem.name.indexOf(cbStr);
      if (idx > -1) {
        if (formElem.checked) { //found a checked checkbox
          var authId = formElem.name.substring(cbStr.length);
          //ACM DL has authors IDs starting with PP
          //TL3 has its users IDs as all numeric
          var good=0;
          if (isInteger(authId)) {good=1;} //its a TL3 user
          else {if (authId.indexOf(ppStr) > -1) {good=1;}} //ACM author
          if (good) {
            if (authList != '') {authList += ',';}
            authList += authId;
          }
        } //if (formElem.checked)
      } //if (idx > -1)
    } //for (var j=0; j < form.elements.length; j++)

    if (authList == '') {
      ok = false;
      msg += "Please select at least one item! \n";
    }
    else {
      form.cbAuthList.value = authList;
    }
  } //if (param == 'showItem')

  var sIndex = form.teamId2.selectedIndex;
  var teamId = form.teamId2[sIndex].value;

  if (teamId == 0) {
    msg += "Please select appropriate destination! \n";
    ok = false;
  }

  if (!ok) {alert (msg); return false;}

  form.action.value = action;
  form.submit();

} // end of submitTE()

/*------------------------------------------------------*
 * Function: submitPfe()
 * Description: validate PF selection from the dropdown
 * Notes:
 *------------------------------------------------------*/
function submitPfe(action, form, param) {
  //alert("submitPfe(): action=" + action + " form=" + form + " param=" + param);

  var ok = true;
  var msg = "Form Submission:\n\n";

  if (param != 'showItem') {
    var artList = ''; var cbStr = 'cb';
    for (var i=0; i < document.forms.length; i++) {
      var f = document.forms[i];
      if (f.name.indexOf('artForm') > -1) {
        for (var j=0; j < f.elements.length; j++) {
          var fElem = f.elements[j];
          var idx = fElem.name.indexOf(cbStr);
          if (idx > -1) {
            if (fElem.checked) {   //found a checked checkbox
              if (artList != '') {artList += ',';}
              artList += fElem.name.substring(cbStr.length);
            }
          }
        } //for (var j=0; j < f.elements.length; j++)
      } //if ((f.name.indexOf('artForm') > -1))
    } //for (var i=0; i < document.forms.length; i++)

    if (artList == '') {
      ok = false;
      msg += "Please select at least one item! \n";
    }
    else {form.cbArtList.value = artList;}
  } //if (param == 'showItem')

  var sIdx = form.pfId2.selectedIndex;
  var sVal = form.pfId2[sIdx].value;

  if (sVal == 0) {
    msg += "Please select appropriate destination! \n";
    ok = false;
  }

  if (!ok) {alert (msg); return false;}

  form.action.value = action;
  form.submit();

} // end of submitPfe()

/*------------------------------------------------------*
 * Function: submitPicsPending()
 * Description: 
 * Notes:
 *------------------------------------------------------*/
function submitPicsPending(action, form, param) {
  //alert("submitPicsPending(): action=" + action + " form=" + form + " param=" + param);

  var ok = true;
  var msg = "Form Submission:\n\n";

  var picList = ''; var cbStr = 'cb';
  for (var i=0; i < document.forms.length; i++) {
    var f = document.forms[i];
    if (f.name.indexOf('picsListForm') > -1) {
      for (var j=0; j < f.elements.length; j++) {
        var fElem = f.elements[j];
        var idx = fElem.name.indexOf(cbStr);
        if (idx > -1) {
          if (fElem.checked) {   //found a checked checkbox
            if (picList != '') {picList += ',';}
            picList += fElem.name.substring(cbStr.length);
          }
        }
      } //for (var j=0; j < f.elements.length; j++)
    } //if ((f.name.indexOf('picsListForm') > -1))
  } //for (var i=0; i < document.forms.length; i++)

  if (picList == '') {
    ok = false;
    msg += "Please select at least one item! \n";
  }
  else {form.cbPicList.value = picList;}

  if (!ok) {alert (msg); return false;}

  form.action.value = action;
  form.submit();

} // end of submitPicsPending()

/*------------------------------------------------------*
 * Function: submitRecsInputSel()
 * Description: validate team selection from the dropdown
 * Notes:
 *------------------------------------------------------*/
function submitRecsInputSel(action, form, param) {
  var ok = true;
  var msg = "Form Submission:\n\n";

  var selList = ''; var cbStr = 'cb';
  for (var j=0; j < form.elements.length; j++) {
    var formElem = form.elements[j];
    var idx = formElem.name.indexOf(cbStr);
    if (idx > -1) {
      if (formElem.checked) { //found a checked checkbox
        var selId = formElem.name.substring(cbStr.length);
          if (selList != '') {selList += ',';}
          selList += selId;
        }
      }
    } //for (var j=0; j < form.elements.length; j++)

    if (selList == '') {
      ok = false;
      msg += "Please select at least one item! \n";
    }
    else {
      form.cbSelList.value = selList;
    }

  if (!ok) {alert (msg); return false;}

  form.action.value = action;
  form.submit();

} // end of submitRecsInputSel()

/*------------------------------------------------------*
 * Function: syncSelectTE()
 * Description:
 *------------------------------------------------------*/
function syncSelectTE(form, source) {
  if (! form.teamId1) {return;}
  if (! form.teamId2) {return;}

  var idx1 = form.teamId1.selectedIndex;
  var idx2 = form.teamId2.selectedIndex;

  if (source == 1) {form.teamId2.selectedIndex = idx1; return;}
  if (source == 2) {form.teamId1.selectedIndex = idx2; return;}

} //end of syncSelectTE()

/*------------------------------------------------------*
 * Function: syncSelect()
 * Description:
 *------------------------------------------------------*/
function syncSelect(form, source) {

  //for some reason, form MUST be identified here
  var form1 = document.pfSelectForm1;
  var form2 = document.pfSelectForm2;

  if (! form1) {return;}; if (! form1.pfId2) {return;}
  if (! form2) {return;}; if (! form2.pfId2) {return;}

  var idx1 = form1.pfId2.selectedIndex;
  var idx2 = form2.pfId2.selectedIndex;

  if (source == 1) {
    form2.pfId2.selectedIndex = idx1;
    return;
  }

  if (source == 2) {
    form1.pfId2.selectedIndex = idx2;
    return;
  }

} //end of syncSelect()

/*------------------------------------------------------*
 * Function: toggleLayer()
 * Description: mode=1 is show tag entry form; mode=0 is hide
 * Notes: Don't use document.all.
 *      : document.getElementById() is supported by every JS supporting
 *      : browser released since 1998.
 *------------------------------------------------------*/
function toggleLayer(span0Id, span1Id, span2Id, mode) {

  var prop0='none'; var prop1='inline'; var prop2='inline';
  if (mode == 1) {
    prop0 = 'inline'; //show tag entry form; reset tagText
    prop2 = 'none';
    var tmpArr = span0Id.split("span0"); //split into span0 & artId
    var tagTextId = 'autocomplete' + tmpArr[1];
    document.getElementById(tagTextId).value = '';
    //alert ("toggleLayer(): span0Id=" + span0Id + " 0=" + tmpArr[0] + " 1=" + tmpArr[1]);
    //document.myFormName.autocomplete3677.focus();  //does not work :-(
  }

  //alert ("toggleLayer(): span0Id=" + span0Id + " span2Id=" + span2Id +
  //         " mode=" + mode);

  if (document.getElementById) {   //this is the way the standards work
    document.getElementById(span0Id).style.display = prop0;
    document.getElementById(span1Id).style.display = prop1;
    document.getElementById(span2Id).style.display = prop2;
  }
  else if (document.all) {   //this is the way old msie versions work
    document.all(span0Id).style.display = prop0;
  }
  else if (document.layers) {  //this is the way nn4 works
    document.layers(span0Id).style.display = prop0;
  }

} // end of toggleLayer()

/*------------------------------------------------------*
 * Function: show0()
 *
 *------------------------------------------------------*/
function show0(divId) {
  document.getElementById(divId).style.display = 'block';
}

/*------------------------------------------------------*
 * Function: hide0()
 *
 *------------------------------------------------------*/
function hide0(divId) {
  document.getElementById(divId).style.display = 'none';
}

/*------------------------------------------------------*
 * Function: hideArticles()
 * Desc: Called when tags are shown/hidden in TL
 *------------------------------------------------------*/
function hideArticles(divId,alCode,tagText) {
  var elem = document.getElementById(divId);

  //when - is clicked, we need to create the original tagText & + links
  //and replace the entire span (or div) with it
  var txt = "<a href=\"/cgi-bin/hk/tagTL.cgi?action=taggedList";
      txt += "&tagText=" + tagText;
      txt += "&alCode=" + alCode + "\">";
      txt += tagText + "</a>";
      txt += " (<font size=\"+1\" <a href=\"javascript:tagPlus('tagPlus', '";
      txt += divId + "', '" + tagText + "', " + alCode + ")\" title=\"Show articles\">+</a></font>)";

  elem.innerHTML = txt;
  //alert ("hideArticles():divId=" + divId + " alCode=" + alCode + 
  //       " tagText=" + tagText + " txt=" + txt);

} // end of hideArticles()

/********************************
window.onload = hide0;
*******************************/

  /*------------------------------------------------------*
   * Function: submitTagSave()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function submitTagSave(action, form, artId) {
    tagSpan0Id = 'span0'+artId; //set it so doTagSave() can access it
    tagSpan1Id = 'span1'+artId; //set it so doTagSave() can access it
    tagSpan2Id = 'span2'+artId; //set it so doTagSave() can access it

    var tagTextId ='autocomplete'+artId;
    var tagText   = document.getElementById(tagTextId).value;

    if (stripSpaces(tagText) == "") {
      //no text entered; just close the tag entry form, and go back
      toggleLayer(tagSpan0Id, tagSpan1Id, tagSpan2Id, 0);
      return false;
    }

    var url = "/cgi-bin/hk/tagTL.cgi";;
        url += "?action=" + action + "&artId=" + artId;
        url += "&tagText=" + tagText;

    var alCode='alCode'+artId; var alCodeId='alCodeId'+artId;
    //following check for missing alCode (when 'select' element does not
    //exist) is not working???
    //if (form.alCode) {
      //if there are no active tag types, alCode is not displayed
      var alCodeVal  = document.getElementById(alCodeId).value;
      url += "&alCode=" + alCodeVal;
    //}

    /***************************************
    var str = "";
    for (var i=0; i < form.elements.length; i++) {
      //var element = form.elements[i];
      //str += " i=" + i + " element=" + element + " value=" + element.value;
    }
    //http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/objects/form.asp
    //var str = " tagText=" + document.forms[0].tagText.value

    alert("submitTagSave(anCMS.js):action=" + action +
          " form=" + form + " artId=" + artId +
          " tagText=" + tagText + " alCode=" + alCode +
          " url=" + url + " str=" + str);
    ********************************************/

    xmlHttp = getXmlHttpObject(doTagSave);
    xmlHttp.open("GET", url , true);
    xmlHttp.send(null);
    return;

  } //end of submitTagSave()

  /*------------------------------------------------------*
   * Function: doTagSave()
   *
   *------------------------------------------------------*/
  function doTagSave() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
      var elem1 = document.getElementById(tagSpan1Id);
      elem1.innerHTML = xmlHttp.responseText;

      //alert("doTagSave():xmlHttp.responseText=" + xmlHttp.responseText);
      toggleLayer(tagSpan0Id, tagSpan1Id, tagSpan2Id, 0);
    }
    return;

  } //end of doTagSave()

  /*------------------------------------------------------*
   * Function: noEnter()
   *
   *------------------------------------------------------*/
  function noEnter() {
    return !(window.event && window.event.keyCode == 13);

    //if ( (window.event && window.event.which == 13) ||
    //     (window.event && window.event.keyCode == 13))
    //return false;

  } // end of noEnter()

  /*------------------------------------------------------*
   * Function: submitTagMore()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function submitTagMore(action, artId) {
    tagSpan0Id = 'span0'+artId; //set it so doTagSave() can access it
    tagSpan1Id = 'span1'+artId; //set it so doTagSave() can access it
    tagSpan2Id = 'span2'+artId; //set it so doTagSave() can access it

    var url = "/cgi-bin/hk/tagTL.cgi";;
        url += "?action=" + action + "&artId=" + artId;

    xmlHttp = getXmlHttpObject(doTagSave);
    xmlHttp.open("GET", url , true);
    xmlHttp.send(null);
    return;

  } //end of submitTagMore()

  /*------------------------------------------------------*
   * Function: submitTagForm()
   * Desc:
   * Notes:
   *------------------------------------------------------*/
  function submitTagForm(action, form, artId) {
    submitTagSave(action, form, artId);
    return false;
  } //end of submitTagForm()

  /*------------------------------------------------------*
   * Function: toggleTaggedList()
   * Description: mode=1 is show tagged list; mode=0 is hide
   * Notes: Don't use document.all.
   *      : document.getElementById() is supported by every JS supporting
   *      : browser released since 1998.
   *------------------------------------------------------*/
  function toggleTaggedList(span3Id, mode) {
    var prop='none'; if (mode == 1) {prop = 'inline';}

    //alert ("toggleTaggedList(): span3Id=" + span3Id + " mode=" + mode);

    if (document.getElementById) {   //this is the way the standards work
      document.getElementById(span3Id).style.display = prop;
    }
    else if (document.all) {   //this is the way old msie versions work
      document.all(span3Id).style.display = prop;
    }
    else if (document.layers) {  //this is the way nn4 works
      document.layers(span3Id).style.display = prop;
    }

  } // end of toggleTaggedList()

  /*------------------------------------------------------*
   * Function: tagPlus()
   * Desc: Gets list of tagged articles for a particular tag
   * Notes: called when + is clicked in 'My Tags' listing
   *------------------------------------------------------*/
  function tagPlus(action, span3Id, tagText, alCode, tagId) {
    tagSpan3Id = span3Id; //set it so doTaggedList() can access it

    //alert("tagPlus():action=" + action + " span3Id=" + span3Id +
    //      " tagText=" + tagText + " alCode=" + alCode);

    var url = "/cgi-bin/hk/tagTL.cgi";;
        url += "?action=" + action + "&tagText=" + tagText;
        url += "&alCode=" + alCode;
        url += "&span3Id=" + span3Id;

    if (tagId) {url += "&tagId=" + tagId;} //used by tagPlusDel

    xmlHttp = getXmlHttpObject(doTagPlus);
    xmlHttp.open("GET", url , true);
    xmlHttp.send(null);
    return;

  } //end of tagPlus()

  /*------------------------------------------------------*
   * Function: doTagPlus()
   *
   *------------------------------------------------------*/
  function doTagPlus() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
      var elem = document.getElementById(tagSpan3Id);
      elem.innerHTML = xmlHttp.responseText;

      //alert("doTagPlus():xmlHttp.responseText=" + xmlHttp.responseText);
      //toggleTaggedList(tagSpan3Id, 1);
      //document.getElementById(tagSpan3Id).style.display = 'inline';
      document.getElementById(tagSpan3Id).style.display = 'block';
    }
    return;

  } //end of doTagPlus()

  /*------------------------------------------------------*
   * Function: toHere()
   * Desc: Gets Google Maps directions to the specified coordinates
   * Notes:
   *------------------------------------------------------*/
  function toHere(resLat, resLng, resTitle) {
    var to_html = resTitle + '<br>Directions: <b>To here</b> - <a href="javascript:fromHere(' + resLat + ', ' + resLng + ', \'' + resTitle + '\')">From here</a>' +
           '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + resLat + ',' + resLng + 
           "(" + resTitle + ")" + 
           '"/>';
    //alert("(toHere): resLat=" + resLat + " resLng=" + resLng + " to_html=" + to_html);
    gmarker.openInfoWindowHtml(to_html);
  } //end of toHere()

  /*------------------------------------------------------*
   * Function: fromHere()
   * Desc: Gets Google Maps directions from the specified coordinates
   * Notes:
   *------------------------------------------------------*/
  function fromHere(resLat, resLng, resTitle) {
    var from_html  = resTitle + '<br>Directions: <a href="javascript:toHere(' + resLat + ', ' + resLng + ', \'' + resTitle + '\')">To here</a> - <b>From here</b>' +
           '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + resLat + ',' + resLng +
           "(" + resTitle + ")" + 
           '"/>';
    gmarker.openInfoWindowHtml(from_html);
  } //end of fromHere()

  /*------------------------------------------------------*
   * Function: insertNthChar()
   * Desc: insert a character after every Nth character in a string
   * Notes:
   *------------------------------------------------------*/
  function insertNthChar(string, chr, nth) {
    var output = '';
    for (var i=0; i<string.length; i++) {
      if (i > 0 && i % nth == 0) {output += chr;}
      output += string.charAt(i);
    }

    return output;
  } //end of insertNthChar()

  /*------------------------------------------------------*
   * Function: submitRefFmt()
   * Desc: User wants to display ref(s) in a particular format
   * Notes:
   *------------------------------------------------------*/
  function submitRefFmt(action, form, param) {
    //param is the field that needs to be populated

    var sIdx = form.rfCode.selectedIndex;
    var rfCode = form.rfCode[sIdx].value;

    if (rfCode == 0) {return;}

    var cgi = "/cgi-bin/hk/art.cgi";
    var str = cgi + "?action=" + action + "&rfCode=" + rfCode;

    if (param == undefined) {  //its the "With selected" option
      param = ''; var cbStr = 'cb';
      for (var i=0; i < document.forms.length; i++) {
        var f = document.forms[i];
        if (f.name.indexOf('artForm') > -1) {
          for (var j=0; j < f.elements.length; j++) {
            var fElem = f.elements[j];
            var idx = fElem.name.indexOf(cbStr);
            if (idx > -1) {
              if (fElem.checked) {   //found a checked checkbox
                if (param != '') {param += ',';}
                param += fElem.name.substring(cbStr.length);
              }
            }
          } //for (var j=0; j < f.elements.length; j++)
        } //if ((f.name.indexOf('artForm') > -1))
      } //for (var i=0; i < document.forms.length; i++)

      if (param == '') {
        alert("Please select at least one item! \n");
        return;
      }

      //form.artId.value = param;

    } //if (param == undefined)

    str += "&artId=" + param;

    var winWidth      = 600;
    var winHeight     = 400;
    var winScrollbars = 'yes';

    var winStr = 'width='+winWidth+',height='+winHeight+',scrollbars='+winScrollbars;
    winStr += ',menubar=no,resizable=yes,location=no,statusbar=no,screenX=150,screenY=150,top=150,left=150';

    //alert("action=" + action + " form=" + form + " param=" + param +
    //      " str=" + str);

    window.open(str,'Reference',winStr);

    return;

  } // submitRefFmt()

  /*** nkk - since this code is not in use but the fn() is being called
	       in <body> of every shtml file, put a dirty fix here.
       This fix used to be in imageCarousal.js but then the file still
       needed to be called. Not if does not have to be. ***/
  function Carousel() {return;}
