function checkEnter(cmd, evt)
{   
    var keyCode = (window.event)?event.keyCode:evt.which
	if (keyCode == 13) {
        if(window.event) {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
        }
        else {
            evt.cancelBubble = true;
            evt.returnValue = false;
        }
        setTimeout(cmd,1);
        return false;
    }
}

function loadSelectFromObj(ctrl, obj, val, txt, preset) {
	// clear control first
	ctrl.length = 0;
	var offset = 0; 
	if (preset != undefined && preset != null) {
		ctrl.options[0] = new Option(preset,preset);
		++offset;
	}
	for (var i=0; i<obj.length; ++i) {
		ctrl.options[i+offset] = new Option(obj[i][txt], obj[i][val]);
	}            
	ctrl.selectedIndex = 0;
	return ctrl.length;
}

// Removes leading whitespaces
function LTrim( value ) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}
 
// Removes ending whitespaces
function RTrim( value ) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}
 
// Removes leading and ending whitespaces
function trim( value ) {
    return LTrim(RTrim(value));
}

//////STATUS BAR
var StatusTimer=new Object();
function updateStatusBar(elementID,status,message){
    //status 1 = success
    //status 2 = error
    //status else = no action
    var persists=(arguments[3]!=undefined)?arguments[3]:5000; /// optional persistence time passed as fourth argument
    
    clearTimeout(StatusTimer[elementID]);
    
    var statusBar=document.getElementById(elementID);
    var statusBarMessage=document.getElementById(elementID+'Message');
    if(status==1)statusBar.className="status_bar_green";
    else if(status==2)statusBar.className="status_bar_red";
    else statusBar.className="status_bar_grey";
    
    statusBarMessage.innerHTML=message;
    
    if(status==1 || status==2){
        StatusTimer[elementID] = setTimeout("updateStatusBar('"+elementID+"',3,'&nbsp;')", persists);
    }
    return StatusTimer[elementID];
}

////GET A VALUE FROM THE QUERY STRING
////variable must match the name of the Query String
////returns value on success and false if there is no such variable
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    } 
    return false;
}

////GET A VALUE FROM THE QUERY STRING
////variable must match the name of the Query String
////returns value on success and false if there is no such variable
//// case insensitive
function iGetQueryVariable(variable) {
    var lcVariable = variable.toLowerCase();
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0].toLowerCase() == lcVariable) {
            return pair[1];
        }
    } 
    return false;
}

////GET A VALUE FROM THE QUERY STRING
////variable must match the name of the Query String
////returns value on success and false if there is no such variable
//// case insensitive
function iGetQueryVariableMulti(variable) {
    var lcVariable = variable.toLowerCase();
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    var ret_val = new Array();
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0].toLowerCase() == lcVariable) {
            ret_val.push(pair[1]);
        }
    } 
    if(ret_val.length > 0) 
      return ret_val;
    else
      return false;
}



function getIFrameId(str) {
    var pos = 0;
    var lastpos = 0;
    var strId = "";
    var count = 0;
    if (str.indexOf("<iframe") != -1) 
    {
        while (pos > -1)
        {
            
            var pos = str.indexOf("<iframe", lastpos);
            if (pos > -1)
            {
                var idPos = str.indexOf("id=",pos);
                lastpos = idPos;
                if (idPos > -1) 
                {
                    idPos += "id='".length;
                    // now we're positioned right on first letter of frame id
                    if(count > 0)
                    {
                        strId += "|";
                    }
                    while (str.charAt(idPos) != "\"") {
                        strId += str.charAt(idPos);
                        ++idPos;
                    }
                    count++;
                }
                else
                {
                    pos = -1;
                }
            }
        }
    }
    else
    {
        return null;
    }
    return strId;

}    

//Creates an HTML Element of any type.
//Takes Properties and Style Attribute Arrays as third and fourth parameters.
function CreateHTMLElement(type,append){
    var text=(arguments[2]!=undefined && arguments[2]!="")?arguments[2]:null;
    var attributes=(arguments[3]!=undefined)?arguments[3]:Array();
    var styles=(arguments[4]!=undefined)?arguments[4]:Array();
    
    //alert(arguments[2]+":"+text);
    var element=document.createElement(type);
    for (var att in attributes) {if(typeof(attributes[att])!="function")element[att]=attributes[att];}
    for (var style in styles) {if(typeof(styles[style])!="function")element.style[style]=styles[style];}
    
    var textElement=null;
    if(text!=null)var textElement=document.createTextNode(text);
    
    if(!append)return element;
    
    if(type=="text"){append.appendChild(textElement); return textElement;}
    else{
        if(textElement!=null)element.appendChild(textElement);
        if(append!=undefined)append.appendChild(element);
        return element;
        }    
}

//Updates the cell with a new value and updates it with the appropriate style
function ChangeCell(cell,newVal,upStyle,downStyle,normStyle){           
    if(isNaN(newVal)){ 
        if(cell.tagName=="INPUT")cell.value=newVal;
        else cell.innerHTML=newVal;
        return; 
    }
    
    var CurrencyFlag=(arguments[5]!=undefined && arguments[2]!="")?arguments[5]:false;
    
    var valRef=(cell.tagName=="INPUT")?cell.value:cell.innerHTML;
        
    var curVal=Math.round(Number(valRef)*100)/100;
    var newVal=Math.round(Number(newVal)*100)/100;    
    var reverse=(arguments[5]!=undefined)? Boolean(arguments[5]):false;
            
    if(cell.tagName=="INPUT")cell.value=(CurrencyFlag)?formatAsMoney(newVal):newVal;
    else cell.innerHTML=(CurrencyFlag)?formatAsMoney(newVal):newVal;
    
    if(curVal<newVal)var styles=(!reverse)?downStyle:upStyle;
    else if(curVal>newVal)var styles=(!reverse)?upStyle:downStyle;
    else var styles=normStyle;
    
    for (var style in styles) {if(typeof(styles[style])!="function")cell.style[style]=styles[style];}
    
    return;        
}


