
var g_fFieldsChanged = 0;
var g_fFieldValue;
var g_fFieldId;
var executingPostBack = false;

AddEventHandler(window, "load", initWarnIfChanges);

function initWarnIfChanges()
{
	var allAnchors = document.getElementsByTagName("a");
	for ( var inxAnchor = 0 ; inxAnchor < allAnchors.length ; inxAnchor++ )
	{
		var a = allAnchors[inxAnchor];
		if ( (a.href.indexOf('__doPostBack') > 0 || a.href.indexOf('DoPostCallBack') > 0 || a.href.indexOf('DoPostBack') > 0)
		      && a.className != 'iC_SubSystemMenu'
		      && a.className != 'iC_SubSystemMenuSelected')
		{
		   //var id = a.getAttribute("id");
		   // some controls might not have an ID, FireFox will throw out an exception in this case.
		   //if (id==null) id = "";
		   
		   // # changed on June/12/2006 Hong:
		   // the idea is correct, but it doesn't work; cause it will prompt twice. not sure how to fix it
		   
		   // the reason of it is, in some information page, we might have a minisearch on top, when we are changing the 
		   // information page data, clicking search is thought as leaving this page. 
		   // (note: AdvSearch should be treated the same, but it is not working because its id is just ExtraButton1; we will change that to AdvSearchButton eventually, so later it will work)
		   // another criteria is, on a navigator, clicking New button will be treated as leaving the current page.
		   //if ( (id.indexOf('MiniSearch') >0 && id.indexOf("SearchButton")>0) ||
		   //     (id.indexOf('PageNav')>0 && id.indexOf('NewButton')>0 ) )
		   //{
		      // do nothing 
		      // continue;
		   //}
		   //else
		   //{
		        AddEventHandler(a, "click", setExecutionFlag);

		   //}
		}
		else
		{
	      // we should always reset the executionFlag if the user clicks other click
	      // one situation might be: a user is modifying a page, and tries to open a subpanel, which is very slow.
	      // during the waiting, the user accidentally clicks any link on the page.
	      // without this reset, it will navigate away the current page
		  AddEventHandler(a, "click", resetExecutionFlag);
		   
		}
	}
}

function resetExecutionFlag()
{
	executingPostBack = false;
}

function setExecutionFlag()
{
	executingPostBack = true;
}

function deb_ssnize (string)
{
   if (string.length == 9)
      return string.substring(0,3) + "-" + string.substring(3,5) + "-" + string.substring(5,9);
   else
      return string;
}
		
function deb_unssnize (string)
{
   var re = new RegExp ("-", "g");
   return string.replace(re,"");
}

function deb_phoneize (string)
{
   // Remove any spaces
   string = removeOccurrences(string, /[\s]/);
   if (string.length == 10)
      return "(" + string.substring(0,3) + ")" + string.substring(3,6) + "-" + string.substring(6,10);

   else if (string.length == 7)
      return string.substring(0,3) + "-" + string.substring(3,7);
   else
      return string;
}
		
function deb_unphoneize (string)
{
   var re = new RegExp ("[\(\)-]", "g");
   return string.replace(re,"");
}

function deb_mmyyyyDateize (mystr)
{
   var q, dd, yy;
   dd = null;

   //Try to match mm/yyyy
   var re = new RegExp ("^(\\d{1,2})[\\/\\.-]?(\\d{1,4})$");
   var re = new RegExp 
   var reDelims = new RegExp ("^([0]?[1-4])[\\/\\.-](\\d{1,4})$");
   var reDigits = new RegExp ("^(0[1-4])(\\d{4})$");
	 
   // Remove any spaces
   mystr = removeOccurrences(mystr,/[\s]/);
       
	 if ( reDelims.test(mystr) )
      var flds = mystr.match(reDelims);
	 else
   {
	    if ( reDigits.test(mystr) )
         var flds = mystr.match(reDigits);
			else
         return mystr;
	 }

   if (flds == null)   //no match
     return mystr;

   q = flds[1];
   yy = flds[2];   
  
   if (yy.length < 4 && yy < 100)
      yy = 2000 + parseInt(yy,10);
   
   yy = "000" + yy;
   yy = yy.substr(yy.length-4,yy.length);
   
   return q + "/" + yy;
}

