function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function focusOnID(id){
  try{document.getElementById(id).focus();}catch(err){}
}

function setRadioByValue(name,val){
var el=document.getElementsByName(name);
for(var j=0; j<el.length; j++) {el[j].checked=(el[j].value==val);}
}

function getRadioValue(name){
var el=document.getElementsByName(name);
for(var j=0; j<el.length; j++) {if(el[j].checked) return el[j].value;}
return null;
}

function IsValidDate(str){
  if (str.length!=10){return false;}
  else { 
    var Mn = str.substring(3,5);
    var Day = str.substring(0,2);
    var Yr = str.substring(6,10);
    var DateVal = Mn + "/" + Day + "/" + Yr;
    var dt = new Date(DateVal);
    return ( dt.getDate()==parseInt(Day,10) && dt.getMonth()==parseInt(Mn,10)-1 && dt.getFullYear()==parseInt(Yr,10) );
  }
}

function IsValidTime24(str){
  if (str.length!=4){return false;}
  else { 
    var HH = str.substring(0,2);
    var mm = str.substring(2);
    return ( parseInt(HH,10)<=23 && parseInt(mm,10)<=59 );
  }
}

function checkAll(putCheck,checkboxNameContains,parentName) {
var e=(parentName)?document.getElementById(parentName):document;
if(e){
var el=e.getElementsByTagName('input');
for(var j=0; j<el.length; j++) {if (el[j].id.indexOf(checkboxNameContains)!=-1 && !el[j].disabled && el[j].checked!=putCheck) el[j].checked=putCheck;}
}}

function whetherAllCheck(chkAllName,checkboxNameContains,parentName) {
var c=document.getElementById(chkAllName);
var e=(parentName)?document.getElementById(parentName):document;
if(c && e){
var el=e.getElementsByTagName('input');
if(c.checked){
for(var j=0; j<el.length; j++) {if (el[j].id.indexOf(checkboxNameContains)!=-1 && !el[j].disabled && !el[j].checked) {c.checked=false; break;}}
}else{
var b=true;
for(var j=0; j<el.length; j++) {if (el[j].id.indexOf(checkboxNameContains)!=-1 && !el[j].disabled && !el[j].checked) {b=false; break;}}
if(b) {c.checked=true;}
}}}

function FullScreen(){
  window.scroll="false";
  this.moveTo(0,0);
  resizeTo(screen.availWidth,screen.availHeight);
}
        
function MM_openBrWindow(theURL,winName,features) { //v2.0
  var c = window.open(theURL,winName,features);
  try{c.focus();}catch(err){}
}
	    
	    function CloseWindow(){
	        if (window.opener && !window.opener.closed) window.opener.focus();
	        if(window.parent && window.parent!=self){//iframe
	            if(confirm('Are you sure to close this window?')){window.parent.close();}
	        }else{
	            window.close();
	        }
	        return false;
	    }
	    
	    function onFeforeUnloadAction(){
	    if(window.event)
            if((window.event.clientX<0) || (window.event.clientY<0))
                if (window.opener && !window.opener.closed) window.opener.focus();
        }
        window.onbeforeunload = onFeforeUnloadAction; 

        //this stops screen flicker in IE6 SP1
        try {
          document.execCommand("BackgroundImageCache", false, true);
        } catch(err) {}

//use within onKeyPress event
//return true if targetKeyID is being hit
function KeyPressMatch(e,targetKeyID,OnKeyPress){
   if(!e) e = window.event;

   var KeyID = (e.which) ? e.which : e.keyCode;

   if(KeyID == targetKeyID){
      if(OnKeyPress){setTimeout(function(){OnKeyPress();},10);}
      return true;
   }else{
      return false;
   }
}
//function KeyPressCheck(e,targetKeyID){
//   var KeyID = (window.event) ? event.keyCode : e.keyCode;
//   return (KeyID == targetKeyID)
//}

function detectOpenerWinClosing(){
    //if(!window.opener || window.opener.closed) window.close(); else setTimeout("detectOpenerWinClosing()",200);
}

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresearch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================
function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	//document.URLForm.F2.value = encoded;
	return encoded;
}

function URLDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   //var encoded = document.URLForm.F2.value;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   //document.URLForm.F1.value = plaintext;
   return plaintext;
}
// ====================================================================

// http://www.devx.com/tips/Tip/15222 =================================
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}
// ====================================================================

//http://www.web-source.net/web_development/currency_formatting.htm
function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
// end of function CurrencyFormatted()

function CommaFormatted(amount)
{
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	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);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}
// end of function CommaFormatted()

function getIFrameDoc(iframe){
    var IFrameObj=document.getElementById(iframe);
    if(IFrameObj){
      if (IFrameObj.contentDocument) {
        // For NS6
        return IFrameObj.contentDocument; 
      } else if (IFrameObj.contentWindow) {
        // For IE5.5 and IE6
        return IFrameObj.contentWindow.document;
      } else if (IFrameObj.document) {
        // For IE5
        return IFrameObj.document;
      }
        
    }
    
    return false;
}

//http://www.webtips.co.in/javascript/copy-to-clipboard-with-javascript-on-mozilla-firefox-and-ie.aspx
function copy_to_clipboard(text)
{
    if(window.clipboardData)
    {
	window.clipboardData.setData('text',text);
    }
    else
    {
        var clipboarddiv=document.getElementById('divclipboardswf');
	if(clipboarddiv==null)
	{
	   clipboarddiv=document.createElement('div');
           clipboarddiv.setAttribute("name", "divclipboardswf");
	   clipboarddiv.setAttribute("id", "divclipboardswf");
	   document.body.appendChild(clipboarddiv);
	}
        clipboarddiv.innerHTML='<embed src="../Images/clipboard.swf" FlashVars="clipboard='+
encodeURIComponent(text)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    }
    //alert(text+'\nhas been copied to your clipboard.');
    return false;
}

try{

//http://allinthehead.com/retro/338/supersleight-jquery-plugin
jQuery.fn.supersleight=function(settings){settings=jQuery.extend({imgs:true,backgrounds:true,shim:'x.gif',apply_positioning:true},settings);return this.each(function(){if(jQuery.browser.msie&&parseInt(jQuery.browser.version,10)<7&&parseInt(jQuery.browser.version,10)>4){jQuery(this).find('*').andSelf().each(function(i,obj){var self=jQuery(obj);if(settings.backgrounds&&self.css('background-image').match(/\.png/i)!==null){var bg=self.css('background-image');var src=bg.substring(5,bg.length-2);var mode=(self.css('background-repeat')=='no-repeat'?'crop':'scale');var styles={'filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='"+mode+"')",'background-image':'url('+settings.shim+')'};self.css(styles)};if(settings.imgs&&self.is('img[src$=png]')){var styles={'width':self.width()+'px','height':self.height()+'px','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+self.attr('src')+"', sizingMethod='scale')"};self.css(styles).attr('src',settings.shim)};if(settings.apply_positioning&&self.is('a, input')&&(self.css('position')===''||self.css('position')=='static')){self.css('position','relative')}})}})};

$(document).ready(function()
{
    if(location.href.indexOf('/Content')<0 && location.href.indexOf('/Page_')<0){
        try{
	        $('body').supersleight({shim: '../images/spacer.gif'});
        }catch(err){}
    }
});

}catch(err){}

