//  Copyright 2008 Narragansett Technologies.  All Rights Reserved.
//**Start Encode**
var changed    = false;
var HTMLFields = false;// Do we have HTML Fields on the Panel !
var saved      = false;
var firstList="";// Name of First List on a Page 
var homeSite="../";
//Global page name
var strPage = document.location.pathname.substring( document.location.pathname.lastIndexOf( "/" ) + 1, document.location.pathname.lastIndexOf( "." ) );
var fullStrPage = document.location.pathname;
var localUrl = window.location.href;
	localUrl = localUrl.substr(0,localUrl.indexOf(strPage));

if (strPage!="templateHome")//disable help on logon page
    document.onhelp = F1Help;
//auto refresh
function autoRefresh(timeoutPeriod) {
    setTimeout("location.reload(true);", timeoutPeriod);
}
// see if changes have been saved
function saveDoc(){
if (!saved && changed){
	saved=true;
	document.forms[0].submit();
	//FIX FOR IE5
	if (navigator.appName == 'Microsoft Internet Explorer')
	    if (event) event.returnValue=false;}
}
//set drop down
function setDropDown(aObj, textValue) {

    TextVal = Trim1(textValue.toLowerCase());
    for (ix = 0; ix < aObj.length; ix++) {
        dropText = Trim1(aObj[ix].text.toLowerCase());
        if (dropText == TextVal) {

            aObj[ix].selected = true;
        }
    }
}
function setDropDownByValue(aObj, textValue) {

    TextVal = Trim1(textValue.toLowerCase());
    for (ix = 0; ix < aObj.length; ix++) {
        dropText = Trim1(aObj[ix].value.toLowerCase());
        if (dropText == TextVal) {

            aObj[ix].selected = true;
        }
    }
}
// RefreshList Contents
function refreshPage(){
document.forms[0].submit();

}

function Paging(aId,aDir){
ListPostBack(aId,'',aDir);
window.event.cancelBubble=true;
return false;
}
function getScreenPosition(e) {
    e = e || window.event;
    var cursor = { x: 0, y: 0 };
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    }
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX +
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY +
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}
//List Post back function
function ListPostBack(aControl1,sortField, pageDirection){
var aControl = aControl1.replace(/\t/,""); 
getElementx(aControl + "_Sort").value = sortField;
getElementx(aControl + "_Direction").value = pageDirection;
getElementx(aControl + "_Active").value = "Y";
saved = true;
//if scrolling on list replace action to ensure that last action does not get executed again
document.forms[0].action = document.forms[0].action.replace("Request","xOequest");
document.forms[0].submit();
window.event.cancelBubble=true;
//FIX FOR IE5
if (navigator.appName == 'Microsoft Internet Explorer')
	if (event) event.returnValue=false;

//alert(1);
}
function hideFilter1(aControl) {
    if (getElementx(aControl).className == "showPanel")
        getElementx(aControl).className = "hidePanel";
    else
        getElementx(aControl).className = "showPanel";
}
function hideFilter(aControl) {
 
    if (getElementx(aControl + "_Filter")) {
        if (getElementx(aControl + "_Filter").className == "showPanel")
            getElementx(aControl + "_Filter").className = "hidePanel";
        else
            getElementx(aControl + "_Filter").className = "showPanel";
    }
    else
        hideFilter1(aControl)
}

// Set All HTMLFields with their Text
function setHTMLFields(){
HTMLFields=true;
for (var ix=0; ix<document.all.length; ix++){
	if (getElementx(ix).HTMLField){
		getElementx(getElementx(ix).HTMLField).innerHTML = getElementx(ix).value;
		}
	if (getElementx(ix).HTMLDiv){
		getElementx(ix).unselectable = "off";
		//getElementx(ix).onkeypress = checkEnter;
		}
	//else
	//	getElementx(ix).unselectable = "on";
	}
}

function checkEnter(){
var sel = null;
var keyCode = event.keyCode;
if (keyCode ==13){// Cancel enter if pressed
	activeHtmlBox.focus();
	event.keyCode="\r";
	//var sel = document.selection.createRange();
	//if (sel.pasteHTML){
	//	sel.pasteHTML("<br>\r");
	//	//event.cancelBubble=true;
	//	event.returnValue=false;
	//	}
	}
}

