
function $(id){return document.getElementById(id);}

var idNum = 0;
function Set$(o) {
    if (!o.id || o.id == null || o.id == '') o.id = 'o' + idNum; idNum++;
}

function EventFire(el, etype){
    if (typeof el.onclick == "function") {
    el.onclick.apply(el);
    }
    else if (el.fireEvent) {
      el.fireEvent('on' + etype);
    } else {
      var evObj = document.createEvent('Events');
      evObj.initEvent(etype, true, false);
      el.dispatchEvent(evObj);
    }
}

function Replace(s, searchText, replaceText)
{
	while(s.indexOf(searchText) != -1)	s = s.replace(searchText, replaceText);   	    
    return s;
}

function FocusOnNextTabIndex(el)
{
    if(el)
    {
        var tabIndex = el.tabIndex;
        var els = document.forms[0].elements;

        //alert('FocusOnNextTabIndex - tabIndex: ' + tabIndex + ' - els.length: ' + els.length + ' - forms[0].action: ' + document.forms[0].action);
        if(tabIndex && document.forms[0].action.indexOf('EdtFldVal.aspx') != -1) 
        {
            /// For Edit-Field-Popup: Just go to the Save button
            var saveBtn = $('ctrSaveArea_lnk');
            if(saveBtn) 
            {
                try{ saveBtn.focus(); }catch(ex){}
                return;  
            }
        }
        else if(els && tabIndex)
        {
            /// We try up to 10 times to try to find the next lowest tabIndex occurrance
            for(var iTry = 0; iTry < 10; iTry++)
            {
                //alert('FocusOnNextTabIndex - tabIndex: ' + tabIndex);

                for(i = 0; i < els.length; i++)
                {
                    //alert('FocusOnNextTabIndex - tabIndex: ' + tabIndex + '\n\n els[i].tagName: ' + els[i].tagName + ' - els[i].offsetWidth: ' + els[i].offsetWidth + ' - els[i].tabIndex: ' + els[i].tabIndex);

                    /// Check ".offsetWidth != 0" because of hidden elements
                    if(els[i] && els[i].offsetWidth && els[i].offsetWidth != 0 && els[i].tabIndex == tabIndex+1)
                    {
                        try{ els[i].focus(); }catch(ex){}
                        return;
                    }
                }

                tabIndex++;
            }

        }
    }
}
// =============================================        Cookie, Querystring         ====================================================
function EraseCookie(name)
{
    var date = new Date();
	date.setTime(date.getTime()+(-1));
	var expires = "; expires="+date.toGMTString();
	document.cookie = name+"="+expires+"; path=/"; 	
}

function UrlNewQs(queryStringName, queryStringValue)
{
    return UrlNewQsEx(window.location.toString(), queryStringName, queryStringValue);
}


/// build a new url with from the current pages with the new querystring added or replaced
function UrlNewQsEx(url, queryStringName, queryStringValue)
{				
	// make all lowercase so that there are no inconsistencies with matching upper and lower case chars
	url = url.toString();//.toLowerCase();
	queryStringName = queryStringName.toString();//.toLowerCase();
	queryStringValue = queryStringValue.toString();//.toLowerCase();
	
	var searchStart = url.indexOf("?" + queryStringName + "=");
	var searchMid = url.indexOf("&" + queryStringName + "=");
	// if the string exists then we need to just replace it
	if(searchStart != -1 || searchMid != -1 )
	{	    
	    var oldValEnd = url.indexOf("&", ((searchStart != -1 ? searchStart : searchMid) + 1));	    
	    // if there is something after the querystring item then we use that as the end point
	    // otherwise we just get the rest of the string
	    var oldVal;
	    if(oldValEnd != -1)	    
	        oldVal = url.substring((searchStart != -1 ? searchStart : searchMid) + (queryStringName.length + 2), oldValEnd);	        	            	    
	    else
	        oldVal = url.substring((searchStart != -1 ? searchStart : searchMid) + (queryStringName.length + 2));	        	            	    	    
	    oldVal = Trim(oldVal);	    	    
	    url = url.replace(((searchStart != -1 ? "?" : "&") + queryStringName + "=" + oldVal), ((searchStart != -1 ? "?" : "&") + queryStringName + "=" + queryStringValue));	        	    
	}
	else // if the querystring item is not in the url then we need to add it	    	 
	     url += (url.indexOf("?") != -1 ? "&" : "?") + queryStringName + "=" + queryStringValue; 
	
	return url;	
}

