﻿// JScript File
//set up the object based on the browser type
function convertToObj(id){
   return document.getElementById?document.getElementById(id):document.all?document.all[id]:document.layers[id];
}

//hide object
function hide(id) {
    var obj = convertToObj(id);
    if (obj!=null)
        obj.style.display = "none";
}

//show object
function show(id) {
    var obj = convertToObj(id);
    if (obj!=null)
        obj.style.display = "block";
}

//show/hide object
function twist(id) {
    var obj = convertToObj(id);
    if (obj!=null){
        if (obj.style.display == "block")
            obj.style.display = "none";
        else
            obj.style.display = "block";
    }
}

//trim the string 
function Trim(str){
	while(str.charAt(0)==' '){
		str=str.substring(1,str.length);
	}
	while (str.charAt(str.length-1)==' '){
		str=str.substring(0,str.length-1);
	}
	return str;
}

function getValidator(id){
    for (var i=0; i<Page_Validators.length; i++){
        if (Page_Validators[i].controltovalidate == id 
                && Page_Validators[i].evaluationfunction.toString().indexOf('RegularExpressionValidatorEvaluateIsValid')!=-1){
            return Page_Validators[i];
        }
    }
    return null;
}

//format phone number
function FormatPhoneNumber(objNumber){
    var strNumber = Trim(objNumber.value);
    
    //validate first
    var obj = getValidator(objNumber.id);
    if (typeof(obj) != 'undefined' && obj != null ){
        ValidatorValidate(obj);
        if (!obj.isvalid)
            return strNumber;
    }
    
    if (strNumber!=""){
	var strInput="";       	//String to hold our entered number
	var strTemp="";        	//Temporary string to hold our working text
	var strCurrentChar=""; 	//Var for storing each character for eval.
	
	//Get all the numbers
	for (var i=0; i<strNumber.length; i++ ){
		strCurrentChar = strNumber.substring(i,i+1); 
		if ( !isNaN(strCurrentChar) && strCurrentChar!=null && strCurrentChar!=" "){
			strTemp += strCurrentChar;
		}
	}
	
	//Swap strTemp back to strInput for next set of validation
	strInput = strTemp
	strTemp = ""
	
	//Remove leading 1 if applicable
	if (strInput.length == 11 &&  strInput.substring(0, 1) == 1)
		strInput = strInput.substring(1);
	
	//Error catch to make sure strInput is proper length now that we've finished manipulating it.
	if (strInput.length != 10){
		//alert("The number you have entered is not correct.  Format includes area code.  Please check and retype.");
		objNumber.focus();
		return strNumber;
	}
	
	//Build the output string formatted to (xxx) xxx-xxxx
	strTemp = "(";                             //"("
	strTemp += strInput.substring(0,3); 	  //Area code
	strTemp += ") ";                 	  //") "
	strTemp += strInput.substring(3,6);	  //Exchange
	strTemp += "-";                   	  //"-"
	strTemp += strInput.substring(6);    	  //4 digit part

	//Set return value
	return strTemp;
   }
   else{
	return "";
   }
}

//format zip code
function FormatZip(objNumber){
    var strNumber = Trim(objNumber.value);
    
    //validate first
    var obj = getValidator(objNumber.id);
    if (typeof(obj) != 'undefined' && obj != null ){
        ValidatorValidate(obj);
        if (!obj.isvalid)
            return strNumber;
    }
    
    if (strNumber!=""){
	var strInput="";       	//String to hold our entered number
	var strTemp="";        	//Temporary string to hold our working text
	var strCurrentChar=""; 	//Var for storing each character for eval.
	
	//Get all the numbers
	for (var i=0; i<strNumber.length; i++ ){
		strCurrentChar = strNumber.substring(i,i+1); 
		if ( !isNaN(strCurrentChar) && strCurrentChar!=null && strCurrentChar!=" "){
			strTemp += strCurrentChar;
		}
	}
	
	//Swap strTemp back to strInput for next set of validation
	strInput = strTemp
	strTemp = ""	
	
	//Error catch to make sure strInput is proper length now that we've finished manipulating it.
	if ( strInput.length!=5 && strInput.length != 9){
		//alert("Your zip code is not correct.  Format includes five or nine digits. Please check and retype.");
		objNumber.focus();
		return strNumber;
	}

	//Build the output string formatted to xxxxx
	if ( strInput.length==5 )
		return strInput;

	//Build the output string formatted to xxxxx-xxxx
	if ( strInput.length==9 ){
		strTemp = strInput.substring(0,5); 	  //zip code
		strTemp += "-";                   	  //"-"
		strTemp += strInput.substring(5);    	  //4 digit part
	}
	return strTemp;
   }
   else{
	return "";
   }
}

