
var mousePosX;
var mousePosY;

function isMicrosoftBrowser() {
  if (navigator.appName.indexOf("Microsoft") == -1) {
    return false;
  }
  return true;
}
  
function captureMousePosition(event) {
    if (isMicrosoftBrowser()) {
      event = window.event;
    }
    mousePosX = event.screenX;
    mousePosY = event.screenY;
}

/**
 * Prepends the specified base path onto the specified url if necessary.
 * This is required to support mouseovers.
 *
 * @pre pBasePath must be of the form http://www.foo.com/bar/
 *      and pRoot must be of the form http://www.foo.com/
 **/
function swtmMaybePrependBasePath(pURL,pBasePath,pRoot) {
  // Check the beginning for the following cases: http:// or // or /
  // If it is none of these cases, then prepend the base path.

  // If pURL start with a single / then pURL is relative to the
  // root of pBasePath.
  if (pURL.charAt(0) == "/" && 
      (pURL.length==1 || pURL.charAt(1) != "/")) {
      return pRoot + pURL.substring(1, pURL.length);
  }
  // If pURL starts with http:// or // then just return it
  if (pURL.indexOf("http://")==0 || pURL.indexOf("//")==0) {
      return pURL;
  }
  // The URL is relative to the base path
  return pBasePath + pURL;
}


/**
 * Somewhat browser independent way of retrieving elements
 **/
function _getElement(strID) {
    var el = null;
    if (document.getElementById) {
        el = document.getElementById(strID);  
    } else if (document.all) {
        el = document.all[strID];  
    }
    return el;
}

/**
 * Pops up a window
 **/
function openWindow(pURL,pHeight,pWidth) {
  var win = window.open(pURL,'popup','menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,width='+pWidth+',height='+pHeight);
  win.focus();
}

/**
 * Pops open a window, attempting to position it next to the current mouse position
 **/
function openWindowNextToMouse(pURL,pHeight,pWidth) {
  if (mousePosX - pWidth < 0) {
    mousePosX = pWidth;
  }
  if (mousePosY + pHeight > screen.height) {
    mousePosY -= (mousePosY + pHeight + 50) - screen.height;
  }
  mousePosX -= pWidth;
  mousePosY += 10;

  var win = window.open(pURL,'popup','screenX=' + mousePosX + ',left=' + mousePosX + 'screenY=' + mousePosY + ',top=' + mousePosY + 'menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,width='+pWidth+',height='+pHeight);
  win.focus();
  win.moveTo(mousePosX, mousePosY);
}

/**
 * Removes the leading and trailing spaces from a string
 * 
 * @see http://www.voy.com/1888/58.html
 **/ 
function trim(st) {
    var len = st.length
    var begin = 0, end = len - 1;
    while (st.charAt(begin) == " " && begin < len) {
        begin++;
    }
    while (st.charAt(end) == " " && begin < end) {
        end--;
    }
    return st.substring(begin, end+1);
}


/**
 * Format US phone numbers to look like (xxx) yyy-zzzz. Ignores any
 * phone number that does not have exactly 10 digits.
 * 
 * @see https://ssl.salesforce.com/js/functions.js
 * @see http://www.js-x.com/example/?ex=980&mode=1&COLOR_OFF=YES
 **/
function formatPhone (field) {
    field.value = trim(field.value);    

    var ov = field.value;
    var v = "";
    var x = -1;

    // is this phone number 'escaped' by a leading plus?
    if (0 < ov.length && '+' != ov.charAt(0)) { // format it
        // count number of digits
        var n = 0;
        if ('1' == ov.charAt(0)) {  // skip it
            ov = ov.substring(1, ov.length);
        }

        for (i = 0; i < ov.length; i++) {
            var ch = ov.charAt(i);

            // build up formatted number
            if (ch >= '0' && ch <= '9') {
                if (n == 0) v += "(";
                else if (n == 3) v += ") ";
                else if (n == 6) v += "-";
                v += ch;
                n++;
            }
            // check for extension type section;
            // are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
            if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
                x = i;
                break;
            }
        }
        // add the extension
        if (x >= 0) v += " " + ov.substring(x, ov.length);

        // if we recognize the number, then format it
        if (n == 10 && v.length <= 40) field.value = v;
    }
    return true;
}

