///////////////////////////////////////////////////////////////////////////////
//
// RemoveTrailingSpaces
//
///////////////////////////////////////////////////////////////////////////////

function RemoveTrailingSpaces(strVal) {
  var nPos = 0;

  if (IsEmpty(strVal))
    return strVal;

  for (nPos = strVal.length-1; nPos >= 0; nPos--) {
    if (whitespace.indexOf(strVal.charAt(nPos)) == -1)
      break;
  }

  return (nPos == strVal.length-1 ? strVal.substring(0) : strVal.substring(0, nPos+1));
}

///////////////////////////////////////////////////////////////////////////////
//
// RemoveLeadingSpaces
//
///////////////////////////////////////////////////////////////////////////////

function RemoveLeadingSpaces(strVal) {
  var nPos = 0;

  if (IsEmpty(strVal))
    return strVal;

  for (nPos = 0; nPos < strVal.length; nPos++) {
    if (whitespace.indexOf(strVal.charAt(nPos)) == -1)
      break;
  }

  return strVal.substring(nPos);
}

///////////////////////////////////////////////////////////////////////////////
//
// RemoveSpaces
//
///////////////////////////////////////////////////////////////////////////////

function RemoveSpaces(strVal) {
  return (IsEmpty(strVal) ? strVal:RemoveLeadingSpaces(RemoveTrailingSpaces(strVal)));
}

///////////////////////////////////////////////////////////////////////////////
//
// IsEmpty: Check whether string strVal is empty
//
///////////////////////////////////////////////////////////////////////////////

function IsEmpty(strVal) {
  return ((strVal == null) || (strVal.length == 0));
}

///////////////////////////////////////////////////////////////////////////////
//
// IsWhitespace: Check if string strVal has only the whitespace characters
//
///////////////////////////////////////////////////////////////////////////////

// whitespace characters: ' ', '\t', '\r', '\n'
var whitespace = " \t\n\r";

function IsWhitespace(strVal) {
  var nPos = 0;

  if (IsEmpty(strVal))
    return false;

  for (nPos = 0; nPos < strVal.length; nPos++)
    if (whitespace.indexOf(strVal.charAt(nPos)) == -1)
      return false;

  return true;
}

///////////////////////////////////////////////////////////////////////////////
//
// Replace: replaces one occurrence of strVal with strWith in strSrc
//
///////////////////////////////////////////////////////////////////////////////

function Replace(strSrc, strVal, strWith) {
  var nPos = 0, strLeft="", strRight="";

  // check if empty (or) no string is found to replace
  if (IsEmpty(strSrc) || (strSrc.indexOf(strVal) < 0))
    return strSrc;

  nPos = strSrc.indexOf(strVal);
  strLeft = strSrc.substring(0, nPos);
  nPos += strVal.length;
  strRight = strSrc.substring(nPos);

  return (strLeft + strWith + strRight);
}

///////////////////////////////////////////////////////////////////////////////
//
// ReplaceAll : replace all occurrences of strVal with strWith in strSrc
//
///////////////////////////////////////////////////////////////////////////////

function ReplaceAll(strSrc, strVal, strWith) {
  var strBuffer=strSrc;

  while (strBuffer.indexOf(strVal) >= 0)
    strBuffer = Replace(strBuffer, strVal, strWith);

  return (strBuffer);
}

///////////////////////////////////////////////////////////////////////////////
//
// Occurs: return no of occurrences of strVal within strSrc
//
///////////////////////////////////////////////////////////////////////////////

function Occurs(strVal, strSrc) {
  var nCnt = 0, strBuffer=strSrc;

  while (strBuffer.indexOf(strVal) >= 0) {
    strBuffer = Replace(strBuffer, strVal, "");
    nCnt++;
  }

  return (nCnt);
}

///////////////////////////////////////////////////////////////////////////////
//
// NOTE: 
//  -- alway RemoveSpaces field value before calling any of these functions
//  -- if field is empty, the function call will return true
//
///////////////////////////////////////////////////////////////////////////////

// IsDigit: check if val has digits (0-9)
function IsDigit(val) {
  var strBuffer = new String(val);
  var nPos = 0;

  if (IsEmpty(strBuffer))
    return false;

  for (nPos = 0; nPos < strBuffer.length; nPos++)
    if (strBuffer.charAt(nPos) < '0' || strBuffer.charAt(nPos) > '9')
      return false;

  return true;
}