// Copy All HTMLFields with their Text
function copyHTMLFields(){
for (var ix=0; ix<document.all.length; ix++){
	if (getElementx(ix).HTMLField){
		if (getElementx(ix).textMode){
			if (getElementx(ix).textMode == '1'){
				getElementx(getElementx(ix).HTMLField).innerHTML=getElementx(getElementx(ix).HTMLField).innerText;
				getElementx(ix).textMode = '0';// Return To HTML
				}
			}
		getElementx(ix).value = getElementx(getElementx(ix).HTMLField).innerHTML.replace('vid :','').replace(localUrl+"{","{").replace(localUrl+"/{","{");
		getElementx(getElementx(ix).name + "1").value = getElementx(getElementx(ix).HTMLField).innerText;
		}
	}
}

//function takes URL and submits to server
function reSubmit(url)
{	//Call client validation if it exista
	//alert(url);
	if (typeof(Page_ClientValidate) == 'function') 
	{
		var Ok =Page_ClientValidate();
		if	(Ok)
		{
			if (url.length >0)
				document.forms[0].action = url;
			if (HTMLFields)
				copyHTMLFields();// Copy HTML Fields to Hidden Fields
			document.forms[0].submit();
			
		}
	}
	else
	{
		if (url.length >0)
				document.forms[0].action = url;
			if (HTMLFields)
				copyHTMLFields();// Copy HTML Fields to Hidden Fields
			document.forms[0].submit();
	}
	//FIX FOR IE5
	if (navigator.appName == 'Microsoft Internet Explorer')
	    if (event) event.returnValue=false;
	return false;
}
function reDirect(url)
{	//Call client validation if it exista
	//alert(url);
	if (url.length >0)
		document.forms[0].action += '?newurl=' + url;
	if (HTMLFields)
			copyHTMLFields();// Copy HTML Fields to Hidden Fields
		document.forms[0].submit();
		//FIX FOR IE5
    if (navigator.appName == 'Microsoft Internet Explorer')
	    if (event) event.returnValue=false;
	return false;
}
//function takes URL and goes to new location
function newLocation(url)
{
    location.href = url;
    if (navigator.appName == 'Microsoft Internet Explorer')
		if (event) event.returnValue=false;
		return false;
}
function encodeHtml(Html) {
     Html = escape(Html);
     Html = Html.replace(/\//g,"%2F");
     Html = Html.replace(/\?/g,"%3F");
     Html = Html.replace(/=/g,"%3D");
     Html = Html.replace(/&/g,"%26");
     Html = Html.replace(/@/g,"%40");
     return Html;
   } 

//function takes URL and goes to new location
function newLocationWithMsg(url,msg)
{	
	if (msg.length>0)
	{
		if (!confirm(msg))
			return;
	}
	newLocation(url);
}
//function takes URL and submits to server
function reSubmitWithMsg(url,msg)
{	
	if (msg.length>0)
	{
		if (!confirm(msg))
			return;
	}
	reSubmit(url);
}
//open page in windowd
function reSubmitWithMsgOpenWindow(url,msg,iWidth,iHeight,aPageID)
{
	var sWindowInfo="";
	sWindowInfo = "resizable=yes,width=" +iWidth+ ",height=" + iHeight + ",top=" + (window.screenTop+10) + ",left=" + (window.screenLeft+10)  + ",toolbar=no, status=yes, scrollbars=yes"
	if (msg.length>0)
		{
			if (!confirm(msg))
				return;
		}
		var aWin = window.open(url, aPageID, sWindowInfo);
		aWin.focus();
		return aWin;
}
function getElementx(elementx)
{	var elem;
		if (navigator.appName == 'Microsoft Internet Explorer')
			elem = document.all(elementx);
		else
		{
		    if (navigator.appName == 'Opera')
		        elem =   document.forms[0].elements[elementx];
		    else
		    {
			    elem = document.getElementById(elementx);
			    if (elem==null) // get element by index number
				    elem = document.forms[0].elements[elementx];
			}
		}
	return elem;
}

//List Post back function Called for Filters to find if Enter is Pressed
function filterEnterKey(aControl){
if (window.event.keyCode == 13) {// Enter Key
	window.event.cancelBubble=true;
	window.event.keyCode = 0;
	ListPostBack(aControl,'','FILTER')
	}
}
//List Post back function Called for Filters to find if Enter is Pressed
function filterEnterKeyCustom(aControl) {
    if (window.event.keyCode == 13) {// Enter Key
        window.event.cancelBubble = true;
        window.event.keyCode = 0;
        ListPostBack(aControl, '', 'FILTERCustom')
    }
}

//Delete a Specific Item
function deleteItem(url,aItem)
{	

window.event.cancelBubble=true;
if (window.confirm("Delete(" + aItem + ") ?")){
	document.forms[0].action = url;
	document.forms[0].submit();
	//FIX FOR IE5
	if (navigator.appName == 'Microsoft Internet Explorer')
	    if (event) event.returnValue=false;
	}
}

//Include or Exclude a Specific Item
function ItemClick(url)
{	
	document.forms[0].action = url;
	saved = true;
	document.forms[0].submit();
	//FIX FOR IE5
	if (navigator.appName == 'Microsoft Internet Explorer')
	    if (event) event.returnValue=false;
	
}

// Highlight a Row Color
function rowHighlight(aObj){
aObj.style.backgroundColor ='#f0f0f0';
}

// Revert a Row Color
function rowNormal(aObj){
aObj.style.backgroundColor ='';
}

function promptValue(aControl, aValue) {
   
getElementx(aControl).value = aValue;
if (getElementx(aControl).onchange)
	getElementx(aControl).onchange();
}

function helpAbout(){
window.open('../help/about.aspx','About','width=400, height=300, toolbar=no, status=no, scrollbars=no, resizeable=no');
}

function Print(ReportId){
window.open('../System/Print.aspx?ReportId' + ReportId ,'Print','width=300, height=243, toolbar=no, status=no, scrollbars=no, resizeable=no');
}

function F1Help(aControl){
	window.event.cancelBubble=true;
	window.event.keyCode = 0;
	openHelp();
	return false;
}

function openHelp() {
    //var strPage = document.location.pathname.substring( document.location.pathname.lastIndexOf( "/" ) + 1, document.location.pathname.lastIndexOf( "." ) );
    var fullStrPage1 = '';
    try {
        fullStrPage1 = fullStrPage.substring(1, fullStrPage.lastIndexOf("/"));
        fullStrPage1 = fullStrPage1.substring(fullStrPage1.lastIndexOf("/") + 1, fullStrPage1.length);
        //alert(fullStrPage);
    }
    catch (e) { fullStrPage1 = ''; }
    window.open('../help/RunHelp.aspx?PageName=' + strPage + '&SDir=' + fullStrPage1, 'Help', 'width=500, height=550, toolbar=no, status=no, scrollbars=yes, resizeable=yes')
}

function openHelpIndex() {
    window.open('../help/RunHelp.aspx?PageName=index', 'Help', 'width=500, height=580, toolbar=no, scrollbars=yes, resizeable=yes')
}

function openHelpReuseParam(helpid) {
    window.open('../help/RunHelp.aspx?PageName=' + helpid, 'Help', 'width=700, height=550, scrollbars=yes, toolbar=no, resizeable=yes')
}

function getPageName() {
	var strPage = document.location.pathname.substring( document.location.pathname.lastIndexOf( "/" ) + 1, document.location.pathname.lastIndexOf( "." ) );
	return strPage;
 }

 function openWindow(aPage, aPageID, iWidth, iHeight) {
	var sWindowInfo="";
	sWindowInfo = "resizable=yes,width=" +iWidth+ ",height=" + iHeight + ",top=" + (window.screenTop+10) + ",left=" + (window.screenLeft+10)  + ",toolbar=no, status=yes, scrollbars=yes"
	var aWin = window.open(aPage, aPageID, sWindowInfo);
	aWin.focus();
	return aWin;
}
function openWindowMax(aPage, aPageID, iWidth, iHeight) {
    var sWindowInfo = "";
    if (window.screen) {
        iWidth = window.screen.availWidth;
        iHeight = window.screen.availHeight;
    }
    sWindowInfo = "resizable=yes,width=" + iWidth + ",height=" + iHeight + ",top=0,left=0,toolbar=no, status=yes, scrollbars=yes"
    var aWin = window.open(aPage, aPageID, sWindowInfo);
    aWin.focus();
    return aWin;
}


function evalMessage() {
	alert('This software has a time-limited license key. Please contact your software vendor for a permanent key.')
}

function Trim1(s) {
  return s.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "");
}
// =========================== Numeric Helpers =======================================================
function formatMoney(aVal1,decSep,groupSep){
var aVal = aVal1.toString().replace(groupSep,'');
var aVal = aVal.replace(decSep,'.');
var decPlaces = aVal.substr(aVal.lastIndexOf('.')+1);
decPlaces = Trim1(decPlaces).length
//get number fo dec places
if (decPlaces<2||decPlaces>4)
    decPlaces=2;
switch (decPlaces)
{
	case 3:
		mulDiv=1000;
		break;
	case 4:
		mulDiv=10000;
		break;
	default:
	    mulDiv =100;
		break;
}
var res = "";
if (!isNaN(aVal) && aVal.length > 0){
	var aNum = Math.round(aVal*mulDiv)/mulDiv;
	var intPart = parseInt(aNum);
	var dec = parseInt(Math.round((aNum-intPart)*mulDiv));
	var intStr = intPart.toString();
	var iy=0;
	var aComma = "";
	for (var ix=1;ix<=intStr.length;ix++){
		if (iy==3){iy=0;aComma= groupSep;} else {iy++;aComma=""}
		res =  intStr.substr(intStr.length-ix,1) + aComma + res;
		}
	if (dec.toString().length < decPlaces)
	{
	   var pad = decPlaces - dec.toString().length;
	   switch (pad)
	   {
		    case 1:
		    res = res + decSep + "0" + dec.toString();
		    break;
		    case 2:
		    res = res + decSep + "00" + dec.toString();
		    break;
		    case 3:
		    res = res + decSep + "000" + dec.toString();
		    break;
		    case 4:
		    res = res + decSep + "0000" + dec.toString();
		    break;
	   }
	}
	else
	   res = res + decSep + dec.toString();
	}
else
	res = aVal1;
return res;
}