// for places like querystring where key and value pairs are used
function SetKey(s, key, value, separator)
{
	key += '='; // add this here so that dont have to add it each time
	if(s.indexOf(key) == 0 || s.indexOf(separator + key) != -1)
	{		
		if(s.charAt(0) == separator) s = s.substr(1); // removes the separator if its is the first char 	
		
		// loop through each pair to find the one with the key and set it to the new value
		var arr = s.split(separator);
		for(var i = 0; i < arr.length; i++)
		{
			//alert('i = ' + i + ' arr[i] = ' + arr[i]);
			if(arr[i].indexOf(key) == 0)
			{
				arr[i] = arr[i].substr(0, (arr[i].indexOf('=') +1)) + value;
				break;
			}
		}
		
		s = '';
		for(var i = 0; i < arr.length; i++)
		{
			s += separator + arr[i];
		}
	}
	else
		s += separator + key + value;
	
	return s;
}

function GetKey(s, key, separator)
{	
	if(s.indexOf(key) != -1)
	{
		if(s.charAt(0) == separator) s = s.substr(1); // removes the separator if its is the first char 
		
		var arr = s.split(separator);
		//alert('arr.length = ' + arr.length);
		for(var i = 0; i < arr.length; i++)
		{
			//alert('i = ' + i + ' arr[i] = ' + arr[i]);
			if(arr[i].indexOf(key + '=') == 0)
			{
				var value = arr[i].substr(key.length + 1);
				if(value.charAt((value.length-1)) == '#') value = value.substr(0, value.length-1);
				return value;
			}
		}
	}
	
	return '';
}

// returns the whole querystring but not the question mark so that this can be appended to another querystring or at the end 
function GetQueryString()
{	
	var qs = location.search;
	if(location.hash && location.hash != '') qs += UrlDecodeHash(location.hash);
	if(qs.length > 0) qs = qs.substr(1);
	return qs;
}

function SetQueryStringValue(url, name, value)
{
	//alert(window.search); return false;	
	var qs = '';
	
	if(url.indexOf('?') != - 1) qs = url.substr(url.indexOf('?')+1);
	
	
	return url.substr(0, url.indexOf('?')) + '?' + SetKey(qs, name, value, '&');
}

function GetQueryStringValue(strName)
{	
	return GetKey(GetQueryString(), strName, '&');	
}

function GetFileExtension(fileName)
{
	var dotIdx = fileName.lastIndexOf('.');
	if(dotIdx > 0)
		return fileName.substring((dotIdx+1)).toLowerCase(); // return in lower case for comparison reasons
	else
		return '';
}

// returns an encoded string for use in a qs, need to use this func isntead of just "escape()" because of some special encoding differences between js and asp.net
function UrlEncode(s)
{	
	
//	var sBefore = s;
	s = encodeURIComponent(s);
	//alert('s before encoding = ' + sBefore + '\ns after encoding = ' + s)
	// the 'encodeURIComponent' encodes everything but spaces are encoded as plus signs so have to convert them to the real encoded value		
	while(s.indexOf('+') != -1)
		s = s.replace('+', '%2b');
		
//	while(s.indexOf('&') != -1)
//		s = s.replace('&', '%26');
		
	return s;	
}

// had to create this because of the Reports and how the hash is returned decoded, 
// main thing with this is to make sure that all the '&' symbols are encoded, otherwise the filter breaks
function UrlDecodeHash(s)
{		
	// weird incompatibility encoding issue between .NET an JS (.NET treats the plus sign as a special char)
//	while(s.indexOf('+++') != -1)
//		s = s.replace('+++', '+%2b+');
	//alert('UrlDecodeHash = ' + s);

	while(s.indexOf('+') != -1)
		s = s.replace('+', '%2b');
						
	while(s.indexOf('&amp;') != -1)
		s = s.replace('&amp;', '%26amp%3B');
		
//	while(s.indexOf(' & ') != -1)
//		s = s.replace(' & ', '%20%26%20');
		
	while(s.indexOf('&quot;') != -1)
		s = s.replace('&quot;', '%26quot%3B');
		
	while(s.indexOf('&lt;') != -1)
		s = s.replace('&lt;', '%26lt%3B');
		
	while(s.indexOf('&gt;') != -1)
		s = s.replace('&gt;', '%26gt%3B');
		
	while(s.indexOf(' ') != -1)
		s = s.replace(' ', '%20');
		
	while(s.indexOf('/') != -1)
		s = s.replace('/', '%2F');
	
	while(s.indexOf('\\') != -1)
		s = s.replace('\\', '%5C');	
		
		
	return s;
}
function GetDDLSelectedText(ddlID)
{
	var thisDDL = $(ddlID);
	return thisDDL.options[thisDDL.selectedIndex].text;	
}

function PubFrmLogin()
{
	var entTpID = GetControlValue('hidEntTpID');
	window.location = '/SAM/Misc/Ent_Login_Edt.aspx?enttpid=' + entTpID + '&frmurl=' + UrlEncode(window.location);	
}

function PubFrmShow()
{
	var cntrFrm = GetControlByMyID('div', 'cntrFrm');
	var cntrQuestion = GetControlByMyID('div', 'cntrQuestion');
	
	//alert('cntrFrm.id = ' + cntrFrm.id); return;
	cntrFrm.style.display = '';
	cntrQuestion.style.display = 'none';
}

