//  Copyright 2009 Narragansett Technologies.  All Rights Reserved.
//**Start Encode**
var cErrorsFunctions = new Array('','','','','','','','','','','','','','','','','','',''); //don not delete used for compatibility
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));
var IsIE = false

if (navigator.appName == 'Microsoft Internet Explorer')
    IsIE = true;

if (strPage!="templateHome")//disable help on logon page
    document.onhelp = F1Help;
//Serialize array
//
function serializekSortList(SortList, SortField) {
    getElementx(SortField).value = $("#" + SortList).sortable('toArray').join('|');
}
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;
}
function fe(aObj)
{
}
function feOut(aObj)
{
}
function feMove(aObj)
{
   //												
}
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;
}				
// 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;
}
}
 
// RefreshList Contents
function refreshPage(){
document.forms[0].submit();

}
// compatibility for other browsers.
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;
}
function Paging(aId,aDir){
ListPostBack(aId,'',aDir);
window.event.cancelBubble=true;
return false;
}
//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;

}
 
function hideFilter(aControl){
if (getElementx(aControl).className == "showPanel")
	getElementx(aControl).className = "hidePanel";
else
	getElementx(aControl).className = "showPanel";
}

// Set All HTMLFields with their Text
function setHTMLFields(){
HTMLFields=true;
for (var ix = 0; ix < document.forms[0].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
// Copy All HTMLFields with their Text
function copyHTMLFields() {
    for (var ix = 0; ix < document.forms[0].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
	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 reSubmitAppendParm(urlParms) {	//Call client validation if it exista
    if (typeof (Page_ClientValidate) == 'function') {
        var Ok = Page_ClientValidate();
        if (Ok) {
            document.forms[0].action = document.forms[0].action + urlParms;
            document.forms[0].submit();
        }
    }
    else {
        document.forms[0].action = document.forms[0].action + urlParms;
        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 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);
}
//jquery modal
function modalAlert(url,msg)
{
    if ($('#myAlert').length==0)
        $("#aspnetForm").append('<div id="myAlert"></div>').hide();
    $("#myAlert").dialog({
        bgiframe: true,
        title: 'Warning',
        resizable: false,
        height: 140,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            OK: function() {
            $(this).dialog('close'); 
            },
            Cancel: function() {
            $(this).dialog('close');
            }
        }
    });
    $('#myAlert').dialog('open');
} 

//function takes URL and submits to server
function reSubmitWithPromptMsg(url, msg) {
    var name='';
    if (msg.length > 0) 
        name = prompt(msg,'');
    if (name == null)
        name = '';
    if (name.length > 0) {
        name.replace(' ', '');
        reSubmit(url + '&pfx=' + name.replace(' ',''));
    }
}
//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);
		if (aWin.focus)
		    aWin.focus();
		return aWin;
}


//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')
	}
}

//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';
    //aObj.style.border = "2px solid black"; 
}

// Revert a Row Color
function rowNormal(aObj){
aObj.style.backgroundColor ='';
}

function promptValue(aControl, aValue) {
    if (getElementx(aControl)) {
        getElementx(aControl).value = aValue;
        if (getElementx(aControl).onchange)
            getElementx(aControl).onchange();
    }
    else {
        aControl = aControl.replace('ctl00_mainPageArea_', '') //caused by security prompt in integrated mode. Using different cml conformance
        getElementx(aControl).value = aValue;
        if (getElementx(aControl).onchange)
            getElementx(aControl).onchange();
    }
}

function whatIsNew() {
    window.open('../System/RSSWhatsNew/RSS.xml', 'About', 'width=800, height=600, toolbar=yes, status=no, scrollbars=yes, resizeable=yes');
}
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 );
	}
	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=550, toolbar=no, status=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);
	if(aWin.focus)
    	aWin.focus();
	return aWin;
}
function openWindowMaxSize(aPage, aPageID, iWidth, iHeight) {
    var sWindowInfo = "";
    iWidth = screen.width - 50;
    iHeight = screen.height - 150;
    sWindowInfo = "resizable=yes,width=" + iWidth + ",height=" + iHeight + ",toolbar=no, status=yes, scrollbars=yes"
    var aWin = window.open(aPage, aPageID, sWindowInfo);
    if (aWin.focus)
        aWin.focus();
    return aWin;
}