// IsAlpha: check if val has alphabets only (a-z, A-Z)
function IsAlpha(val) {
  var strBuffer = new String(val);
  var nPos = 0;

  if (IsEmpty(strBuffer))
    return false;

  for (nPos = 0; nPos < strBuffer.length; nPos++)
    if (!((strBuffer.charAt(nPos) >= 'a' && strBuffer.charAt(nPos) <= 'z') ||
        (strBuffer.charAt(nPos) >= 'A' && strBuffer.charAt(nPos) <= 'Z')))
      return false;

  return true;
}

// IsInteger: check if nVal is integer type
function IsInteger(nVal) {
  var strBuffer = new String(nVal);
  var nPos = 0, nStart = 0;

  if (IsEmpty(strBuffer))
    return true;
  if (IsWhitespace(strBuffer))
    return false;

  // check if -ve or +ve sign occurs in the beginning
  if ((strBuffer.charAt(0) == '-') || (strBuffer.charAt(0) == '+'))
    nStart = 1;
  else
    nStart = 0;

  for (nPos = nStart; nPos < strBuffer.length; nPos++)
    if (strBuffer.charAt(nPos) < '0' || strBuffer.charAt(nPos) > '9')
      return false;

  return true;	
}

// IsFloat: check if fVal is floating-point type
//	LIMITATION: no scientific notation (for eg: xxxx.xxE+xx)
function IsFloat(fVal) {
  var strBuffer = new String(fVal);
  var nPos = 0, nStart = 0;

  if (IsEmpty(strBuffer))
    return true;
  if (IsWhitespace(strBuffer))
    return false;

  // check if -ve or +ve sign occurs in the beginning
  if ((strBuffer.charAt(0) == '-') || (strBuffer.charAt(0) == '+'))
    nStart = 1;
  else
    nStart = 0;

  for (nPos = nStart; nPos < strBuffer.length; nPos++)
    if ((strBuffer.charAt(nPos) < '0' || strBuffer.charAt(nPos) > '9') && 
        (strBuffer.charAt(nPos) != '.'))
      return false;

  return true;
}


///////////////////////////////////////////////////////////////////////////////
//
// Commify
//
// The following function is used to add commas to a number
//
// Input:  Number to commify
// 
// Return: Commified number
//
///////////////////////////////////////////////////////////////////////////////

function Commify(tNum) {
  var Num = tNum.toString();
  var newNum = "";
  var newNum2 = "";
  var count = 0;

  //check for decimal number
  if (Num.indexOf('.') != -1) { //number ends with a decimal point
    if (Num.indexOf('.') == Num.length-1)
      Num += "00";
    if (Num.indexOf('.') == Num.length-2) //number ends with a single digit
      Num += "0";

    var a = Num.split("."); 
    Num = a[0]; //the part we will commify
    var end = a[1] //the decimal place we will ignore and add back later
  } else {
    var end = "00";
  } 

  //this loop actually adds the commas 
  for (var k = Num.length-1; k >= 0; k--){
    var oneChar = Num.charAt(k);
    if (count == 3) {
      newNum += ",";
      newNum += oneChar;
      count = 1;
      continue;
    } else {
      newNum += oneChar;
      count ++;
    }
  } //but now the string is reversed!

  //re-reverse the string
  for (var k = newNum.length-1; k >= 0; k--) {
    var oneChar = newNum.charAt(k);
    newNum2 += oneChar;
  }

  // add dollar sign and decimal ending from above
  newNum2 = newNum2 + "." + end;
  return newNum2;
}

///////////////////////////////////////////////////////////////////////////////
//
// RoundNumber
//
// The following function is used to round real numbers to a
// a given precision.
//
// Input:  Number to round
//         Precision
//
// Return: Rounded number
//
///////////////////////////////////////////////////////////////////////////////