// =============================================        String              ====================================================



function ArrayAddItem(arr, name)
{
	if(ArrayIndexOf(arr, name) == -1) arr[arr.length] = name;
}
function ArrayDeleteElmenet(arr, name)
{        
    var index = ArrayIndexOf(arr, name);
    if(index != -1) arr.splice(index, 1);        
    return arr;
}       
function ArrayIndexOf(arr, name)
{        
    if(IsDefined(arr) && IsDefined(name))    
        for(var i = 0; i < arr.length; i++)
            if(arr[i] == name) return i;
    return -1;
}

function IsArrayContains(arr, name)
{        
    if(IsDefined(arr) && IsDefined(name))    
        for(var i = 0; i < arr.length; i++)
            if(arr[i] == name) return true;
    return false;
}
function Trim(s)
{ 
	if(s && s != null)
	{
		s = s.replace(/\x00/g,"");
		return s.replace(/^\s+/,"").replace(/\s+$/,"");
	}
	else
		return '';
}
// =============================================        Window/Doc      ========================================================
function Refresh()
{
    location.reload();
}

// =============================================        Control         ========================================================
function GetObjectID(obj)
{
	if(obj && obj != null)
	{
		if(!obj.id || obj.id == '') obj.id = obj.uniqueID;
		return obj.id;
    }
	else
		return '';
}

/* used */
function GetElementsByTagNAttr(tagName, attrName, attrValue) 
{
    var els = document.getElementsByTagName(tagName);
	if(els.length == 0) return null;
	var arr = new Array();
	for(var i = 0; i < els.length; i++) 
		if(els[i].getAttribute(attrName) == attrValue) arr[arr.length] = els[i];	    
		//if(els[i].attributes && els[i].attributes.getNamedItem(attrName) && els[i].attributes.getNamedItem(attrName).value == attrValue) arr.push(els[i]);	    
	return arr;
}

/* used */
function GetControlsElementsByTagNAttr(control, tagName, attrName, attrValue) 
{    
    var els = control.getElementsByTagName(tagName);
	if(els.length == 0) return null;
	var arr = new Array();
	for(var i = 0; i < els.length; i++) 
		if(els[i].attributes && els[i].attributes.getNamedItem(attrName) && els[i].attributes.getNamedItem(attrName).value == attrValue) arr.push(els[i]);	    
	return arr;
}

function GetElementsByTagN2Attr(tagName, attrName, attrValue, attr2Name, attr2Value) 
{
    var els = document.getElementsByTagName(tagName);
	if(els.length == 0) return null;
	var arr = new Array();
	for(var i = 0; i < els.length; i++) 
		if(els[i].attributes && els[i].attributes.getNamedItem(attrName) && els[i].attributes.getNamedItem(attrName).value == attrValue && els[i].attributes.getNamedItem(attr2Name) && els[i].attributes.getNamedItem(attr2Name).value == attr2Value) arr.push(els[i]);	    
	return arr;
}


function IsDefined(el)
{
    return typeof(el) != 'undefined';
}
function IsDefinedNNotNull(el)
{
    return typeof(el) != 'undefined' && el != null;      
}



function GetControlAttributeByControlID(controlID, attrName)
{
	var thisControl = $(controlID);
	if(thisControl && thisControl.attributes && thisControl.attributes.getNamedItem(attrName)) return thisControl.attributes.getNamedItem(attrName).value;
	else return '';
}
function GetControlAttribute(thisControl, attrName)
{	
	if(thisControl && thisControl.attributes && thisControl.attributes.getNamedItem(attrName)) return thisControl.attributes.getNamedItem(attrName).value;
	else return '';
}
function MyPostBack()
{
	var divSv = $('divSv');
	if(divSv && divSv != null)
	{		
		divSv.style.height = divSv.offsetHeight + 'px';
		divSv.innerHTML = '<span class="lblLg">Submitting...</span><img src="/SAM/Img/LoadingBig.gif" alt="" />';
		
		var errCell = $('errCell');
		if(errCell && errCell != null) errCell.innerHTML = '&nbsp;';
	}
	
	$('hidIsPB').value = '1';	
	Submit();
}
function Submit()
{
    hidIsPB = $('hidIsPB');    
    if(hidIsPB && hidIsPB != null) hidIsPB.value = '1';
	if(document.forms['frm'] != null)
		document.forms['frm'].submit();
	else
		document.forms[0].submit();
}
function ShowRptrItems(val, tagName, myid, trLblID, myid2)
{
	var controls = GetElementsByTagNAttr(tagName, 'myid', myid);	
	var controls2;
	if(myid2) controls2 = GetElementsByTagNAttr(tagName, 'myid', myid2);	
	val = Number(val);
	if(!IsDefined(trLblID) || trLblID == null) trLblID = myid;
	var trlbl = GetControlByMyID('tr', trLblID + '_trlbl');
		
	/// this has to stay exactly this way, bc the trLbl is sometimes not there
	if(trlbl && trlbl.style) trlbl.style.display = (val == 0 ? 'none' : '');
	
	for(var i = 0; i < val; i++)
	{ 
	    if(controls[i] && controls[i].style) controls[i].style.display = ''; 
	    if(myid2 && controls2 && controls2[i] && controls2[i].style) controls2[i].style.display = ''; 
	}	
	
	for(var i = val; i < controls.length; i++) 
	{ 
	    if(controls[i] && controls[i].style) controls[i].style.display = 'none'; 
	    if(myid2 && controls2 && controls2[i] && controls2[i].style) controls2[i].style.display = 'none'; 
	}
	
	
}