function formatInt(aVal1,decSep,groupSep){
var aVal = aVal1.toString().replace(groupSep,'');
var aVal = aVal.replace(decSep,'.');
var res = "";
if (!isNaN(aVal) && aVal.length > 0){
	var aNum = Math.round(aVal*100)/100;
	var intPart = parseInt(aNum);
	var intStr = intPart.toString();
	var iy=0;
	var aComma = "";
	for (var ix=1;ix<=intStr.length;ix++){
		// if (iy==3){iy=0;aComma= groupSep;} else {iy++;aComma=""}
		res =  intStr.substr(intStr.length-ix,1) + aComma + res;
		}
	}
else
	res = aVal1;
return res;
}
// ========================================================================================================


// ============================= Calendar Routines ============================================

function calendarClick(aField,aFormat) {
	var dateParts;
	var fmt;
	var found = false;
	var aDate = new Date();
	var aMonth = aDate.getMonth()+1,aYear=aDate.getFullYear(),aDay = aDate.getDate();//Default Values
	var aDateStr = "";
	
getElementx('cal').currElement=getElementx(aField);
if ((event.clientY+10 + 240) < document.body.clientHeight) {
   getElementx('cal').style.top=event.clientY+10;
   }
else {
   getElementx('cal').style.top=document.body.clientHeight - 240;
   }
getElementx('cal').style.position='absolute';
if ((event.clientX+10 + 220) < document.body.clientWidth) {
   getElementx('cal').style.left=event.clientX;
   }
else {
   getElementx('cal').style.left=document.body.clientWidth-225;
   }


var aFormat1 = aFormat.toLowerCase();
var aValue = getElementx(aField).value;

if (aValue.length > 0){
	if (aFormat.search("/") != -1) {dateParts = aValue.split("/");fmt = aFormat1.split("/");found=true;};
	if (aFormat.search("-") != -1) {dateParts = aValue.split("-");fmt = aFormat1.split("-");found=true;};
	if (aFormat.search(":") != -1) {dateParts = aValue.split(":");fmt = aFormat1.split(":");found=true;};
	if (aFormat.search(/\\/) != -1) {dateParts = aValue.split("\\");fmt = aFormat1.split("\\");found=true;}; 
	if (aFormat.search("\ ") != -1) {dateParts = aValue.split("\ ");fmt = aFormat1.split("\ ");found=true;};
	if (aFormat.search("[\.]") != -1) {dateParts = aValue.split("\.");fmt = aFormat1.split("\.");found=true;}; 
	if (found)
	for (var  ix=0;ix < fmt.length && ix < dateParts.length ;ix++){
		if (!isNaN(dateParts[ix]))
		switch (fmt[ix]){
			case "m": case "mm":
				aMonth = parseInt(dateParts[ix],10);
				break;
			case "yyyy": case "yy":
				aYear = parseInt(dateParts[ix],10);
				break;
			case "d": case "dd":
				aDay = parseInt(dateParts[ix],10);
				break;
			default:
			break;
			}
		}
	//var aDate = new Date(getElementx(aField).value);
	}
aDateStr =  '' + aYear.toString() + '/' + aMonth.toString() + '/' + aDay.toString();
getElementx('cal').aFormat= aFormat1;
getElementx('cal').value=aDateStr;
getElementx('cal').style.display='';
getElementx('cal').children(0).focus();
try
{
if (hideCalFields())
	hideCalFields();
}
catch (e) {}
}
function isEMAIL(email) {
    var Regx = /^[\w\.\-]+\@[\w\.\-]+\.[\w.]{2,}$/;
    return (Regx.test(email));
}
function isPassword(password) {
    var Regx = /[0-9]/;
    return (Regx.test(password));
    
}
// ============================================================================================