//make sure no selection is enabled
function validateSelection(list, dropdown, value){
    var objList = convertToObj(list);
    var objDropDownList = convertToObj(dropdown);
    //alert(dropdown);
    //return;
    var types = new Array ('Primary', 'Nominating', 'Communications Contact', 'Financial Officer', 'Highest Ranking Executive', 'Project Director', 'Secondary');
    for (var i = 0; i<types.length; i++){
        if (objDropDownList.selectedIndex>0 && value!=types[i]){
            if (objDropDownList.options[objDropDownList.selectedIndex].value==types[i]){
                if (objList.innerHTML.indexOf(types[i])!=-1){
                    alert('Only one ' + types[i] + (types[i].indexOf('Contact')==-1 ? ' contact' : '') + ' allowed.');
                    objDropDownList.selectedIndex = -1;
                    objDropDownList.focus();
                }
            }
        }
    }
}

//display the popup
function preview(path, width, height){
	var windowprops = 'resizable=1,scrollbars=1,left=50,top=50,';
	if (width>0)
	    windowprops += 'width=' + (width+30) + ',height=' + (height+30); 
	preview1 = window.open(path, "Preview", windowprops, false); 
}

function previewEmail(path, width, height){
	var windowprops = 'scrollbars=1,left=50,top=50,';
	if (width>0)
	    windowprops += 'width=' + (width+30) + ',height=' + (height+30); 
	preview1 = window.open(path, "Preview", windowprops, false); 
}
function calPopup(path, width, height){
    //sometime the value of date is not passed correctly
    var qsParm = new Array(); 
    var queryStrings = path.substring(path.indexOf('?')+1);
    var parms = queryStrings.split('&');
    for (var i=0; i<parms.length; i++) {
        var pos = parms[i].indexOf('=');
            if (pos > 0) {
                var key = parms[i].substring(0,pos);
                var val = parms[i].substring(pos+1);
                qsParm[key] = val;
            }
    }
    textObj = convertToObj(qsParm['textbox']);
    if (Trim(textObj.value).length>0)
        qsParm['curdate'] = Trim(textObj.value);
    //alert(qsParm['curdate']);
    path = path.substring(0, path.indexOf('?')+1) + 'textbox=' + qsParm['textbox'] + '&curdate=' + qsParm['curdate'];
    
	var windowprops = "left=250,top=250,width=" + width + ",height=" + height; 
	preview1 = window.open(path, "Preview", windowprops, false); 
}

//hide upload function
function hideUpload(args){
    hide(arguments[0]);
    hide(arguments[1]);
    convertToObj(arguments[2]).enabled = false;
    convertToObj(arguments[3]).IsValid = true;
    convertToObj(arguments[3]).enabled = false;
}

/*a Repeater/DataList mangles the control IDs and group names, causing radiobutton to not work correctly. The fix is a simple bit of JavaScript that you can add to pages with Repeaters/DataList and RadioButton controls. */
function SetUniqueRadioButton(nameregex, current)
{
   re = new RegExp(nameregex);
   for(i = 0; i < document.forms[0].elements.length; i++)
   {
      elm = document.forms[0].elements[i]
      if (elm.type == 'radio')
      {
         if (re.test(elm.name))
         {
            elm.checked = false;
         }
      }
   }
   current.checked = true;
}

function clearSelection(args){
    for (var i=0; i<2; i++){
        var rdo = convertToObj(arguments[0] + '_' + i);
        if (rdo.checked)
            rdo.checked = false;
    }
}

//enable/disable fields based on type
function EnableSelections(args){
    parentObj = convertToObj(arguments[0]);
    focusObj = convertToObj(arguments[1]);
    focusValidator = convertToObj(arguments[2]);
    sipValidator = convertToObj(arguments[4]);
    coreValidator = convertToObj(arguments[6]);
    endObj = convertToObj(arguments[7]);
    if (parentObj.selectedIndex != -1){
        endObj.value = ''; //reset the end date to blank
        
        if (parentObj.selectedIndex == 0){ //sip program
            focusObj.disabled = false; //program focus is enabled
            focusValidator.enabled = true; //validation for program focus is enabled
            show(arguments[3]); //show sip duration
            sipValidator.enabled = true; //enable the sip duration validator
            hide(arguments[5]); //hide core duration
            coreValidator.enabled = false; //disable core duration validator
            coreValidator.IsValid = true; //set the core duration validator to valid status
            clearSelection(arguments[8]); //reset the selection
            clearSelection(arguments[9]);
        }
        else if (parentObj.selectedIndex == 1){//core program
            focusObj.selectedIndex = -1;
            focusObj.disabled = true; //disable proram focus
            focusValidator.enabled = false; //disable program focus validator
            focusValidator.IsValid = true; //set program focus validator to valid status
            show(arguments[5]); //show core duration
            coreValidator.enabled = true; //enable core duration validator
            hide(arguments[3]); //hide sip duration
            sipValidator.enabled = false; //disable sip duration validator
            sipValidator.IsValid = true; //set the sip duration validator to valid status
            clearSelection(arguments[8]); //reset the selection
            clearSelection(arguments[9]); 
        }
    }
}