/// When the control is inside a user control then we use to use the myid to reference it
function GetCtrlID(id)
{        
	var control = GetControlByMyID('input', id);		
	
	// second try for select
	if(control == null) control = GetControlByMyID('select', id);
	
	if(control == null) control = GetControlByMyID('textarea', id);
		
	// and lastly 'div' for those controls which have multiple parts
	if(control == null) control = GetControlByMyID('div', id);
	//if(control == null) controls = GetElementsByTagNAttr('div', id);
	
	if(control != null)
	    return control.id;
	else
	    return '';
}
function GetRepeaterControlID(fldID, i)
{	
	// we dont know the control type so this tries to get the control by looking it up as an 'input' and then as a 'select'
	var controls = GetElementsByTagNAttr('input', 'myid', fldID);
	
	// second try for select
	if(controls == null || controls.length == 0) controls = GetElementsByTagNAttr('select', 'myid', fldID);
		
	// and lastly 'div' for those controls which have multiple parts
	if(controls == null || controls.length == 0) controls = GetElementsByTagNAttr('div', 'myid', fldID);
		
	if(controls != null && controls.length > 0)
	{		
		return controls[i].id;
	}
	else
		return '';
}


function DDLAddOption(ddl, value, text, isSelected)
{
	var option = document.createElement('option');
	option.text = text;
	option.value = value;
	if(IsDefined(isSelected) && isSelected == true) option.selected = true;
	
	try{ddl.add(option, null);}
	catch(ex){ddl.add(option);}
}

function GetControlByMyID(tagName, myID)
{
	var controls = GetElementsByTagNAttr(tagName, 'myid', myID);
	if(controls != null && controls.length > 0)
		return controls[0];
	else
		return null;
}

function GetControlValue(controlID)
{
	var control = $(controlID);
	
	/// Get the ControlID by using the "MyID" if the first/defaul way fails
	if(control == null) 
    {
       var newID = GetCtrlID(controlID);
       if(newID && newID != '') control = $(newID); 
    }
	
	//alert('controlID: ' + controlID + '; control: ' + control);
	
	if(control == null) return '';
	
	var controlType =  control.getAttribute('tp');
	
	if(controlType == '7') // phone	
		return GetPhoneControlValue(id);	
	else if(controlType == '21') // ssn
		return GetSSNControlValue(id);
	else if(controlType == '2') // date
		return GetDateControlValue(id);				
	else if(controlType == '3' || controlType == '4') // time or date+time
		return GetDateTimeControlValue(id);
	else if(controlType == '10') // region	
		return GetRgnControlValue(id);		
	else if(controlType == '25') // yes/no radio buttons
	{				
		if(control.checked == true)
		    return '1';
		else
		    return '0';			
	}	
	else if(controlType == '5') // checkbox
	{		    
		if(control.checked == true)
		    return '1';
		else
		    return '0';			
	}	
	else if(controlType == '28') // Chk-Lst
	{		    
		if(control.checked && control.checked == true)
		    return '1';
		else
		{
		    /// See if we are dealing with the cntr
		    return null;			
		}
	}
	else if(control) return Trim(control.value);
	else return '';	
}
function GetPhoneControlValue(id)
{
    var hidPhn = $(id + '_HidPhn');	
	if(hidPhn.value == '1')
	{
		var phnInt = $(id + '_PhnInt');
		return Trim(phnInt.value);		
	}
	else
	{
		var phn0 = Trim($(id + '_Phn0').value);
		var phn1 = Trim($(id + '_Phn1').value);
		var phn2 = Trim($(id + '_Phn2').value);
	
	    if(phn0 == '' || phn1 == '' || phn2 == '')
		    return '(' + phn0 + ')' + phn1 + '-' + phn2;
		else
		    return '';
	}
}
function GetSSNControlValue(id)
{
	// first have to check if the control is shown because it could be not there
	if($(id + '_0') != null)
	{
		var val0 = Trim($(id + '_0').value);
		var val1 = Trim($(id + '_1').value);
		var val2 = Trim($(id + '_2').value);				
				
		if(val0 == '' || val1 == '' || val2 == '') return val0 + '-' + val1 + '-' + val2;		
	}
	return '';
}
function GetDateControlValue(id)
{
    var control = $(id);
	var dt = control.value;
	dt = dt.replace(' ', '');
	if(dt == dateFormat)	 
	    return '';		
	else 
	    return dt;
}
function GetDateTimeControlValue(id)
{
	var hr = GetControlValue(id + '_hr');
	var min = GetControlValue(id + '_min');
	var returnVal = GetDateControlValue(id + '_dt');
	
	if(hr != '')			
	{
		returnVal += hr;
		if(min != '') returnVal += ':' + min;
	}				
	return returnVal;
}
function GetRgnControlValue(id)
{
	var st = $(id + '_st');
	var rgn = $(id + '_st');
	
	// We have to check that this control is visible
	if(rgn.offsetWidth == 0 && st.offsetWidth == 0) return '';
	
	if(GetControlValue(id + '_hidIsSt') == '1') // when state	
		return st.value;	
	else	
		return Trim(rgn.value);		
}