/**
 * Used to set the page number while paginating through a table.
 * We prefer this to using a form as it allows us to avoid
 * nesting forms.
 * 
 * @param pTargetURL The URL to which to go redirect the user
 * @param pURLVars URL Vars to pass along. Should include everything 
 *                 except for this widget's field name.
 **/ 
function adTableRedirect(pSelectWidget, pFieldName, pTargetURL, pURLVars) {
  var value = pSelectWidget.options[pSelectWidget.selectedIndex].value;
  var url = pTargetURL + '?';
  if (pURLVars.length > 0) {
     url += pURLVars + '&';
  }
  url += pFieldName + '=' + value;
  window.location.href = url;
}


/**
 * Check all input fields (e.g. all checkboxes)
 * 
 * @param pFieldName The input field to check
 * @param pTrueFalse The value to which to set the checkboxes
 **/ 
function checkAll(pFieldName, pTrueFalse) {
  var inputFields = null;
  if (document.getElementsByTagName) {
     inputFields = document.getElementsByTagName("input");
  } else if (document.all) {
    inputFields = document.all.tags("input");
  } else {
    // no input fields could be found - just return
    return;
  }

  var fld, thisType, thisName;
  for (var i = 0; i < inputFields.length; i++) {
    fld = inputFields[i];
    if (! fld.type || fld.type != "checkbox" ) {
      continue;
    }
    if (! fld.name || fld.name != pFieldName ) {
      continue;
    }

    fld.checked = pTrueFalse;
  }
}

/**
 * Toggles the diplay attributes of our simple category menu
 **/
function toggleCategoryDisplay(strID, imgID) {
    var el = _getElement(strID);
    var img = _getElement(imgID);
    if (el.style.display != "none") {
        el.style.display = "none";
        img.src = "/images/util/plus-box.gif";
    } else {
        el.style.display = "block";
        img.src = "/images/util/minus-box.gif";
    }
}

/**
 * Toggles the diplay attributes of our simple category menu
 **/
function displayIfSelected(strID) {
    var el = _getElement(strID);
    if (el.style.display != "none") {
        el.style.display = "none";
    } else {
        el.style.display = "block";
    }
}


/**
 * Set display to none of all elements that begin with strPrefix
 **/
function setDisplayToNoneByPrefix(strPrefix) {
  var inputFields = null;
  if (document.getElementsByTagName) {
     inputFields = document.getElementsByTagName("div");
  } else if (document.all) {
    inputFields = document.all.tags("div");
  } else {
    // no input fields could be found - just return
    return;
  }
  // alert("setDisplayToNoneByPrefix: " +strPrefix + "-== " + inputFields);

  var fld, thisType, thisName;
  for (var i = 0; i < inputFields.length; i++) {
    fld = inputFields[i];
    if (fld.id && strPrefix == fld.id.substring(0, strPrefix.length) ) {
      fld.style.display = 'none';
    }
  }
}


/**
 * Set the diplay attribute of the element with the specified ID
 **/
function setDisplay(strID, strDisplay) {
    var elements = strID.split("|");
    var i = 0;
    while (i < elements.length) {
      var el = _getElement(elements[i]);
      if ( el != null ) {
        if (el.style.display != strDisplay) {
            el.style.display = strDisplay;
        }
      }
      i += 1;
    }
}

// Store the last field to allow the user to immediately correct what
// we auto-capitalize
var lastCapitalizedField = null;

/**
 * Capitalizes the specified word
 **/
function capitalizeWord(strWord) {
  return strWord.substring(0,1).toUpperCase() + strWord.substring(1, strWord.length);
}

/**
 * Capitalizes the first letter in each word (space separated). 
 * Does not touch any other characters.
 **/
function capitalizeWords(strID) {
  if (lastCapitalizedField != null && strID == lastCapitalizedField) {
    return;
  }
  lastCapitalizedField = strID;
  var el = _getElement(strID);
  var current = el.value;
  if (current != null) {
    var newValue;
    var words = current.split(' ');
    if (words.length == 0) {
      newValue = capitalizeWord(current);
    } else {
      newValue = '';
      for (var i=0; i < words.length; i++) {
        if (i > 0) {
          newValue += ' ';
        }
        newValue += capitalizeWord(words[i]);
      }
    }
  }
  el.value = newValue;
}