function deb_qyyyyDateize (mystr)
{
   var q, yy;

   //Try to match q/yyyy or qyyyy
   var reDelims = new RegExp ("^([1-4])[\\/\\.-](\\d{4})$");
   var reDigits = new RegExp ("^([1-4])(\\d{4})$");  
	 
   // Remove any spaces
   mystr = removeOccurrences(mystr,/[\s]/);
       
	 if ( reDelims.test(mystr) )
      var flds = mystr.match(reDelims);
	 else
   {
	    if ( reDigits.test(mystr) )
         var flds = mystr.match(reDigits);
	    else
         	return mystr;
	 }

   if (flds == null)   //no match
     return mystr;

   q = flds[1];
   yy = flds[2];   
   
   return q + "/" + yy;
}

function deb_mmyyyyDateize (mystr)
{
   var mm, dd, yy;
   dd = null;

   //Try to match mm/yyyy
   var re = new RegExp ("^(\\d{1,2})[\\/\\.-]?(\\d{1,4})$");
   var re = new RegExp 
   var reDelims = new RegExp ("^([0]?[1-9]|1[0-2])[\\/\\.-](\\d{1,4})$");
   var reDigits = new RegExp ("^(0[1-9]|1[0-2])(\\d{4})$");
	 
   // Remove any spaces
   mystr = removeOccurrences(mystr,/[\s]/);
       
	 if ( reDelims.test(mystr) )
      var flds = mystr.match(reDelims);
	 else
   {
	    if ( reDigits.test(mystr) )
         var flds = mystr.match(reDigits);
			else
         return mystr;
	 }

   if (flds == null)   //no match
     return mystr;

   mm = "0" + flds[1];
   yy = flds[2];   
   
   mm = mm.substr(mm.length-2,mm.length);
      
   if (yy.length < 4 && yy < 100)
      yy = 2000 + parseInt(yy,10);
   
   yy = "000" + yy;
   yy = yy.substr(yy.length-4,yy.length);
   
   return mm + "/" + yy;
}
		
function deb_dateize (mystr)
{
	var mm, dd, yy;
	dd = null;

	// Date expressions
	var reDelims = new RegExp ("^(\\d{1,2})[\\/\\.-](\\d{1,2})[\\/\\.-](\\d{1,4})$");
	var reDigits = new RegExp ("^(\\d{2})(\\d{2})(\\d{4})$");
	
	// DateTime expressions
	var reDelimsTime = new RegExp ("^(\\d{1,2})[\\/\\.-](\\d{1,2})[\\/\\.-](\\d{1,4})([ ]{0,1})(\\d{1,2})[:](\\d{1,2})([ ]{0,1})([APap][Mm])$");
	var reDigitsTime = new RegExp ("^(\\d{2})(\\d{2})(\\d{4})([ ]{0,1})(\\d{1,2})(\\d{1,2})([ ]{0,1})([APap][Mm])$");
   // Remove any spaces
   mystr = removeOccurrences(mystr,/[\s]/);
	 
	if ( reDelims.test(mystr) )
		var flds = mystr.match(reDelims);
	else
	{
		if ( reDigits.test(mystr) )
			var flds = mystr.match(reDigits);
		else
		{
			if (reDelimsTime.test(mystr))
				var flds = mystr.match(reDelimsTime);
			else
			{
				if (reDigitsTime.test(mystr))
					var flds = mystr.match(reDigitsTime);
				else
					return mystr;
			}
		}
	}

   mm = "0" + flds[1];
	   
   dd = "0" + flds[2];
   dd = dd.substr(dd.length-2,dd.length);
		   
   yy = flds[3];
			
   mm = mm.substr(mm.length-2,mm.length);

   if (yy.length < 4 && yy < 100)
      yy = 2000 + parseInt(yy,10);
   
   yy = "000" + yy;
   yy = yy.substr(yy.length-4,yy.length);
   
	var hh;
	var mi;
	var ampm;

   	if (flds[5]==null)
	{
		return mm + "/" + dd + "/" + yy;
	}
	else
	{
		hh=flds[5];
		if (flds[6]==null)
		{
			mi="00";
		}
		else
		{
			mi=flds[6];
		}
	}

	if (hh == "00" || hh == "0")
		hh = "12";
	if (hh.length == 1)
		hh = "0" + hh;
	
	if (mi.length == 1)
		mi = "0" + mi;
	
	if (flds[8]==null)
		ampm = "AM";
	else
		ampm = flds[8].toUpperCase();
	
	if (ampm.length == 0)
		ampm = "AM";
   
   return mm + "/" + dd + "/" + yy + " " + hh + ":" + mi + " " + ampm;
}
	