function GetControlInnerHTML(controlID)
{
	var control = $(controlID);
	if(control) return control.innerHTML;
	else return '';	
}
function SetControlValue(controlID, value)
{
	var control = $(controlID);
	if(control) control.value = value;	
}
function SetControlValueFromAtr(thisControl, targetControlID, atrName)
{	
	if(!atrName) atrName = 'atr';
	var option = thisControl.options[thisControl.selectedIndex];
	var atr = option.getAttribute(atrName);	
	
	if(atr && atr != null)
	{ 
		var targetControl = $(targetControlID);
		var tp = targetControl.getAttribute('tp');
		if(tp == '6') atr = GetMoneyFormat(atr);		
		targetControl.value = atr;
	}
}
// good for checkbox changing visibility of a row or table
function ToggleControl(ctrlID, isVis) {
    if(!IsDefined(isVis)) /// When not specified if vis then we make it so that it can turn it of and on
    {
        var ctrl = $(ctrlID);
        if(ctrl.style.display == 'none')
            isVis = true;
        else
            isVis = false;
    }

    if (isVis) ShowControl(ctrlID);
    else HideControl(ctrlID);
}

function ShowControl(controlID)
{
	var control = $(controlID);
	//alert('ShowControl - control = ' + control);
	if(control) control.style.display = '';
}
function HideControl(controlID)
{
	var control = $(controlID);
	//alert('HideControl - control = ' + control);
	if(control) control.style.display = 'none';
}
function HideSelf(self){ if(self) self.style.display = 'none'; }
function GetMoneyFormat(s)
{
	if(s != null && s != '')
	{
		var dotIdx = s.indexOf('.');
		var change = s.substring(dotIdx + 1);
		if(change != '00' && change != '0000')
			return s.substring(0, dotIdx + 3);
		else
			return s.substring(0, dotIdx);				
	}
	else
		return '';
}
// =============================================        AJAX             ====================================================
function AJAXGetXmlHttpObject(handler)
{ 
	var objXMLHttp=null;
	if (window.XMLHttpRequest)	
		objXMLHttp=new XMLHttpRequest();	
	else if (window.ActiveXObject)
	{
		try{objXMLHttp=new ActiveXObject("Msxml2.XMLHTTP");}
		catch(e){try{objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}}
	}	
	return objXMLHttp;
} 

var xmlHttp;

// AJAXGetStr Bgn
var xmlHttpGeStr;
function AJAXGetStr(pageUrl, stateChangedFunction)
{		
	pageUrl = GetUniqueAJAXUrl(pageUrl); // necessary so that won't cache
	xmlHttpGeStr = AJAXGetXmlHttpObject();
	if(xmlHttpGeStr == null){AJAXShowError(); return;} 			
	xmlHttpGeStr.onreadystatechange = stateChangedFunction;
	xmlHttpGeStr.open("GET", pageUrl, true);
	xmlHttpGeStr.send(null);		
}

function AJAXShowArea(pageUrl, containerID, isShowLoading)
{		
	if(!IsDefined(isShowLoading)) isShowLoading = true;
	var ajaxAreaContainer;
	var xmlHttpShowArea;
	xmlHttpShowArea = AJAXGetXmlHttpObject();
	if(xmlHttpShowArea == null)
	{
		AJAXShowError(); return;
	} 		
	ajaxAreaContainer = $(containerID);
	
	if(isShowLoading == true) ajaxAreaContainer.innerHTML = '<img src="/SAM/Img/Loading.gif" alt="" />';
			
	
	function AJAXShowAreaStateChanged() 
	{ 	
		if(xmlHttpShowArea.readyState == 4 || xmlHttpShowArea.readyState == "complete")	
		{		
			// hide the area if it empty
			if(xmlHttpShowArea.responseText != '' && xmlHttpShowArea.responseText != ' ') // ajax pages can return blank space 
			{				
				ajaxAreaContainer.innerHTML = xmlHttpShowArea.responseText;							
				if(ajaxAreaContainer.style.display == 'none') ajaxAreaContainer.style.display = '';							
			}
			else
				ajaxAreaContainer.style.display = 'none'; 
		}
	}
	this.AJAXShowAreaStateChanged = AJAXShowAreaStateChanged;

	pageUrl = GetUniqueAJAXUrl(pageUrl);

	xmlHttpShowArea.onreadystatechange = AJAXShowAreaStateChanged;
	xmlHttpShowArea.open("GET", pageUrl, true);
	xmlHttpShowArea.send(null);		

}