function RoundNumber(num, precision) {

  var roundedNum, sign, oldNum, decimalValue;

  roundedNum = parseFloat(num);
  if ( isNaN(roundedNum) )
    return num;

  // Change neg numbers to positive for rounding and then change them back
  sign = roundedNum < 0.0? -1.0 : 1.0;
  roundedNum *= sign;

  // Move decimal point to the right according to the precision
  roundedNum *= Math.pow( 10, precision );
  oldNum = roundedNum;
  roundedNum = Math.floor( roundedNum );   
  decimalValue = oldNum - roundedNum;

  if ( decimalValue >= 0.499999999 )
    roundedNum += 1.0;

  // Move decimal point back to the correct position
  roundedNum /= Math.pow( 10, precision );

  // Put the correct sign back on the number
  if ( roundedNum != 0.0 )
    roundedNum *= sign;

  return roundedNum;

}

///////////////////////////////////////////////////////////////////////////////
//
// FormatNumber
//
// The following function is used to format a number to a specified precision.
//
// Input:  Number
//         Precision
//
// Return: Rounded number as a string
//
///////////////////////////////////////////////////////////////////////////////

function FormatNumber(num, precision) {

  var rNum = RoundNumber( num, precision );
  var strNum = new String(rNum);
  var i = 0, decPos = 0;
  var decimalFound = false;
  var numPlaces = 0;

  for (i = 0; i < strNum.length; i++) {
    if (strNum.charAt(i) == '.') {
      decPos = i;
      decimalFound = true;
    }
  }

  if ( decimalFound ) {
    numPlaces = strNum.length - decPos - 1;
  }
  else {
    strNum += '.';
  }

  for (i = numPlaces; i < precision; i++) {
    strNum += '0';
  }

  return strNum;

}

///////////////////////////////////////////////////////////////////////////////
//
// ConvertToFloat
//
// The following function is used to convert a string to a float
//
// Input:  Number
//
// Return: Converted float
//
///////////////////////////////////////////////////////////////////////////////

function ConvertToFloat( str ) {
  var strBuffer = new String(str);
  var nPos = 0;
  var newStr = "";
  var digitFound = false;
  var negNum = false;

  RemoveSpaces( strBuffer );

  if ( IsEmpty( strBuffer ) ) {
    return( 0.0 );
  }

  for (nPos = 0; nPos < strBuffer.length; nPos++) {
    var currChar = strBuffer.charAt(nPos);
    if (currChar != '(' && currChar != '$' &&
        currChar != ','&& currChar != ')') {
      if ( currChar >= '0' && currChar <= '9' ) {
        digitFound = true;
      }
      newStr += currChar;
    } else if ( currChar == '(' ) {
      negNum = true;
    }
  }

  if ( digitFound ) {
    return( negNum? parseFloat( newStr ) * -1.0 : parseFloat( newStr ) );
  } else {
    return( 0.0 );
  }

}

///////////////////////////////////////////////////////////////////////////////
//
// CleanNumber
//
// The following function is used to strip dollar signs and commas from number
// strings
//
// Input:  String representation of a number
//
// Return: Rounded number as a string
//
///////////////////////////////////////////////////////////////////////////////

function CleanNumber(numStr) {
	var strBuffer = new String(numStr);
  var newStr = "";
  var i = 0;

  for (i = 0; i < strBuffer.length; i++) {
    var currChar = strBuffer.charAt(i);
    if (currChar != '$' && currChar != ',') {
      newStr += currChar;
    }
  }

  return newStr;
}

///////////////////////////////////////////////////////////////////////////////
//
// PreLoadImage
//
// Preload the image for later use
//
// Input:  Image to preload
//
///////////////////////////////////////////////////////////////////////////////

function PreLoadImage( image ) {
  if ( document.images ) {
    img = new Image();
    img.src = image;
  }
}

///////////////////////////////////////////////////////////////////////////////
//
// DisableField
//
// The following function disables the given element
//
///////////////////////////////////////////////////////////////////////////////

function DisableField ( field ) {
	field.disabled = !(field.disabled);
}

///////////////////////////////////////////////////////////////////////////////
//
// CancelEvent
//
// The following function cancels a window event
//
///////////////////////////////////////////////////////////////////////////////