function deb_numberize( string, num_decimals, is_currency )
{
	string = string+"";
	var OrigString = string;
	var pos;

    //Strip leading and trailing spaces
    string = string.replace(/(^\s*)|(\s*$)/,'');

    // First zap any commas the user may have entered
    var re = new RegExp(",", "g");
    string = string.replace(re, "");
    
    //If there is a preceding - sign, strip it out, 
	//but remeber it was there so you put it back
	var isNegative = 0;
    pos = string.indexOf("-");
    if (pos >= 0)
		{			
			isNegative = 1;
			re = new RegExp("-", "g");
			string = string.replace(re, "");
		}
		
    //If there are brackets, strip them out, 
	//but remeber it was there so you put it back		    
	var isBracketed = 0;
    pos = string.indexOf("(");
    if (pos >= 0)
		{			
			isBracketed = 1;
			re = new RegExp("[(]", "g");
			string = string.replace(re, "");
			re = new RegExp("[)]", "g");
			string = string.replace(re, "");
		}	
    
    // If this is not a valid number then just return the original string
    if (isNaN(string))
       return OrigString;       

    // If the length is zero, then do nothing    
    if (string.length == 0)
       return "";

	//Pad out the decimals if required
	if (num_decimals>0)
		{
			pos = string.indexOf(".");
			if (pos == -1) //Add the decimal point if not found
			{
				string+=".";
				pos = string.indexOf(".");
			}
				
			//how many decimals exist
			var numOfDec = (string.length - 1) - pos;
			//Add trailing zeros as required
			for(x=numOfDec;x<num_decimals;x++)
				string += "0";		
		}
	

    // Inject comma's into the string
    var newstr = "";
    var comma = "";
    pos = string.indexOf(".");
    if (pos >= 0)
        newstr = string.substr(pos);
     else
        pos = string.length;

    // Put a comma every third character
    while (pos > 3)
    {
		newstr = string.substring(pos-3, pos) + comma + newstr;
		comma = ",";
		pos -= 3;
	}

    // Finish out the string	
	newstr = string.substring(0,pos) + comma + newstr;

	//Place the negative sign back if required
	if (isNegative)
		newstr = "-" + newstr;

    // Add currency symbol if requested
    if (is_currency)
       newstr = "$" + newstr;
   
    // Add brackets if requested
    if (isBracketed)
       newstr = "(" + newstr + ")";
          
    // And the answer is!!
    return newstr;
}

function deb_unnumberize( string )
{
var orig_string;

    if (string.length == 0)
       return "";
 
    orig_string = string;      
	while ( string.match(/[\$,]/) )
	{
		string = string.replace(/[\$,]/, "");
	}

    //If there are brackets, strip them out, 
	//but remeber it was there so you put it back		    
	var isBracketed = 0;
    pos = string.indexOf("(");
    if (pos >= 0)
		{			
			isBracketed = 1;
			re = new RegExp("[(]", "g");
			string = string.replace(re, "");
			re = new RegExp("[)]", "g");
			string = string.replace(re, "");
		}	

    if (isNaN(string))
       return orig_string;

	string = string*1.0;
	
    // Add brackets if requested
    if (isBracketed)
       string = "(" + string + ")";
	
       
	return string;
}