function expandcontent(cid){
try{
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
}catch(err){}
}
        function PrintThisPage(title){
           var sOption="width=1000,height=600,toolbar=yes,menubar=1,location=no,status=no,scrollbars=yes,resizable=yes,top=0,left=0"; 

           var sWinHTML = document.getElementById('ForPrint').innerHTML; 
           
           var winprint=window.open("","",sOption); 
           winprint.document.open(); 
           winprint.document.write('<html><body onLoad="self.print()">'); 
           winprint.document.write('<title>'); 
           winprint.document.write(title);
           winprint.document.write('</title>'); 
           
           //Scripting
            winprint.document.write('<script> function click(e) {     var targ;if (!e) var e = window.event;targ = (e.target) ? e.target : e.srcElement;if (targ.nodeType == 3) targ = targ.parentNode;if (targ.id.toLowerCase().indexOf("btn") >= 0 && !targ.disabled) { alert("No clicking!")}}document.onmousedown=click<\/script>'); 
           
           winprint.document.write('<style type="text/css">.printHide {display:none;} .row0 {background-color:Black;border-bottom-style:solid;font-weight:bold;color:White; } table{border-width:2; border-style:solid;  border-color:Black;}</style>'); 
           winprint.document.write('<span style="font-size:large">');
           winprint.document.write(title);
           winprint.document.write('</span>');  
           winprint.document.write('<br/><br/><form id="form1">');
           winprint.document.write(sWinHTML);          
           winprint.document.write('</form></body>');
           
           winprint.document.write('</html>'); 
           winprint.document.close(); 
           winprint.focus(); 
        }
        
        var winprint2;
        function PrintLoading(s,r,action,sOption){
            var title = '';
            if (action='1') title = 'Exporting Data'; else title = 'Preparing Data';
            
                if (!winprint2 || winprint2.closed){
                    winprint2=window.open('about:blank','Print',sOption);
                }
                with(winprint2.document){
                    open();
                    writeln('<title>' + title + '</'+'title>');
                    writeln('<body>');
                        writeln('<span id="lblTitle" style="font-size:X-Large;">' + title + '</span><br />');
                        writeln('<img src="../Images/hourglass_16.png" title="Processing data" /> ');
                        write('<span id="lblInfo" style="color:#8080FF;font-weight:bold;">Please wait as we process your page');
                        if (r) write(' of '+r+' records');
                        writeln('...</span>');
                    writeln('</body>');
                    close();
                }
                winprint2.focus();
                
                if (s) {
                    if (action='1'){
                     window.open(s,'Excel',sOption) ;
                     winprint2.close();
                    }
                    
                    else{
                     winprint2.location = s ;
                    }
                }
        }

        function Select(Select){
            for (var n=0; n < document.forms[0].length; n++)
                if (document.forms[0].elements[n].type=='checkbox'){
                        document.forms[0].elements[n].checked=Select;
                }
            return false; 
        }
        
        function CheckIfSelected(){
            for (var n=0; n < document.forms[0].length; n++)
                if (document.forms[0].elements[n].type=='checkbox')
                    if (document.forms[0].elements[n].checked == true)
                        return confirmDelete(); 


            alert('Please select user in order to proceed.');
            return false;

        }
        
        function confirmDelete(e) {    
            var targ;
            if (!e) 
                var e = window.event;
            targ = (e.target) ? e.target : e.srcElement;
            if (targ.nodeType == 3) 
                targ = targ.parentNode;
            if (targ.id.toLowerCase().indexOf("delete") >= 0 && !targ.disabled) {        
                return confirm("Are you sure you want to delete selected users?");
            }
            if (targ.id.toLowerCase().indexOf("archive") >= 0 && !targ.disabled) {        
                return confirm("Are you sure you want to archive selected users?");
            }
            return true
        }
        