function GetUniqueAJAXUrl(url)
{
	if(url.indexOf('&bs') == -1)
	{
		if(url.indexOf('?') != -1)
			url += '&bs=' + new Date().getTime();
		else
			url += '?bs=' + new Date().getTime();
	}
	return url;
}

// for pages that exec some proc but dont return anything
function AJAXCallPage(pageUrl)
{	
	var xmlHttpCallPage = AJAXGetXmlHttpObject();
	if(xmlHttpCallPage == null)
	{
		AJAXShowError(); return;
	} 				
	xmlHttpCallPage.open("GET", GetUniqueAJAXUrl(pageUrl), true);
	xmlHttpCallPage.send(null);
}

function AJAXCallPageNHideLnk(pageUrl, lnkID) {
    AJAXCallPage(pageUrl);
    var lnk = $(lnkID);
    if(lnk && lnk.style) lnk.style.display = 'none';
}

function ConfirmAJAXCallPageNRefresh(msg, ajaxPageUrl) { if(window.confirm(msg)){ AJAXCallPageNRefresh(ajaxPageUrl); } }

function AJAXCallPageNRefresh(ajaxPageUrl) { AJAXCallPageNRedirect(ajaxPageUrl, window.location); }

function AJAXCallPageNRedirectAfterConfirm(ajaxPageUrl, redirectPageUrl, confirmText) {
    if (window.confirm(confirmText)) AJAXCallPageNRedirect(ajaxPageUrl, redirectPageUrl);
}

var ajaxRedirectPageUrl;
// for pages that exec some proc but dont return anything and redirect to another page after they are executed (redirect only after done executing so that changes are made before redirect page is loaded)
function AJAXCallPageNRedirect(ajaxPageUrl, redirectPageUrl)
{		
	var xmlHttpCallPage;	
	xmlHttpCallPage = AJAXGetXmlHttpObject();
	ajaxRedirectPageUrl = redirectPageUrl;	
	if(xmlHttpCallPage == null) { AJAXShowError(); return; } 				
	xmlHttpCallPage.onreadystatechange = AJAXCallPageNRedirectStateChanged;
	xmlHttpCallPage.open("GET", GetUniqueAJAXUrl(ajaxPageUrl), true);
	xmlHttpCallPage.send(null);		
	
	function AJAXCallPageNRedirectStateChanged()
	{
		if(xmlHttpCallPage.readyState == 4 || xmlHttpCallPage.readyState == 'complete')	
		{
			setTimeout("window.location = ajaxRedirectPageUrl", 100); // need to setup timeout because sometimes refreshes too early
		}
		//window.location = ajaxRedirectPageUrl;	
	}
	this.AJAXCallPageNRedirectStateChanged = AJAXCallPageNRedirectStateChanged;
}

function AJAXToggleArea(ajaxPageUrl, controlID)
{
	var control = $(controlID);
	if(control.style.display != 'none')
	{
		control.style.display = 'none';				
	}
	else
	{
		control.style.display = '';		
		if(control.innerHTML == '')				
			AJAXShowArea(ajaxPageUrl, controlID);
	}
}


// NEEDS to be changed to displaying a bar on the page which states that 
function AJAXShowError() { alert ("Browser does not support HTTP Request.\n Please contact your administrator."); }

// for simply getting the val inside an xml element
function XmlGetVal(el, i)
{
	return (el.childNodes[i] && el.childNodes[i].firstChild && el.childNodes[i].firstChild.nodeValue ? el.childNodes[i].firstChild.nodeValue : '');
}
// =============================================	Disable Accidental Form Submit	====================================================

// should be used an all pages so that a user does not accidentily cause the form to submit while still entering values 
// must put issubmit="1" on non-submit buttons to allow the control to submit the form when pressing enter when control has focus
function DisableFalseSumbit(e)
{            
    // the event passed in will be null in IE
    if(e == null) e = window.event;        
    if(e) 
	{
		var charCode = (e.charCode ? e.charCode : e.keyCode);    		
		if(charCode == 13)// && (e.target && e.target.attributes && e.target.attributes.getNamedItem(attrName) && e.target.attributes.getNamedItem(attrName).value != "1"))        
		{        						
			var target = (e.target ? e.target : e.srcElement);
			
			//if(GetControlAttribute(e.target, "type") != "submit" && e.target.type != "textarea")
			//if(target.tagName != "A" && target.type != "textarea")			
			if(target.type != "textarea")			
			{        
				if(!isIE) 
				{
					e.preventDefault();					
					e.stopPropagation();			
				}
				else 
				{
					e.cancelBubble = true;					
					e.returnValue = false;
				}
			}
			
		}
	}
}
try{document.onkeydown = DisableFalseSumbit;}catch(er){}