function deb_HighlightField ( f )
{
   if( f.setSelectionRange ) 
      	{
        f.setSelectionRange(0,f.value.length);
        } 
   else if( f.createTextRange ) 
      	{
   	   var r = f.createTextRange();
              r.select();
        }  
}

function convertUpperCase(keyItem) 
{
	setTimeout('ConvertKey("' +keyItem.id+ '")', 1);
}
function ConvertKey(selObj) 
{
	document.getElementById(selObj).value = document.getElementById(selObj).value.toUpperCase();
}
function uppercaseOnFly(e)
{
    var e = e || event;    
    
	key = window.event ? e.keyCode: e ? e.which: null;
	if ((key > 0x60) && (key < 0x7B))
		changeKeycode(e, key-0x20);
}

/***********************************************************
* Remove all occurences of whatToRemove from originalStr.
* Leaves the origial string intact.  The param whatToRemove
* can be a standard string or a regular expression
***********************************************************/
function removeOccurrences(originalStr, whatToRemove)
{
  var orig_string;

  if (originalStr.length == 0)
    return "";
    
  if (whatToRemove.length == 0)
    return originalStr;
 
  orig_string = originalStr;      
  while ( orig_string.match(whatToRemove) )
  {
    orig_string = orig_string.replace(whatToRemove, "");
  }

  return orig_string;
}


/******************************************************
 * ic_checkMaxLength is intended to limit a textarea  *
 * characters to a maxlength.                         *
 ******************************************************/
function ic_checkMaxLength(elem, maxchars)
{
	if (elem.value.length > maxchars)
    { 
        elem.value=elem.value.substring(0,maxchars);
	var msg = "You have exceeded the maximum characters allowed for this field." +
	          "\n\nYour text has been truncated to the maximum " + maxchars + " characters.";
        alert(msg);
    }
}

/***********************************************************
*ic_checkMinMaxVals
* Check both the Min and Max values of the input textboxes
*CO16217 SA
***********************************************************/
function ic_checkMinMaxVals(val, args)
{
var valueToValidate = ValidatorTrim(ValidatorGetValue(val.controltovalidate));


	 if ((valueToValidate.length < parseInt(val.getAttribute("minimumlength"), 10) || (valueToValidate.length > parseInt(val.getAttribute("maximumlength"), 10))))
	    {
	 
            args.IsValid=false;
        }
  else
  {

  args.IsValid = true
  }
  
   
}
/***********************************************************
*ic_checkMaxVals
* Check Max values of the input textboxes
*CO16217 SA
***********************************************************/
function ic_checkMaxVals(val, args)
{
var valueToValidate = ValidatorTrim(ValidatorGetValue(val.controltovalidate));


	 if (valueToValidate.length > parseInt(val.getAttribute("maximumlength"), 10)) 
	    {
	 
            args.IsValid = false;
        }
  else
  {
  

   args.IsValid = true;
   }
}
/***********************************************************
*ic_checkMinVals
* Check Min values of the input textboxes
*CO16217 SA
***********************************************************/

function ic_checkMinVals(val, args)
{
var valueToValidate = ValidatorTrim(ValidatorGetValue(val.controltovalidate));


	 if (valueToValidate.length < parseInt(val.getAttribute("minimumlength"), 10)) 
	    {
	 
            args.IsValid=false;
        }
  
  else
  {

    args.IsValid = true;
    }
}

/***********************************************************
*ic_CleanPattern
* Cleans regex pattern before from quotes before handing it to the calling function
*CO16314 Sammy Ageil
***********************************************************/
function ic_CleanPattern(patternString)
    {
    charToRemove = '"';
    regExp = new RegExp("["+charToRemove+"]","g");
    return patternString.replace(regExp,"");
    }

/***********************************************************
*ic_checkDisallowed
* Cleans Disallowed Characters based on the pattern provided by the ascx file
*CO16314 Sammy Ageil
***********************************************************/
function ic_checkDisallowed(val, args)
{

var valueToValidate = ValidatorTrim(ValidatorGetValue(val.controltovalidate));
var pattern = ic_CleanPattern(val.getAttribute("pattern"));
regExp = new RegExp(pattern);
if(regExp.test(valueToValidate))
{
args.IsValid=false;
}
else
{
args.IsValid=true;
}  
}