function OpenDetails(append){
    MM_openBrWindow('../hrm/staff_detail.aspx'+ append, 'StaffDetail', 'width=800,height=500, scrollbars=1,resizable=0');
}
function OpenRights(append){
    MM_openBrWindow('../peoplemanagement/people_groupaccessrights.aspx?editKey='+ append, 'GroupAccessRights', 'width=800,height=500, scrollbars=1,resizable=0');
}
function OpenPeopleDetails(append){
    MM_openBrWindow('../hrm/staff_detail.aspx?editKey='+ append, 'StaffDetail', 'width=800,height=500, scrollbars=1,resizable=0');
}
function enterPopItemDesc(id,setid){
    MM_openBrWindow('../Accounts/itemdesc.aspx?id='+id+'&setid='+setid,'','width=600,height=500,toolbar=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=0,left=0');
}
function enterPopEditVoidReason(append){
    MM_openBrWindow('../Generic/EditVoidReason.aspx'+append,'','width=600,height=500,toolbar=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=0,left=0');
}
function enterPopEditReturnReason(append){
    MM_openBrWindow('../Approval_AddOn/EditReturnReason.aspx'+append,'','width=600,height=500,toolbar=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=0,left=0');
}
function enterPopEditRejectReason(append){
    MM_openBrWindow('../HRM/EditRejectReason.aspx'+append,'','width=600,height=500,toolbar=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=0,left=0');
}
function OpenINVPayment(append){
    MM_openBrWindow('../accounts/invpayment_list.aspx'+ append, 'Payment', 'width=800,height=600,scrollbars=1,resizable=1');
}
function OpenINVReceiptDetails(append){
    MM_openBrWindow('../accounts/invreceipt_detail.aspx'+ append, '', 'width=800,height=600,scrollbars=1');
}
function OpenInvoiceDetails(append){
    MM_openBrWindow('../accounts/myinvoice_detail.aspx'+ append, '', 'width=800,height=600,scrollbars=1');
}
function OpenAccountsPrintable(append){
    MM_openBrWindow('../accounts/Accounts_Printable.aspx'+ append, '', 'width=800,height=600,toolbar=1,scrollbars=1,resizable=1');
}
function OpenPageContentList(append){
    MM_openBrWindow('../PageContent/PageContent_List.aspx?pageId='+ append, 'PageContentList', 'width=1010,height=600, resizable=1,scrollbars=1');
}
function OpenPageContentAccessList(append){
    MM_openBrWindow('../PageContent/PageContent_Access_List.aspx?pageId='+ append, 'PageContentAccessList', 'width=1010,height=600, resizable=1,scrollbars=1');
}

function OpenChat(id){
    window.open('../Includes/OnlineUserChat.aspx?id='+id, '', 'width=550,height=600,toolbar=no,menubar=no,location=no,status=no,scrollbars=no,resizable=0');
}

function OpenRecordChat(id,PageID,TableSourceID,ReferenceID){
    window.open('../Includes/OnlineUserChat.aspx?id='+id+'&PageID='+PageID+'&TableSourceID='+TableSourceID+'&ReferenceID='+ReferenceID, '', 'width=550,height=600,toolbar=no,menubar=no,location=no,status=no,scrollbars=no,resizable=0');
}

function enterPopOnlineBuddyWindow(){
    MM_openBrWindow('../Includes/OnlineBuddyWindow.aspx', 'OnlineBuddyWindow', 'width=720,height=600,toolbar=no,menubar=no,location=no,status=no,scrollbars=no,resizable=no');
}

function OpenConfigDetails(url){
    MM_openBrWindow(url, '', 'width=800,height=600,scrollbars=1');
}

function enterPopEditPageHelp(append){
    MM_openBrWindow('../Generic/EditPageHelp.aspx?pageId='+append,'','width=920,height=700,scrollbars=1');
}

function enterPopViewPageHelp(append){
    MM_openBrWindow('../Generic/ViewPageHelp.aspx?pageId='+append,'','width=800,height=600,scrollbars=1');
}

function PlaySound(url) {
var MSIE=navigator.userAgent.indexOf("MSIE");
//var NETS=navigator.userAgent.indexOf("Netscape");
//var OPER=navigator.userAgent.indexOf("Opera");
//if((MSIE>-1) || (OPER>-1)) {
if((MSIE>-1)) {
  document.all.sound.src = url;
} else {
//  document.getElementById("soundspan").innerHTML=
//    "<embed src='"+url+"' hidden=true autostart=true loop=false>";
document.getElementById("soundspan").innerHTML=
'<object type="audio/x-mpeg" data="'+url+'" width="0" height="0" autoplay="true"></object>';
}
}


document.writeln('<bgsound id=sound>');
//document.writeln('<span id=soundspan style="visibility:hidden;float:right;width:1px;height:1px;"></span>');
document.writeln('<span id=soundspan style="position:absolute;top:0px;left:0px;width:1px;height:1px;visibility:hidden;overflow:hidden;"></span>');