function evalMessage() {
	alert('This software has a time-limited license key. Please contact your software vendor for a permanent key.')
}


// =========================== Numeric Helpers =======================================================
function formatMoney(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 dec = parseInt(Math.round((aNum-intPart)*100));
	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 == 1)
	   res = res + decSep + "0" + dec.toString();
	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) {}
}
//
//start replicate from runsurvey30Vx.js
//
function readCookie(cookieName) {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName);
    if (ind == -1 || cookieName == "") return "";
    var ind1 = theCookie.indexOf(';', ind);
    if (ind1 == -1) ind1 = theCookie.length;
    return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}
function Querystring() {
    // get the query string, ignore the ? at the front.
    var querystring = location.search.substring(1, location.search.length);
    // parse out name/value pairs separated via &amp;
    var args = querystring.split('&');
    // split out each name = value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        // Fix broken unescaping
        temp = unescape(pair[0].toLowerCase()).split('+');
        name = temp.join(' ');
        temp = unescape(pair[1]).split('+');
        value = temp.join(' ');
        this[name] = value;
    }
    this.get = Querystring_get;
}
function Querystring_get(strKey, strDefault) {
    var value = this[strKey.toLowerCase()];
    if (value == null) {
        value = strDefault;
    }
    else {
        if (value.toLowerCase() == 'undefined')
            value = '';
    }
    return value;
}
//
//end replicate from runsurvey30Vx.js
//
var documentOverlay = {
    show: function() {
        // ---------------------
        // STUFF YOU CAN CHANGE:
        var color = 'black';
        // SET THE COLOR HERE (IT CAN BE A HEX COLOR e.g. #FF00FF) 
        var opacity = 0.4;
        // SET AN OPACITY HERE - MUST BE BETWEEN 0 AND 1        
        // ---------------------        
        // DON'T TOUCH ANYTHING FROM HERE ONWARDS        
        // ---------------------        
        var o = document.getElementById('doc_overlay');
        if (!o) {
            var o = document.createElement('div');
            o.id = "doc_overlay";
            documentOverlay.style(o, {
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: documentOverlay.getDocHeight() + 'px',
                background: color,
                zIndex: 1000,
                opacity: opacity,
                filter: 'alpha(opacity=' + opacity * 100 + ')'
            });
            //document.body.appendChild(document.createElement('div'));
            document.getElementsByTagName('body')[0].appendChild(o);
        }
        else {
            documentOverlay.style(o, { background: color || '#000', display: 'block' });
        }
    },
    hide: function() {
        var o = document.getElementById('doc_overlay');
        o.style.display = 'none';
    },

    style: function(obj, s) {
        for (var i in s) {
            obj.style[i] = s[i];
        }
    },

    getDocHeight: function() {
        var Y, YT;
        if (self.innerHeight) {
            Y = self.innerHeight;
        }
        else
            if (document.documentElement && document.documentElement.clientHeight) {
            Y = document.documentElement.clientHeight;
        }
        if (document.body) {
            YT = document.body.clientHeight;
        }
        if (YT > Y) {
            Y = YT;
        }
        return Y;
    }
}
function isEMAIL(email) {
    var Regx = /^[\w\.\-]+\@[\w\.\-]+\.[\w.]{2,}$/;
    return (Regx.test(email));
}
function isPassword(password) {
    var Regx = /[0-9]/;
    return (Regx.test(password));

}
//auto refresh
function autoRefresh(timeoutPeriod) {
    setTimeout("location.reload(true);", timeoutPeriod);
}