function IsDate(source, args) 

{
	 //Valid MMDDYYYY must have exactly 8 digits or have deliminators
	 //with at least one digit for M/D/Y 
	 
   var reDelims = new RegExp ("^(\\d{1,2})[\\/\\.-](\\d{1,2})[\\/\\.-](\\d{1,4})$");
   var reDigits = new RegExp ("^(\\d{2})(\\d{2})(\\d{4})$");
	 
   // remove all spaces before we test
   args.Value = removeOccurrences(args.Value,/[\s]/);
	 if ( reDelims.test(args.Value) )
      var matchArray = args.Value.match(reDelims);
	 else
   {
	    if ( reDigits.test(args.Value) )
         var matchArray = args.Value.match(reDigits);
			else
      {
         args.IsValid = false;
         return;
      }
	 }

   var datestatus=true;

   month = matchArray[1]; // parse date into variables
   day = matchArray[2];
   year = matchArray[3];

  if (month < 1 || month > 12) 
  { // check month range
     datestatus=false;
  }

  if (day < 1 || day > 31) 
  {
     datestatus=false;
  }

  if ((month==4 || month==6 || month==9 || month==11) && day==31) 
 
  {
     datestatus=false;
  }

  if (month == 2) 
  { // check for february 29th
     var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
     if (day > 29 || (day==29 && !isleap)) 
     {
         datestatus=false;
		}
     }
   args.IsValid= datestatus; 
}

function IsDateTime(source, args)
{
	IsDate(source, args);
	if (args.IsValid)
	{
		return;
	}
	
	var reDelims = new RegExp ("^(\\d{1,2})[\\/\\.-](\\d{1,2})[\\/\\.-](\\d{1,4})([ ]{0,1})(\\d{1,2})[:](\\d{1,2})([ ]{0,1})([APap][Mm])$");
	var reDigits = new RegExp ("^(\\d{2})(\\d{2})(\\d{4})([ ]{0,1})(\\d{1,2})(\\d{1,2})([ ]{0,1})([APap][Mm])$");
	 
	if ( reDelims.test(args.Value) )
		var matchArray = args.Value.match(reDelims);
	else
	{
		if ( reDigits.test(args.Value) )
			var matchArray = args.Value.match(reDigits);
		else
		{
			args.IsValid = false;
			return;
		}
	}

	var datestatus=true;
	var hh;
	var mi;

	if (matchArray == null || matchArray[1]==null) 
	{
		args.IsValid = false;
		return;
	}
	else
	{
		if(matchArray[2]==null || matchArray[3]==null)
		{
			args.IsValid = false;
			return;
		}
	}
	if (matchArray[5]==null)
	{
		hh=0;
		mi=0;
	}
	else
	{
		hh=matchArray[5];
		if (matchArray[6]==null)
		{
			mi=0;
		}
		else
		{
			mi=matchArray[6];
		}
	}

	month = matchArray[1]; // parse date into variables
	day = matchArray[2];
	year = matchArray[3];

	if (month < 1 || month > 12) 
	{ // check month range
		datestatus=false;
	}

	if (day < 1 || day > 31) 
	{
		datestatus=false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) 
	{
		datestatus=false;
	}

	if (month == 2) 
	{ // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) 
		{
			datestatus=false;
		}
	}
	
	if (hh > 23 || hh < 0)
	{
		datestatus=false;
	}
	if (mi > 59 || mi < 0)
	{
		datestatus=false;
	}
	
	args.IsValid=datestatus; 
}

function deb_ndcize (string)
{
   if (string.length == 11)
      return string.substring(0,5) + "-" + string.substring(5,9) + "-" + string.substring(9,11);
   else
      return string;
}

function deb_ndcize (string)
{
   if (string.length == 11)
      return string.substring(0,5) + "-" + string.substring(5,9) + "-" + string.substring(9,11);
   else
      return string;
}
		