//Returns the x and y coordiantes of and HTML Node
function findPosition( HTMLNode ) {
  if( HTMLNode.offsetParent ) {
    for( var posX = 0, posY = 0; HTMLNode.offsetParent; HTMLNode = HTMLNode.offsetParent ) {
      posX += HTMLNode.offsetLeft;
      posY += HTMLNode.offsetTop;
    }
    return [ posX, posY ];
  } else {
    return [ HTMLNode.x, HTMLNode.y ];
  }
}

function loopTillOptionsLoad(cmd, cnt, ddlName) {
        var objDdl = document.getElementById(ddlName)
        alert(objDdl.selectedIndex);
    if(objDdl.selectedIndex == -1) {
        cnt++;
        setTimeout("loopTillOptionsLoad('" + cmd + "'," + cnt + ",'" + ddlName + "');",100);
    }
    else if(cnt > 20) {
        return;
    }
    else {
        setTimeout(cmd,100);
    }
}
function IsNumber(val)
{
	var ValidChars = "0123456789";
	var Char;
	for (i = 0; i < val.length; i++) 
	{ 
		Char = val.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		 return false;
	}
	return true;
}
function ListboxSelectedValue(selBox)
{
    if(selBox.selectedIndex==-1)
        return "";
    else
        return selBox.options[selBox.selectedIndex].value;
}
function ListboxSelectedText(selBox)
{
    if(selBox.selectedIndex==-1)
        return "";
    else
        return selBox.options[selBox.selectedIndex].text;
}

//Used when using parseInt(parseVal(val))
//In JavaScript passing a number with a leading 0 to the parseInt() function designates that number as octal. 
//In octal, there is no 08 or 09. Therefore, these numbers are interpreted as 0.
function parseVal(val)
{
   while (val.charAt(0) == '0')
      val = val.substring(1, val.length);
 
   return val;
}

//Cookies
function setCookie(c_name,value,expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value)+ ((expiredays==null) ? "" : "; expires=" + exdate.toGMTString());
}

function setCookieRoot(c_name,value,expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value)+ ((expiredays==null) ? "" : "; expires=" + exdate.toGMTString()) + "; path=/";
}

function getCookie(c_name){
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1)
        { 
            c_start=c_start + c_name.length+1; 
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) 
                c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        } 
      }
    return "";
}

//ML 06/02/2008
//call for TextArea onkeydown to limit the length
//EXAMPLE: <textarea id="test" onkeydown="textAreaMax(this, 500)"></textarea>
function textAreaMax(object, max)
{
    if (object.value.length >= max)
        object.value = object.value.substring(0,max);                
}

function checkIfBlank(text)
{
    if (text == null || trim(text) == "")
        return false;
    else
        return true;
}

function isBlank(text)
{
    if (text == null || trim(text) == "")
        return true;
    else
        return false;
}

//addr= email value
//man= 1 mandatory, 0 not mandatory
//db= 1 alert reasons 0 no alerts
function validateEmail(addr,man,db) {
if (addr == '' && man) {
   if (db) alert('email address is mandatory');
   return false;
}
if (addr == '') return true;
var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
for (i=0; i<invalidChars.length; i++) {
   if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
      if (db) alert('email address contains invalid characters');
      return false;
   }
}
for (i=0; i<addr.length; i++) {
   if (addr.charCodeAt(i)>127) {
      if (db) alert("email address contains non ascii characters.");
      return false;
   }
}

var atPos = addr.indexOf('@',0);
if (atPos == -1) {
   if (db) alert('email address must contain an @');
   return false;
}
if (atPos == 0) {
   if (db) alert('email address must not start with @');
   return false;
}
if (addr.indexOf('@', atPos + 1) > - 1) {
   if (db) alert('email address must contain only one @');
   return false;
}
if (addr.indexOf('.', atPos) == -1) {
   if (db) alert('email address must contain a period in the domain name');
   return false;
}
if (addr.indexOf('@.',0) != -1) {
   if (db) alert('period must not immediately follow @ in email address');
   return false;
}
if (addr.indexOf('.@',0) != -1){
   if (db) alert('period must not immediately precede @ in email address');
   return false;
}
if (addr.indexOf('..',0) != -1) {
   if (db) alert('two periods must not be adjacent in email address');
   return false;
}
var suffix = addr.substring(addr.lastIndexOf('.')+1);
suffix = suffix.toLowerCase();
if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
   if (db) alert('invalid primary domain in email address');
   return false;
}
return true;
}


        function xtractJsFile(data){
            data = data.replace(/^\s|\s$/g, ""); //trims string

            //var m = data.match(/([^\/\\]+)\.(asp|html|htm|shtml|php)$/i);
            var m = data.match(/([^\/\\]+)\.(js)$/i);
            if (m)
                return {filename: m[1], ext: m[2]};
            else
                return null;
        }

function IncludeJs(file){
  var head = document.getElementsByTagName('head').item(0)
  var scriptTagInfo = xtractJsFile(file);
  if (!scriptTagInfo)
    return;
  var scriptTagId = scriptTagInfo.filename + scriptTagInfo.ext;
  var scriptTag = document.getElementById(scriptTagId);
  if(scriptTag) head.removeChild(scriptTag);
  script = document.createElement('script');
  script.src = file;
	script.type = 'text/javascript';
	script.id = scriptTagId;
	head.appendChild(script)
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}