function LnkKeydown(lnk, e)
{	
	if(e == null) e = window.event;        
    if(e) 
	{
		var charCode = (e.charCode ? e.charCode : e.keyCode);    		
		//if(charCode == 13) lnk.onclick();			
		if(charCode == 13)
		{ 
			var onclick = lnk.getAttribute('onclick');
			if(onclick != null && onclick != '')
				lnk.onclick();			
			else
				window.location = lnk.href;
		}
	}
}
// =============================================	Integrated Popup	====================================================

var isIE = (document.all != null ? true : false);

function CreateMyFrame(obj, objID, className)
{
	obj = document.createElement("div");
	document.body.appendChild(obj);
		
	if(className && className != '') obj.className = className;	
	//alert(obj.className);
	obj.id = objID + '_cntr';	
	//obj.zIndex = 999;
	
	CreateMyIFrame(obj, objID, '');
}

function CloseMyFrame(iFrameID)
{		
	var frmCntr = $(iFrameID + '_cntr');
	frmCntr.style.display = 'none';	
	
	var ifrm = $(ifrm);
	if(ifrm) ifrm.src = '/SAM/Loading.html'; // set this first because it is not being set when no visible
}

function CreateMyIFrame(ifrmPrnt, id, src)
{
	var ifrm = document.createElement("iframe");
	
	ifrm.id = id;
	ifrm.name = id;
	
	if(isIE)
	{
		ifrm.width = '100%';
		//ifrm.height = '85%';
		if(id == 'ifrmEdt' || id == 'ifrmPic')
			ifrm.height = '85%';
		else
			ifrm.height = '90%';
	}
	
	ifrm.style.width = '100%';
	//ifrm.style.height = '85%';
	if(id == 'ifrmEdt' || id == 'ifrmPic')
		ifrm.style.height = '85%';
	else
		ifrm.style.height = '90%';
		
	ifrm.scrolling = "auto";		
			
	if(src != null && src != '')
		ifrm.src = src;	
	else
		ifrm.src = '/SAM/Loading.html';
		
	ifrm.className = "Iframe";
	ifrm.frameBorder = 0;			
	//ifrm.zIndex = 9999;	
									
	CreateIframeCloseBtn(ifrmPrnt);
		
	
	ifrmPrnt.appendChild(ifrm);		
}



function CreateIframeCloseBtn(prnt)
{
	var img = document.createElement("img");
	
	prnt.appendChild(img);
	
	if(isIE)
	{
		img.onclick = function(){ HideInPage(this.parentNode);}
	}
	else
	{
		img.setAttribute("onclick", "HideInPage(this.parentNode);");
	}
	img.id = "imgClose";
	img.src  = "/SAM/Img/Close.png";
	img.className = "ImgClose";	
}



function HideInPage(ifrmPrnt)
{
    ifrmPrnt.style.display = 'none';
    /// The "iFrm" is inside the ifrmPrnt
    var ifrm = ifrmPrnt.getElementsByTagName("iframe")[0];
    //alert('ifrm.src = ' + ifrm.src);
    if(ifrm) ifrm.src = '/SAM/Loading.html';
	//alert('ifrm.src = ' + ifrm.src);		
}


function CreateEdtFrame()
{
	edtIframeCntr = document.createElement("div");
	document.body.appendChild(edtIframeCntr);
		
	edtIframeCntr.className = "divEdtIframe";	
	edtIframeCntr.id = "edtFrame";	
	isEdtIframe = true;

	CreateMyIFrame(edtIframeCntr, edtIframeID, '');
}
/// =============== Medium Frame =============
var isMediumIframe = false;
var mediumIframeID = "ifrmMedium";
var mediumIframeCntr;
var mediumIframe;

function GetMediumIFrame(win)
{
	if(!IsDefinedNNotNull(win)) win = window;
	
	if(!win.isMediumIframe) 
		win.CreateMediumFrame();			
	else 	 
		win.mediumIframeCntr.style.display = '';				
			
	return win.$(win.mediumIframeID);
}
function CreateMediumFrame()
{
	mediumIframeCntr = document.createElement("div");
	document.body.appendChild(mediumIframeCntr);
		
	mediumIframeCntr.className = "divMediumIframe";	
	mediumIframeCntr.id = "mediumFrame";
	isMediumIframe = true;
	
	CreateMyIFrame(mediumIframeCntr, mediumIframeID, '');	
}
function CloseMediumIframe(){ mediumIframeCntr.style.display = 'none'; }