function deb_unndcize (string)
{
   var re = new RegExp ("-", "g");
   return string.replace(re,"");
}

function setKeyCode(e, key)
{
  var evnt = window.event ? window.event.srcElement : e ? e.target : null;
  
  if (!evnt)
    return;
  if (evnt && key != 8)    
    changeKeycode(e, key);
  else
    return;
}

// This method assumes that it's being called to handle an event that deals
// with keycodes.  It makes sure that only those characters specified in mask
// are accepted.
function AllowOnly(e, allowMask, disallowMask)
{
  var key =  getKeyCode(e);
  var strVal = String.fromCharCode(key);
  var keyDisallowed = false;
  
  // first check to weed out chars that we don't allow 
  if (disallowMask != null && disallowMask != "" && RegExp(disallowMask).test(strVal) == true && key != 8)
    keyDisallowed = true;
  
  if (keyDisallowed == false)
  {
    // so far the key is allowed
    if (allowMask != null && allowMask != "" && RegExp(allowMask).test(strVal) == false && key != 8)
        keyDisallowed = true;
  }

  if (keyDisallowed)
    key = 0;
     
  setKeyCode(e, key);
}

// CO # 14125 - Hoskins: Improve control over formatting and behaviour of Radio Button lists
// Add JavaScript to reset a selected radio button when it was selected and clicked
function toggleRadioButton(uniqueID, item)
{
    // Replace any ":" with "_"
    var re = new RegExp (":", "g");
    var varID = uniqueID.replace(re,"_");
   
    var elem = document.forms[0].elements[uniqueID];
   
    if (eval("typeof(g_" + varID + "_value) == 'undefined'")) {
        eval("g_" + varID + "_value='noradiobuttonselected'");
    }
   
    if (eval("g_" + varID + "_value == item.value")) {
        item.checked = !item.checked;
        eval("g_" + varID + "_value='noradiobuttonselected'");
    } else {
        for (i=0; i<elem.length; i++) {
            if (elem[i].checked) {
                eval("g_" + varID + "_value=elem[i].value");
            }
        }
    }
}

//CO#14520 - Oct-27/2006 - JIL : New functions addded to handled client side
//process of warning message preventing panles from close ('x' button) when
//they have pending changes on it.
function xAllowClose(id)
{
    var ele = window.document.getElementById(id);
    for(i=0; i<ele.childNodes.length; i++)
    {
        if(ele.childNodes[i].id.indexOf("_allowClose") != -1)
        {
            if( ele.childNodes[i].value == "1" )
            {
                alert('Please save or cancel any changes before closing the panel.');
                //Since we are returning false and cancelling the postback we need to stop any other event listeners 
                //from setting the executingPostBack flag to true
                window.event.srcElement.detachEvent('onclick',setExecutionFlag);
                resetExecutionFlag();
                return false;
            }
        }
    }
    
    return true;
}

function iCFieldChanged(ctl)
{    
    //Loop through the control parent until it bubbles up to the container panel
    
    if (ctl.nextSibling && ctl.nextSibling.controltovalidate)
    {
        ctl.nextSibling.enabled = true;
    }
    
    while(ctl.parentNode)
    {
        if(ctl.parentNode.className)
        {
          if(ctl.parentNode.className.indexOf("NavItemLoadedControl") != -1 || ctl.parentNode.className.indexOf("NavItemWizardLoadedControl") != -1)
            { 
                //Finds the datapanel container cell
                var v = window.document.getElementById(ctl.parentNode.parentNode.id );
                //Looks for the child hidden control used to persist the panel changed status
                for(i=0; i<v.childNodes.length; i++)
                {
                    if(v.childNodes[i].id.indexOf("_allowClose") != -1)
                    {
                        //-2 value is used to Disable the datachanged warning for an specific panel
                        if( v.childNodes[i].value != "-2" )
                        {
                            v.childNodes[i].value = "1";
                            g_fFieldsChanged++;
                            return;
                        }
                    }
                }
            }
        }
        ctl = ctl.parentNode;
    }
}
