﻿//NOT WORK
Date.prototype.toISO = function() {
    var tem, A = this.toUTCArray(), i = 0;
    A[1] += 1;
    while (i++ < 7) {
        tem = A[i];
        if (tem < 10) A[i] = '0' + tem;
    }
    return A.splice(0, 3).join('-') + 'T' + A.join(':');
}

// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {

    // create Date object for current location
    d = new Date();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000 * offset));

    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
    //http://articles.techrepublic.com.com/5100-10878_11-6016329.html
}

function getVNDateByZone(offset) {
//DO NOT WORK ON FIREFOX with UTC
//    //var utcDate = new Date().toISO().replace('-', '/');
//    var thetime = new Date(); //utcDate);
//    var utcDate = new Date();// Date.UTC(thetime);
//    //var offset = thetime.getTimeZoneOffset()
//    utcDate.addHours(ZoneNow); //-8pst
//    return utcDate;

    // create Date object for current location
    d = new Date();
    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000 * offset));
    return nd;
}
Date.prototype.addHours = function(h) {
    this.setTime(this.getTime() + (h * 60 * 60 * 1000));
    return this;
}
Date.prototype.toUTCArray = function() {
    var D = this;
    return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
             D.getUTCMinutes(), D.getUTCSeconds()];
}

Date.prototype.VNDayHourMin = function(nday, nhours, nmins, nsecn) {
    if (nday == 0) nday = "CN";
    if (nday == 1) nday = "T2";
    if (nday == 2) nday = "T3";
    if (nday == 3) nday = "T4";
    if (nday == 4) nday = "T5";
    if (nday == 5) nday = "T6";
    if (nday == 6) nday = "T7";
    var AorP = '';
    if (nhours >= 12) AorP = "PM"; else AorP = "AM";
    if (nhours == 0) nhours = 12;
    if (nhours >= 13) nhours -= 12;
    if (nhours < 10) nhours = "0" + nhours;
    if (nmins < 10) nmins = "0" + nmins;
    if (nsecn < 10) nsecn = "0" + nsecn;
    return String(nday + ',' + nhours + ':' + nmins + ':' + nsecn + '' + AorP);
}
function verifyIPByValue(IPvalue,isAlert) {
    errorString = "";
    theName = "IPaddress";
    var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
    var ipArray = IPvalue.match(ipPattern);

    if (IPvalue == "0.0.0.0")
        errorString = errorString + theName + ': ' + IPvalue + ' is a special IP address and cannot be used here.';
    else if (IPvalue == "255.255.255.255")
        errorString = errorString + theName + ': ' + IPvalue + ' is a special IP address and cannot be used here.';
    if (ipArray == null)
        errorString = errorString + theName + ': ' + IPvalue + ' is not a valid IP address.';
    else {
        for (i = 0; i < 4; i++) {
            thisSegment = ipArray[i];
            if (thisSegment > 255) {
                errorString = errorString + theName + ': ' + IPvalue + ' is not a valid IP address.';
                i = 4;
            }
            if ((i == 0) && (thisSegment > 255)) {
                errorString = errorString + theName + ': ' + IPvalue + ' is a special IP address and cannot be used here.';
                i = 4;
            }
        }
    }
    if (errorString == "") { return true; }
    if(isAlert) alert(errorString);
    return false;

}
function verifyIPOrDomain(idIPDomain) {
    var IPvalue = document.getElementById(idIPDomain).value;
    if(IsNumericAndDot(IPvalue)) 
        return verifyIPByValue(IPvalue, true);
    return true;    
}
function verifyIP(idIP) {
    var IPvalue = document.getElementById(idIP).value;
    return verifyIPByValue(IPvalue,true);
}
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
function GetRounder(rateFix) {
    // Convert the number to a string
    var value_string = rateFix.toString();
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".");
    var totalZero=0;
    if(decimal_location!=-1){
        var decimal_part_length = value_string.length - decimal_location - 1;
        
        for (var counter = decimal_location+1; counter <= value_string.length; counter++) 
            if (value_string.charAt(counter)=='0') {
                totalZero++;
            }else break;
    }
    return totalZero+2;// 0.00345678 -> rounder=0.0034, 0.023456->rounder=0.023 
}
function IncreasePercent(objectRate,id4,id10) {
    var txt7=document.getElementById(id7);
    var txt12=document.getElementById(id12);
    var rate7=objectRate.value*4/100+objectRate.value*1;
    var rate12=objectRate.value*10/100+objectRate.value*1;
    txt7.value=roundNumber(rate7,GetRounder(rate7));
    txt12.value=roundNumber(rate12,GetRounder(rate12));
} 
function DecreasePercent(objectRate,id7,id4) {
    var txt7=document.getElementById(id7);
    var txt4=document.getElementById(id4);
    var rate7=objectRate.value*1 - objectRate.value*7/100;
    var rate4=objectRate.value*1 - objectRate.value*4/100;
    txt7.value=roundNumber(rate7,GetRounder(rate7));
    txt4.value=roundNumber(rate4,GetRounder(rate4));
}
function IsNumericAndDot(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function CheckNumeric(obj){
 
//test regular expression regarding numeric format
if (!(obj.value).match(/^\d+(\.\d*)?$/)){
    obj.value= obj.value.replace(/[^0-9.]/g,'');
    return false;
  }
  else{
  	var strEnteredText;
  	strEnteredText=obj.value;
 
  	if(strEnteredText.indexOf('.')!=-1){
  		if((strEnteredText.split("."))[1].length>6){
			obj.value=strEnteredText.substring(0,strEnteredText.length-1);
		}
  	}
  	return true;
  }
}
function HasCheck2(idCB,idCB2,msg){
        var hasCheck1=false;
        var chkArray=document.getElementsByTagName("INPUT");
        for(var i=0;i<chkArray.length;i++){
            var obj=chkArray[i];
            if(obj.id.indexOf(idCB)>=0 || obj.id.indexOf(idCB2)>=0)
                if(obj.checked==true){
                    hasCheck1=true;
                    //break;
                }
        }
        if(!hasCheck1)
            alert(msg);
        return hasCheck1;
    }

function HasCheck(idCB,msg){
        var hasCheck1=false;
        var chkArray=document.getElementsByTagName("INPUT");
        for(var i=0;i<chkArray.length;i++){
            var obj=chkArray[i];
            if(obj.id.indexOf(idCB)>=0)
                if(obj.checked==true){
                    hasCheck1=true;
                    //break;
                }
        }
        if(!hasCheck1)
            alert(msg);
        return hasCheck1;
    }
    function HasCheckConfirm(idCB,msg,cfirm){
        var hasCheck1=false;
        var chkArray=document.getElementsByTagName("INPUT");
        for(var i=0;i<chkArray.length;i++){
            var obj=chkArray[i];
            if(obj.id.indexOf(idCB)>=0)
                if(obj.checked==true){
                    hasCheck1=true;
                    //break;
                }
            
        }
        if(!hasCheck1)
            alert(msg);
        else return confirm(cfirm);
        return hasCheck1;
    }
    function IsMatchedFromDDLValue(idDDL,val) {
        var isMatched=false;
        var array=document.getElementsByTagName("SELECT");
        for(var i=0;i<array.length;i++){
            var obj=array[i];
            if(obj.id.indexOf(idDDL)>=0)
                if(obj.options[obj.selectedIndex].value==val){
                    isMatched=true;
                    //break;
                }
            
        }
         return isMatched;
    }
function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function IsNumberRange(object_value, min_value, max_value)
{
    // check minimum
    if (min_value != null)
	{
        if (object_value < min_value)
			return false;
	}
    // check maximum
    if (max_value != null)
	{
		if (object_value > max_value)
			return false;
	}
    //All tests passed, so...
    return true;
}

function RequireDate(checkYear, checkMonth, checkDay)
{
    if (checkYear == 0 || checkMonth == 0 || checkDay == 0)
    {
        return false;            
    }
    return true;  
}

function CheckDay(checkYear, checkMonth, checkDay)
{
	maxDay = 31;
	if (checkMonth == 4 || checkMonth == 6 ||
			checkMonth == 9 || checkMonth == 11)
		maxDay = 30;
	else
	if (checkMonth == 2)
	{
		if (checkYear % 4 > 0)
			maxDay =28;
		else
		if (checkYear % 100 == 0 && checkYear % 400 > 0)
			maxDay = 28;
		else
			maxDay = 29;
	}
	return IsNumberRange(checkDay, 1, maxDay); //check day
}

//Only allow to enter number
function OnlyAllowNumber(e)
{
    e = e || window.event;
    ch = e.which || e.keyCode;
    if( ch != null) {
        if( (ch >= 48 && ch <= 57)
        || (ch >= 96  && ch <= 105)
        || ch == 0 || ch == 8
        || ch == 13 || ch == 9   || ch == 46
        || ch == 109 || ch == 190 || ch == 32 )  {return true;}
    }
    return false;//        ||  (ch >= 37 && ch <= 40) 
}
function getKeyCode(e)
{
     if (window.event)
        return window.event.keyCode;
     else if (e)
        return e.which;
     else
        return null;
}
function NumericOnly(event)
      {
       
       key = getKeyCode(event);
       if (key <48 || key >57)
          return false;
       return true;
      }
      
function keyRestrict(e, validchars) {
 var key='', keychar='';
 key = getKeyCode(e);
 if (key == null) return true;
 keychar = String.fromCharCode(key);
 keychar = keychar.toLowerCase();
 validchars = validchars.toLowerCase();
 if (validchars.indexOf(keychar) != -1)
  return true;
 if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
  return true;
 return false;
}
function OnlyAllowNumberComma(e)
{
    e = e || window.event;
    ch = e.which || e.keyCode;
    if( ch != null) {
        if( (ch >= 48 && ch <= 57)
        || (ch >= 96  && ch <= 105)
        || ch == 0 || ch == 8
        || ch == 13 || ch == 9   || ch == 46
        || ch == 109 || ch == 190 || ch == 32 )  {return true;}
    }
    return false;//        ||  (ch >= 37 && ch <= 40) 
}
function MaxLength(selObject,maxlength)
{
	if(selObject.value.length>=maxlength)
	{
		selObject.value=selObject.value.slice(0,maxlength);
		return false;
	}
}

//set the state of all item checkboxes is 'checked'
function ChangeCheckAll(objSource){
	var form = document.forms[0];
	try
	{
	    for(i=0;i<form.length;i++)	
	    {   
		    if(form[i].id.indexOf("chkItem")!=-1 && form[i].disabled==false) {
			    form[i].checked=objSource.checked;
			    setSelect("row"+form[i].value,objSource.checked)
			}
	    }
    }
    catch(er){alert(er.message)}	
}
//update the state of ALL checkbox by ITEM checkbox
function CheckItemClick(chkAllItemName, chkItemName)
{
    var form = document.forms[0];
    var chkAllItem = document.getElementById(chkAllItemName);
    if (chkAllItem == null)return;
    var isCheckAll = true;
    for(i=0;i<form.length;i++)	
    {   
	    if(form[i].id.indexOf(chkItemName)!=-1 && form[i].disabled==false && form[i].checked==false)
	        isCheckAll = false;
    }
    chkAllItem.checked = isCheckAll;
}

//return true if there is at least a checkbox has been checked
function RadioOneCheckedColumeGV(idGridView,groupName,object)
    {
    //ctl00_ContentPlaceHolder1_VendorTerminationData1_gvTechPrefixes_ctl02_rbDefault
        var form = document.forms[0];
        var state=object.checked;
        for(i=0;i<form.length;i++)
        {
            if(form[i].id.indexOf(idGridView)!=-1 && form[i].id.indexOf(groupName)!=-1 && form[i].id!=object.id){
                form[i].checked=!state;
            }
        }
    }

function HasChecked()
    {
        var form = document.forms[0];
        var hasChecked = false;
        for(i=0;i<form.length;i++)
        {
            if(form[i].id.indexOf("chkItem")!=-1 && form[i].checked==true){
                hasChecked = true;
                break;
            }
        }
        return hasChecked;
    }
    function HasCheckedByIndexStr(str,msg)
    {
        var form = document.forms[0];
        var hasChecked = false;
        for(i=0;i<form.length;i++)
        {
            if(form[i].id.indexOf(str)!=-1 && form[i].checked==true){
                hasChecked = true;
                break;
            }
        }
        if(!hasChecked)
            alert(msg);
        return hasChecked;
    }
 //helper function for gridview checkbox, before doing an action, if not any checkbox checked then appear alert message
function CheckCheckBoxBeforeDoingAction(msgNoSelect){
    var hasChecked=false;
    for(var i=0;i<CheckBoxIDs.length;i++){
        var cb=document.getElementById(CheckBoxIDs[i]);
        if (cb.checked){
            hasChecked=true;
            break;
        }
    }
    
    if (!hasChecked){
        alert(msgNoSelect);
        return false;
    }
    return true;
}
//
function AssignPrefixOfDropdownToTextBox(ddlPrefixId, txtPrefixId)
{
    var txtPrefixControl = document.getElementById(txtPrefixId);
    var ddlPrefixControl = document.getElementById(ddlPrefixId);
    
    var index1=ddlPrefixControl.options[ddlPrefixControl.selectedIndex].text.indexOf('(');
    var index2=ddlPrefixControl.options[ddlPrefixControl.selectedIndex].text.indexOf(')');
    txtPrefixControl.value=ddlPrefixControl.options[ddlPrefixControl.selectedIndex].text.substring(index1+1,index2);
    
    
}
function AssignListOptionValuesToHidden(hiddenControlId, selectControlId)
{
    var selectControl = document.getElementById(selectControlId);
    var hiddenControl = document.getElementById(hiddenControlId);
	hiddenControl.value = "";

	if (selectControl.length > 0)
	{
    	var optionValues = new Array();    	
	    for(var i=0; i < selectControl.length; i++)
	    {
		    optionValues[optionValues.length] =selectControl.options[i].value;	
        }
        hiddenControl.value = optionValues.join("|");
    }

}
function AssignCheckBoxGroupValuesToHidden(hiddenControlId, cbGroupName)
{
    var hiddenControl = document.getElementById(hiddenControlId);
	hiddenControl.value = "";
	var form = document.forms[0];
    var optionValues = new Array();    	
    for(i=0;i<form.length;i++)
    {
        if(form[i].id.indexOf(cbGroupName)!=-1 && form[i].checked==true){
            optionValues[optionValues.length] =form[i].value;	
        }
    }
    hiddenControl.value = optionValues.join("|");
}
function AssignCheckBoxGroupValuesToHidden(hiddenControlId, cbGroupName,cbGroupName2)
{
    var hiddenControl = document.getElementById(hiddenControlId);
	hiddenControl.value = "";
	var form = document.forms[0];
    var optionValues = new Array();    	
    for(i=0;i<form.length;i++)
    {
        if((form[i].id.indexOf(cbGroupName)!=-1 || form[i].id.indexOf(cbGroupName2)!=-1) && form[i].checked==true){
            optionValues[optionValues.length] =form[i].value;	
        }
    }
    hiddenControl.value = optionValues.join("|");
}
//
function AssignListOptionTextsToHidden(hiddenControlId, selectControlId)
{
    var selectControl = document.getElementById(selectControlId);
    var hiddenControl = document.getElementById(hiddenControlId);
	hiddenControl.value = "";

	if (selectControl.length > 0)
	{
    	var optionValues = new Array();    	
	    for(var i=0; i < selectControl.length; i++)
	    {
		    optionValues[optionValues.length] =selectControl.options[i].text;	
        }
        hiddenControl.value = optionValues.join("|");
    }

}

//--Checkbox helper in gridview
function ChangeHeaderAsNeeded(idrow,isChecked)
{
    setSelect(idrow,isChecked);
    // Whenever a checkbox in the GridView is toggled, we need to
    // check the Header checkbox if ALL of the GridView checkboxes are
    // checked, and uncheck it otherwise
    if (CheckBoxIDs != null)
    {
        // check to see if all other checkboxes are checked
        for (var i = 1; i < CheckBoxIDs.length; i++)
        {
            var cb = document.getElementById(CheckBoxIDs[i]);
            if (!cb.checked)
            {
                // Whoops, there is an unchecked checkbox, make sure
                // that the header checkbox is unchecked
                ChangeCheckBoxState(CheckBoxIDs[0], false);
                return;
            }
        }
        
        // If we reach here, ALL GridView checkboxes are checked
        ChangeCheckBoxState(CheckBoxIDs[0], true);
    }
    
}
function CheckBeforeDeleting(){
    if (CheckBoxIDs!=null){
        var checked=false;
        for (var i=1;i<CheckBoxIDs.length;i++){
            var cb=document.getElementById(CheckBoxIDs[i]);
            if (cb.checked){
                checked=true;
                break;
            }
        }
        if (checked){
            return confirm('Are you sure you want to delete the selected job(s) from your applied jobs list');
        }else{
            alert('Please select a job to delete');
            return false;
        }
        
    }
}
function CheckCheckBoxBeforeDeleting(confirmMsg,alertMsg){
    if (CheckBoxIDs!=null){
        var checked=false;
        for (var i=1;i<CheckBoxIDs.length;i++){
            var cb=document.getElementById(CheckBoxIDs[i]);
            if (cb.checked){
                checked=true;
                break;
            }
        }
        if (checked){
            return confirm(confirmMsg);
        }else{
            alert(alertMsg);
            return false;
        }
        
    }
}
 function ProtectAZDomain(contactName,objHP,isMSN) {
    var mt=isMSN?'msnim:chat?contact=':'mailto:';
    var domain='azdirectroute'+'.'+'com';
    var e=mt+contactName+'@'+domain;
    objHP.href=e;
}
function ProtectCalling84Domain(contactName, objHP, isMSN) {
    var mt = isMSN ? 'msnim:chat?contact=' : 'mailto:';
    var domain = 'calling84' + '.' + 'com';
    var e = mt + contactName + '@' + domain;
    objHP.href = e;
}
 function ChangeCheckBoxState(id, checkState)
   {
      var cb = document.getElementById(id);
      if (cb != null)
         cb.checked = checkState;
   }

function ChangeAllCheckBoxStates(tableid,checkState)
{
  // Toggles through all of the checkboxes defined in the CheckBoxIDs array
  // and updates their value to the checkState input parameter
  if (CheckBoxIDs != null)
  {
     for (var i = 0; i < CheckBoxIDs.length; i++)
        ChangeCheckBoxState(CheckBoxIDs[i], checkState);
     for (var k=0; k<RowIDs.length;k++){
        setSelect(RowIDs[k],checkState);
     }
  }
}
function SelectAllItems(id,idGridView)
        {
            //get reference of GridView control
            var grid = document.getElementById(idGridView);
            //variable to contain the cell of the grid
            var cell;
            
            if (grid.rows.length > 0)
            {
                //loop starts from 1. rows[0] points to the header.
                for (i=1; i<grid.rows.length; i++)
                {
                    //get the reference of first column
                    cell = grid.rows[i].cells[0];
                    
                    //loop according to the number of childNodes in the cell
                    for (j=0; j<cell.childNodes.length; j++)
                    {           
                        //if childNode type is CheckBox                 
                        if (cell.childNodes[j].type =="checkbox")
                        {
                        //assign the status of the Select All checkbox to the cell checkbox within the grid
                            cell.childNodes[j].checked = document.getElementById(id).checked;
                         
                        }
                    }
                }
            }
           
        }