function ShowPopupMsgPub(msgKey)
{				
	
	if(!isMediumIframe) CreateMediumFrame();			
	else 
	{ 
		mediumIframeCntr.style.display = '';						
	}	
	
	if(mediumIframe == null) mediumIframe = document.getElementById(mediumIframeID);			
		
	mediumIframe.src = '/SAM/Ctrl/PopupMsg_Pub.aspx?pubmsgkey=' + msgKey;
}

// =============================================	Misc	====================================================

var isValidateInput = false; // is set in each individual forms EH page

function SubmitForm()
{		
    //alert('isValidateInput = ' + isValidateInput);
	if(isValidateInput)	
	{
		if(ValidateInput()) 
			if(CheckDup()) MyPostBack();
	}
	else if(CheckDup()) MyPostBack();
}
function CheckDup()
{
	// will only have the duplicate confirmation when adding the duplicate
	var entID = GetControlValue('hidEntID');	
	if(entID == '')
	{
		var dvDup = $('dvDup');	
		if(dvDup && dvDup.style.display && dvDup.style.display != 'none')
		{
			return window.confirm('You are about to enter a Possible Duplicate Record!\n\nPlease ensure that this record is not a duplicate by clicking on the \'View Duplicate Record\' link.\n\nIf you are sure that this is not a duplicate record then please press the \'Ok\' button, otherwise please press the \'Cancel\' button.');
		}
		else
			return true;
	}
	else 
		return true;
}

/// =============== Dynamic Layout =============

function getBrowserWidth(){
	var win = (window.parent == null || window.parent.location.toString() == location.toString() ? window : window.parent);
    if (win.innerWidth){return win.innerWidth;}  
    else if (win.document.documentElement && win.document.documentElement.clientWidth != 0){ return win.document.documentElement.clientWidth;    }
    else if (win.document.body){return win.document.body.clientWidth;}      
        return 0;
}
function getBrowserHeight(){
	var win = (window.parent == null || window.parent.location.toString() == location.toString() ? window : window.parent);
    if (win.innerHeight){return win.innerHeight;}  
    else if (win.document.documentElement && win.document.documentElement.clientHeight != 0){ return win.document.documentElement.clientHeight;    }
    else if (win.document.body){return win.document.body.clientHeight;}      
        return 0;
}

function dynamicLayout(){
    var browserWidth = getBrowserWidth();
	//alert('browserWidth = ' + browserWidth);
    //Load Thin CSS Rules
    if (browserWidth < 949){
        changeLayout("small");
    }
    //Load Wider CSS Rules
    else if (browserWidth > 950 && browserWidth < 1200){
        changeLayout("medium");
    }

}

function changeLayout(description){
   var i, a;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++){
	
	   if(a.getAttribute("title") == description){a.disabled = false;}
	   else if(a.getAttribute("title") != "default" && a.getAttribute("title") != null && a.getAttribute("title") != ""){a.disabled = true;}
	   //alert('title = ' + a.getAttribute("title") + " - href = " + a.getAttribute("href") + " a.disabled = " + a.disabled);		
   }
}


function addEvent( obj, type, fn )
{ 
   if (obj.addEventListener)
   { 
      obj.addEventListener(type, fn, false);
   }
   else if (obj.attachEvent)
   { 
		obj["e"+type+fn] = fn; obj[type+fn] = function(){ obj["e"+type+fn]( window.event ); }; obj.attachEvent( "on"+type, obj[type+fn] ); } 
} 

/* Screen Optimizer does not work in Safari, have to move all the font-sizes to Regular.css */



//Run dynamicLayout function when page loads and when it resizes.
addEvent(window, 'load', dynamicLayout);
//addEvent(window, 'resize', dynamicLayout);

function PrnClk(ctrl){if(ctrl && ctrl != null && ctrl.parentNode != null) ctrl.parentNode.click();}

function ControlSetClass(control, className)
{	
	control.className = className;
}

function ControlAddClass(control, className)
{
	if(control.className != '')
		control.className += ' ' + className;
	else
		control.className = className;
}
var oldCss;
function LnkBtnFoc(control)
{
	oldCss = control.className;
	ControlAddClass(control, 'lnkBtnHover');
}

function LnkBtnBlur(control)
{
	ControlSetClass(control, oldCss);
}

// necessary because IE and other browsers use different calls
function AddEvent(obj, ev, fu) 
{	
	if (obj.attachEvent)
		obj.attachEvent("on" + ev, fu);
	else
		obj.addEventListener(ev, fu, false);
}
function GetUniqueID()
{
	var uniqueID = ''
	var i = 0;
	while(uniqueID == '')
	{
		if($(i)) unqiueID = i;
		i++;
	}
}

String.prototype.startsWith = function(str) 
{
    return (this.indexOf(str) == 0);
    //return (this.match("^"+str)==str)
}