function CancelEvent( bubble ) {
  window.event.returnValue = false;
  if ( bubble ) window.event.cancelBubble = true;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetContainerWith
//
// Starting with the given node, find the nearest containing element
// with the specified tag name and style class.
//
///////////////////////////////////////////////////////////////////////////////

function GetContainerWith(node, tagName, className) {

  while (node != null) {
    if (node.tagName != null && node.tagName == tagName &&
        HasClassName(node, className))
      return node;
    node = node.parentNode;
  }

  return node;
}

///////////////////////////////////////////////////////////////////////////////
//
// HasClassName
//
// Return true if the given element currently has the given class name.
//
///////////////////////////////////////////////////////////////////////////////

function HasClassName(el, name) {

  var i, list;

  list = el.className.split(" ");
  for (i = 0; i < list.length; i++)
    if (list[i] == name)
      return true;

  return false;
}

///////////////////////////////////////////////////////////////////////////////
//
// RemoveClassName
//
// Remove the given class name from the element's className property.
//
///////////////////////////////////////////////////////////////////////////////

function RemoveClassName(el, name) {
  var i, curList, newList;

  if (el.className == null)
    return;

  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}

///////////////////////////////////////////////////////////////////////////////
//
// GetPageOffsetLeft
//
// Return the x coordinate of an element relative to the page.
//
///////////////////////////////////////////////////////////////////////////////

function GetPageOffsetLeft(el) {
  var x;

  x = el.offsetLeft;
  if (el.offsetParent != null)
    x += GetPageOffsetLeft(el.offsetParent);

  return x;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetPageOffsetTop
//
// Return the x coordinate of an element relative to the page.
//
///////////////////////////////////////////////////////////////////////////////

function GetPageOffsetTop(el) {
  var y;

  y = el.offsetTop;
  if (el.offsetParent != null)
    y += GetPageOffsetTop(el.offsetParent);

  return y;
}

///////////////////////////////////////////////////////////////////////////////
//
// CheckElHidden
//
// Check to see if the given element is contained within a hidden object.  It
// traverses up the object tree until no parent is found, or until it finds
// a parent that is hidden.
//
// Input:  Element to check
// 
// Return: true if 'hidden' found in object tree
//         false otherwise
//
///////////////////////////////////////////////////////////////////////////////

function CheckElHidden( el ) {
  if ( el ) {
    if ( el.currentStyle.visibility == 'hidden' )
      return true;

    var parentEl =  el.parentElement;
    while ( parentEl ) {
      if ( parentEl.currentStyle.visibility == 'hidden' )
        return true;
      parentEl = parentEl.parentElement;
    }
  }

  return false;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetEventSrc
//
// Get the source of the current window event
//
// Input:  Event
// 
// Return: event element
//
///////////////////////////////////////////////////////////////////////////////

function GetEventSrc(e) {
  if (!e) e = window.event;

  if (e.target)
    return e.target;
  else if (e.srcElement)
    return e.srcElement;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetObjPosition
//
// Get the position of the given object
//
// Input:  Object
// 
// Return: position structure
//
///////////////////////////////////////////////////////////////////////////////

function GetObjPosition( el ) {
  var SL = 0, ST = 0;
  var is_div = /^div$/i.test(el.tagName);
  if (is_div && el.scrollLeft)
    SL = el.scrollLeft;
  if (is_div && el.scrollTop)
    ST = el.scrollTop;
  var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
  if (el.offsetParent) {
    var tmp = GetObjPosition(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

///////////////////////////////////////////////////////////////////////////////
//
// GetObjVisibility
//
// Get the visibility of the given object
//
// Input:  Object
// 
// Return: visibility
//
///////////////////////////////////////////////////////////////////////////////

function GetObjVisibility(obj) {
  var value = obj.style.visibility;
  if (!value) {
    if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") {
      if (!BrowserIs_khtml)
        value = document.defaultView.
          getComputedStyle(obj, "").getPropertyValue("visibility");
      else
        value = '';
    } else if (obj.currentStyle) { // IE
      value = obj.currentStyle.visibility;
    } else
      value = '';
  }
  return value;
}

///////////////////////////////////////////////////////////////////////////////
//
// HideShowCovered
//
// Set the visibility to 'hidden' for all tags that show through objects that
// draw over them
//
// Input:  Object that will be visible
// 
///////////////////////////////////////////////////////////////////////////////

function HideShowCovered( obj, saveName ) {
  var tags = new Array("applet", "iframe", "select");
  saveName = saveName? saveName : '__save_visibility';

  var p = GetObjPosition(obj);
  var EX1 = p.x;
  var EX2 = obj.offsetWidth + EX1;
  var EY1 = p.y;
  var EY2 = obj.offsetHeight + EY1;

  for (var k = tags.length; k > 0; ) {
    var ar = document.getElementsByTagName(tags[--k]);
    var cc = null;

    for (var i = ar.length; i > 0;) {
      cc = ar[--i];

      if (!IsChildOfParent(cc, obj)) {
        p = GetObjPosition(cc);
        var CX1 = p.x;
        var CX2 = cc.offsetWidth + CX1;
        var CY1 = p.y;
        var CY2 = cc.offsetHeight + CY1;

        if (self.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
          if (!cc[saveName]) {
            cc[saveName] = GetObjVisibility(cc);
          }
          cc.style.visibility = cc[saveName];
        } else {
          if (!cc[saveName]) {
            cc[saveName] = GetObjVisibility(cc);
          }
          cc.style.visibility = "hidden";
        }
      }
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
//
// GetMouseCoords
//
// Get the mouse coordinates
//
// Input:  event
//
///////////////////////////////////////////////////////////////////////////////

function GetMouseCoords( e ) {
	if (!e)
		return { x:0, y:0 }

	if (e.pageX || e.pageY)
		return { x:e.pageX, y:e.pageY };

	var docScrollLeft = (document.documentElement)? document.documentElement.scrollLeft : document.body.scrollLeft;
	var docClientLeft = (document.documentElement)? document.documentElement.clientLeft : document.body.clientLeft;
	var docScrollTop = (document.documentElement)? document.documentElement.scrollTop : document.body.scrollTop;
	var docClientTop = (document.documentElement)? document.documentElement.clientTop : document.body.clientTop;
	
	return { x:e.clientX + docScrollLeft - docClientLeft,
             y:e.clientY + docScrollTop - docClientTop };
}

///////////////////////////////////////////////////////////////////////////////
//
// IsChildOfParent
//
// Check to see if the given element is a child of the given parent
//
// Input:  Element to check, parent
// 
// Return: true if element is a child of the parent false otherwise
//
///////////////////////////////////////////////////////////////////////////////

function IsChildOfParent( el, parent ) {
  if ( el && parent ) {
    if ( el == parent )
      return true;

    var parentEl =  el.parentElement;
    while ( parentEl ) {
      if ( parentEl == parent )
        return true;
      parentEl = parentEl.parentElement;
    }
  }
  return false;
}

///////////////////////////////////////////////////////////////////////////////
//
// FindPositionX
//
// Find the x position of the given object
//
///////////////////////////////////////////////////////////////////////////////

function FindPositionX(obj) {
  var curleft = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  } else if (obj.x) {
    curleft += obj.x;
  }
  return curleft;
}

///////////////////////////////////////////////////////////////////////////////
//
// FindPositionY
//
// Find the y position of the given object
//
///////////////////////////////////////////////////////////////////////////////

function FindPositionY(obj) {
  var curtop = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  } else if (obj.y) {
    curtop += obj.y;
  }
  return curtop;
}

///////////////////////////////////////////////////////////////////////////////
//
// SetOpacity
//
///////////////////////////////////////////////////////////////////////////////

function SetOpacity(obj, opacity) {
  opacity = (opacity == 100)? 99.999 : opacity;
  
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  
  // Safari < 1.2, Konqueror
  obj.style.KHTMLOpacity = opacity / 100;
  
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity / 100;
  
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity / 100;
}

///////////////////////////////////////////////////////////////////////////////
//
// WindowOpen
//
// Open a javascript window centered on the screen
//
///////////////////////////////////////////////////////////////////////////////

function WindowOpen(url, name, w, h) {
  if (w > screen.width) {
    w = screen.width;
    wleft = 0;
  } else {
    wleft = (screen.width - w) / 2;
  }
  
  if (h > (screen.height - 60)) {
    h = screen.height - 60;
    wtop = 0;
  } else {
    wtop = (screen.height - h) / 2;
  }
  
  
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  
  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=yes, menubar=no, titlebar=no, directories=no ' +
    'status=yes, toolbar=no, scrollbars=yes, resizable=yes');
    
  // Just in case width and height are ignored
  win.resizeTo(w, h);
  
  // Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.focus();
  
  return win;
}

function ShowEmailForm(EmailId) {
    var url = '/SendMail.aspx?EmailId=' + EmailId;
    editWin = WindowOpen(url, 'SendMail', 668, 600);
}