//Date Add function
function dateAddExtention(p_Interval, p_Number){ 
   var thing = new String();    
    
   //in the spirt of VB we'll make this function non-case sensitive 
   //and convert the charcters for the coder. 
   p_Interval = p_Interval.toLowerCase(); 
    
   if(isNaN(p_Number)){ 
    
      //Only accpets numbers  
      //throws an error so that the coder can see why he effed up    
      throw "The second parameter must be a number. \n You passed: " + p_Number; 
      return false; 
   } 

   p_Number = new Number(p_Number); 
   switch(p_Interval.toLowerCase()){ 
      case "yyyy": {// year 
         this.setFullYear(this.getFullYear() + p_Number); 
         break; 
      } 
      case "q": {      // quarter 
         this.setMonth(this.getMonth() + (p_Number*3)); 
         break; 
      } 
      case "m": {      // month 
         this.setMonth(this.getMonth() + p_Number); 
         break; 
      } 
      case "y":      // day of year 
      case "d":      // day 
      case "w": {      // weekday 
         this.setDate(this.getDate() + p_Number); 
         break; 
      } 
      case "ww": {   // week of year 
         this.setDate(this.getDate() + (p_Number*7)); 
         break; 
      } 
      case "h": {      // hour 
         this.setHours(this.getHours() + p_Number); 
         break; 
      } 
      case "n": {      // minute 
         this.setMinutes(this.getMinutes() + p_Number); 
         break; 
      } 
      case "s": {      // second 
         this.setSeconds(this.getSeconds() + p_Number); 
         break; 
      } 
      case "ms": {      // second 
         this.setMilliseconds(this.getMilliseconds() + p_Number); 
         break; 
      } 
      default: { 
       
         //throws an error so that the coder can see why he effed up and 
         //a list of elegible letters. 
         throw   "The first parameter must be a string from this list: \n" + 
               "yyyy, q, m, y, d, w, ww, h, n, s, or ms.  You passed: " + p_Interval; 
         return false; 
      } 
   } 
   return this; 
} 
Date.prototype.dateAdd = dateAddExtention; 

function isDate(sDate) {
    var date = new Date(sDate);
    if (date.toString() == "NaN" || date.toString() == "Invalid Date") {
        return false;
    } else {
        return true;
    }
}

//set up end date when user click the radiobutton list
function SetUpEndDate(args){
    var beginDate = convertToObj(arguments[0]);
    if (!isDate(beginDate.value)){
        alert('Please input buget begin date first.');
        convertToObj(arguments[3]).checked = false;
        beginDate.focus();
    }
    var endDate = convertToObj(arguments[2]);
    var curDate = new Date(beginDate.value);
    if (isDate(curDate)){
        var newDate = curDate.dateAdd('m', arguments[1]);
        var newDate = newDate.dateAdd('d', -1);
        endDate.value = (newDate.getMonth()+1) + '/' + newDate.getDate() + '/' + newDate.getFullYear();
    }
}

//set up the end date when begin date is changed
function ResetEndDate(args){
    for (var i=0; i<arguments[3]; i++){
        var rdo = convertToObj(arguments[2] + '_' + i);
        if (rdo.checked){
            SetUpEndDate(arguments[0], rdo.value, arguments[1], arguments[2]);
            break;
        }
    }
    
    for (var i=0; i<arguments[3]; i++){
        var rdo = convertToObj(arguments[4] + '_' + i);
        if (rdo.checked){
            SetUpEndDate(arguments[0], rdo.value, arguments[1], arguments[4]);
            break;
        }
    }
}

//disable enter key
function onKeyPress (e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
		else return true;

	if (keycode == 13) 
		return false;

	return true; 
}

//for the buget amount, don't allow 
function RoundUpCurrency(amount)
{
    result = amount.replace(',', '');
    if (result.indexOf('.')>0){
        cents = 0 + result.substring(result.indexOf('.'));
        if (cents>0.5){
            result = parseInt(result.substring(0, result.indexOf('.'))) + 1; //round up one
            result = CommaFormatted(result);
        }
        else{
            result = result.substring(0, result.indexOf('.'));
        }
    }
    return result;
}
function CommaFormatted(amount)
{
	var delimiter = ","; // replace comma if desired
	var i = parseInt(amount);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	amount = n; 
	amount = minus + amount;
	return amount;
}
// end of function CommaFormatted()

function isAlphaKey(e) {
   var k;
   document.all ? k = e.keyCode : k = e.which;
   return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
}
function extractAlpha(str) {
   return str.replace(/[^a-z]/gi,"");
}


