var nChecked = true;

function checkWnd(objWnd,bDontStoreNew)
{
	try
	{
		if (window.top.g_wndPopup)
			window.top.g_wndPopup.close();
		if (objWnd && objWnd != undefined && (!bDontStoreNew || bDontStoreNew == null || bDontStoreNew == undefined) )
			window.top.g_wndPopup = objWnd;
	}catch(e)
	{
		try
		{
			if (window.parent.g_wndPopup)
				window.parent.g_wndPopup.close();
			if (objWnd && objWnd != undefined && (!bDontStoreNew || bDontStoreNew == null || bDontStoreNew == undefined) )
				window.parent.g_wndPopup = objWnd;
		}catch(e){}
	}
	return objWnd;
}
function buyPages()
{
	checkWnd(window.open("addon_faxPage_index.asp","","width=350,height=400"));
}
function addressBook(nType)
{
	try
	{
		checkWnd(window.open("AddressBookIndex.asp?Type=" + escape(nType),"","width=800,height=600,scrollbars=no,resizable=yes,status=no,center=yes")); 
	}
	catch(e){}
}
function sendFaxDialog(funcCallback)
{
	try
	{
		var strWinName = "SendDialog";

		var nWidth = g_nWidthViewer;
		if (screen.width > 1024)
			nWidth = 1024;
		var nHeight = g_nHeightViewer;
		if (screen.height > 800)
			nHeight = 800;
		return checkWnd(window.open("fax_sendDialog_index.asp?func=" + escape(funcCallback),strWinName,"top=" + g_nOffset + ",left=" + g_nOffset + ",width=" + nWidth + ",height=" + nHeight + ",resizeable=1"));
	}
	catch(e){}
}
function getElementY(nObj,bBottom) 
{ 
	yPos = nObj.offsetTop; 
	tempEl = nObj.offsetParent; 
	while (tempEl != null) 
	{ 
		yPos += tempEl.offsetTop; 
		tempEl = tempEl.offsetParent; 
	}
	if (bBottom)
		yPos += nObj.offsetHeight;
	return yPos; 
} 
function getElementX(nObj,bRight) 
{ 
	xPos = nObj.offsetLeft; 
	tempEl = nObj.offsetParent; 
	while (tempEl != null) 
	{ 
		xPos += tempEl.offsetLeft; 
		tempEl = tempEl.offsetParent; 
	} 
	if (bRight)
		xPos += nObj.offsetWidth;
	return xPos; 
} 
function handleEsc(strRet)
{
	try
	{
		if (strRet == undefined)
			strRet = "-1";
		if(window.event.keyCode==27)
		{
			try
			{
				window.parent.returnValue = strRet;
				window.parent.close();
			}
			catch(e)
			{
				window.returnValue = strRet;
				window.close();
			}
		}
	}
	catch(e){}
}

function checkAll()
{
	var coll = document.getElementsByTagName("input");
	for(i=0; i < coll.length; i++) //>
	{
		if(coll[i].type =="checkbox" && coll[i].value !="1" && !coll[i].disabled)
		{
			coll[i].checked = nChecked;
		}
	}
	if(nChecked==true)
	{
		nChecked=false;
	}
	else	
	{
		nChecked=true;
	}
}
function convertItem(strFID,bCancel,nStatus)
{
	try
	{
		var strXML = "<";
		if (bCancel)
		{
			if (nStatus != 2)
			{
				if (!confirm("Are you sure you wish to cancel this conversion?"))
					return;
			}
			strXML += "CFX_CancelConvertFileReq";
		}
		else
			strXML += "CFX_ConvertFileReq";
		strXML += " FID=\"" + encodeXML(strFID) + "\"";
		strXML += " Option=\"1\"";
		strXML += " />";
		var strResponse = xmlHTTP("xmlrequest.asp",strXML);
		if (validateReturn(strResponse,"convertItem('" + strXML + "')",true))
		{
			loadXML();
		}
	}
	catch(e){}
}
function calculateTrialPeriod(nTrialPeriodExpire)
{
	var nDays = 0;

    var buffer = new Number(Date.parse( new Date() )) ;
	var nDiff = nTrialPeriodExpire - buffer;
	return new Number(nDiff/24/60/60/1000).toFixed(0);
}

function validateEmail(x)
{
	regExp = / /gi;
	x = x.replace(regExp,"");
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) 
		return true;
	else 
		return false;
}
function validateData(strData)
{
	var regExp = new RegExp("\@?\#?\&?\'?\\\"?\;?\:?\%?\!?\\$?\\^?\`?\\\\?\/?\\*?\>?\<?\\??\\|?","gi");
	return strData.replace(regExp,"");
}
function validateReturn(strResponse,strFunc, bSilent) //bSilent is used to supress the error message
{
	
	
//**TODO check for 83019 (bad CC and prompt for new info)
	if ( strResponse == null || strResponse == undefined || strResponse == "" )
	{
		if ( !bSilent)
			alert("No XML returned.");
		return false;
	}
	if (strResponse.charAt(0) == "-")
	{
		strResponse = strResponse.substr(1,strResponse.length);
			
		if ( !bSilent)
		{
		    var xmlDom = jsXML.createDOMDocument("", "");
			xmlDom.loadXML(strResponse);			
			alert(xmlDom.documentElement.getAttribute("Message") + "\r\n" + xmlDom.documentElement.getAttribute("Status"));
		}
		return false;
	}
	if (strResponse.charAt(0) == "*")
	{
		try{window.parent.top.reAuth(this.name,null,strFunc);}catch(e){window.parent.parent.reAuth(this.name,null,strFunc);}
		return false;
	}
	if ( strResponse.charAt(0) == "$" )
	{	
		
		alert("Your credit card information is no longer valid.  You must update your credit card information before continuing.");
		try
		{
			if ( window.parent.opener.location == null || window.parent.opener.location == undefined )
			{
				window.parent.location.href = "account_UpdateCreditCard.asp";
				return;
			}
			else
			{
				try{window.parent.opener.top.location.href = "account_UpdateCreditCard.asp";}catch(e){window.parent.opener.parent.location.href = "account_UpdateCreditCard.asp";}
				window.close();
				return;
			}
		}
		catch(e)
		{
			try{window.parent.location.href = "account_UpdateCreditCard.asp";}catch(e){window.parent.location.href = "account_UpdateCreditCard.asp";}
			return;
		}		
	}	
	if ( strResponse == "" || strResponse == null || strResponse == undefined )
	{
		if ( !bSilent)
			alert("Error: Data was not returned from the server.");
		return false;
	}
	return true;
}
function endTrial(bNoConfirm, bNoReload)
{
	bConfirm = true;
	if (!bNoConfirm || bNoConfirm == undefined)
		bConfirm = confirm("By clicking the 'OK' button I agree to end my Trial Period and set my account live.\n\nI understand that I will be charged for the services that I have selected.");
	if (bConfirm)
	{
		try
		{
			var strXML = "<CFX_EndTrialReq />";
			var strResponse = xmlHTTP("xmlrequest.asp",strXML);
			if (validateReturn(strResponse,"endTrial(true)"))
			{
				if ( !bNoReload )
				{
					try{window.top.location.href = window.top.location.href;}catch(e){window.parent.location.href = window.parent.location.href;}
				}	
				return true;
			}
		}catch(e){}
	}
	
	return false;
}
function auditLog(strID,strName)
{
	try
	{
		checkWnd(window.open("auditLog_index.asp?ID=" + escape(strID) + "&Name=" + escape(strName),"","height=650,width=600,status=no,titlebar=no,toolbar=no,resizable=no")); 
	}
	catch(e){}
}
function encodeXML(strXML)
{
	if (strXML == undefined || strXML == null)
		return;
	regExp = /&/gi;
	strXML = strXML.replace(regExp,"&amp;");
	regExp = /'/gi;
	strXML = strXML.replace(regExp,"&apos;");
	regExp = /"/gi;
	strXML = strXML.replace(regExp,"&quot;");
	regExp = /</gi;
	strXML = strXML.replace(regExp,"&lt;");
	regExp = />/gi;
	strXML = strXML.replace(regExp,"&gt;");
	
	return strXML;
}
function formatSize(strSizeBytes)
{
	strMega = "";
	strKilo = "";
	strByte = "";
	strLabel = " Bytes";

	nSize = new Number(strSizeBytes);
	if (nSize >= 1024*1024*1024*1024)
	{
		nSize = nSize / (1024*1024*1024*1024);
		nSize = nSize.toFixed(1);
		strLabel = " TB";
	}
	else if (nSize >= 1024*1024*1024)
	{
		nSize = nSize / (1024*1024*1024);
		nSize = nSize.toFixed(1);
		strLabel = " GB";
	}
	else if (nSize >= 1024*1024)
	{
		nSize = nSize / (1024*1024);
		nSize = nSize.toFixed(1);
		strLabel = " MB";
	}
	else if (nSize >= 1024)
	{	
		nSize = nSize / 1024;
		nSize += 1;
		nSize = nSize.toFixed(1);
		strLabel = " KB";
	}
	else
		nSize = nSize.toFixed(1);

	strSizeBytes = nSize.toString() + strLabel;
	return strSizeBytes;
}
function normalizeString(strString,nDigits)
{
	try
	{
		if (strString.length < nDigits)
		{
			for (var i = 0; i < nDigits - strString.length; i++)
			{
				strString = "0" + strString;
			}
		}
		return strString;
	}catch(e){}
}

function formatDate(nDate,bFax)
{
	var dDate = new Date(new Number(nDate));
	var strDate = "";
	if (bFax)
	{
		strYear = dDate.getYear();
		if (strYear < 1900)
			strYear += 1900;
		strAMPM = "AM";
		strHours = dDate.getHours();
		if (new Number(strHours) > 12)
		{
			strAMPM = "PM";
			strHours = new Number(strHours) - 12;
		}
		strMinutes = dDate.getMinutes();
		strSeconds = dDate.getSeconds();
		strDate = new Number(dDate.getMonth())+1 + "/" + dDate.getDate() + "/" + strYear + " " + strHours.toString() + ":" + normalizeString(strMinutes.toString(),2) + ":" + normalizeString(strSeconds.toString(),2) + " " + strAMPM;
	}
	else
	{
		try
		{	
			if(g_AdminDateFormat)
			{
				strYear = dDate.getYear();
				if (strYear < 1900)
					strYear += 1900;
				strAMPM = "AM";
				strHours = dDate.getHours();
				if (new Number(strHours) > 12)
				{
					strAMPM = "PM";
					strHours = new Number(strHours) - 12;
				}
				strMinutes = dDate.getMinutes();
				strSeconds = dDate.getSeconds();
				strDate = new Number(dDate.getMonth())+1 + "/" + dDate.getDate() + "/" + strYear + " " + strHours.toString() + ":" + normalizeString(strMinutes.toString(),2) + ":" + normalizeString(strSeconds.toString(),2) + " " + strAMPM;
			}
		}
		catch(e)
		{
			strDate = dDate.toLocaleString();
		}
	}
	return strDate;
}
function formatPage()
{
	try
	{	
		var nodeList = document.getElementsByTagName("td");
		for (var i = 0; i < nodeList.length; i++)
		{
			strNodeID = nodeList[i].id;
			strNodeValue = nodeList[i].getAttribute("value");
			if (strNodeID.substr(0,8) == "td_size_")
				nodeList[i].innerHTML = formatSize(strNodeValue);
			else if (strNodeID.substr(0,8) == "td_date_")
				nodeList[i].innerHTML = formatDate(strNodeValue,strNodeID.substr(8,1)=="_");
		}
		
		nodeList = document.getElementsByTagName("font");
		for (var i = 0; i < nodeList.length; i++)
		{
			strNodeID = nodeList[i].id;
			strNodeValue = nodeList[i].innerHTML;
			if (strNodeID.indexOf("size_") > -1 )
				nodeList[i].innerHTML = formatSize(strNodeValue);
			else if (strNodeID.indexOf("date_") > - 1)
				nodeList[i].innerHTML = formatDate(strNodeValue,strNodeID.substr(5,1)=="_");
		}
	}catch(e){}
}
function formatFaxNumber(strNumber)
{
	try
	{
		strReturn = "";
		if (strNumber != "")
			strReturn = strNumber.substr(0,3) + "-" + strNumber.substr(3,3) + "-" + strNumber.substr(6,4);
		else
			strReturn = "pending allocation";
		return strReturn;
	}catch(e){}
}
g_nOffset = 20;
g_nWidthViewer = 800 - 2*g_nOffset;
g_nHeightViewer = 600 - 2*g_nOffset;

function xmlHTTP(url,strXML) 
{
	var g_xmlDocReq;
	if (window.XMLHttpRequest)
		g_xmlDocReq = new XMLHttpRequest();
	else if (window.ActiveXObject) 
		g_xmlDocReq = new ActiveXObject("Microsoft.XMLHTTP");
	if (g_xmlDocReq) 
	{
	    if ( url == undefined || url == "" )
	        url = "xmlrequest.asp";
	        
		g_xmlDocReq.open("POST", url, false);
//		g_xmlDocReq.SetRequestHeader("Content-Type", "text/html; charset=iso-8859-1")
		g_xmlDocReq.send(strXML);
		return g_xmlDocReq.responseText;		
	}
}

/*** XML CLASS ***/
//Possible prefixes ActiveX strings for DOM DOcument
var ARR_ACTIVEX = ["MSXML4.DOMDocument", "MSXML3.DOMDocument", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XmlDom"];

//When the proper prefix is found, store it here
var STR_ACTIVEX = "";

//browser detection
var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1;
var isMoz = document.implementation && document.implementation.createDocument;
var isMac = navigator.appVersion.toLowerCase().indexOf("mac") > -1;
//-----------------------------------------------------------------
// IE Initialization
//-----------------------------------------------------------------

//if this is IE, determine which string to use
if (isIE) {
    //define found flag
    var bFound = false;
    
    //iterate through strings to determine which one to use (NCZ, 1/30/02)
    for (var i=0; i < ARR_ACTIVEX.length && !bFound; i++) {
    
        //set up try...catch block for trial and error of strings (NCZ, 1/30/02)
        try {
        
            //try to create the object, it will cause an error if it doesn't work (NCZ, 1/30/02)
            var objXML = new ActiveXObject(ARR_ACTIVEX[i]);
            
            //if it gets to this point, the string worked, so save it and return
            //the DOM Document (NCZ, 1/30/02)
            STR_ACTIVEX = ARR_ACTIVEX[i];
            bFound = true                
        
        } catch (objException) { 
        } //End: try
    } //End: for

    //if we didn't find the string, send an error (NCZ, 1/30/02)
    if (!bFound)
       throw "No DOM DOcument found on your computer."

} //End: if

//-----------------------------------------------------------------
// Mozilla Initialization
//-----------------------------------------------------------------
if (isMoz) {
    
    //add the loadXML() method to the Document class
    Document.prototype.loadXML = function(strXML) {
    
        //change the readystate
        changeReadyState(this, 1);

        //create a DOMParser
        var objDOMParser = new DOMParser();
        
        //create new document from string
        var objDoc = objDOMParser.parseFromString(strXML, "text/xml");
        
        //make sure to remove all nodes from the document
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);
            
        //add the nodes from the new document
        for (var i=0; i < objDoc.childNodes.length; i++) {
            
            //import the node
            var objImportedNode = this.importNode(objDoc.childNodes[i], true);
            
            //append the child to the current document
            this.appendChild(objImportedNode);
        
        } //End: for
        
        //we can't fire the onload event, so we fake it
        handleOnLoad(this);
        
    } //End: function
 
    //add the getter for the .xml attribute
    Node.prototype.__defineGetter__("xml", _Node_getXML);
    
    //add the readystate attribute for a Document
    Document.prototype.readyState = "0";
    
    //save a reference to the original load() method
    Document.prototype.__load__ = Document.prototype.load;

    //create our own load() method
    Document.prototype.load = _Document_load;
    
    //add the onreadystatechange attribute
    Document.prototype.onreadystatechange = null;
    
    //add the parseError attribute
    Document.prototype.parseError = 0;
    
} //End: if

function jsXML(){}
jsXML.createDOMDocument = function(strNamespaceURI, strRootTagName) {

    //variable for the created DOM Document
    var objDOM = null;
    
    //determine if this is a standards-compliant browser like Mozilla
    if (isMoz) {
    
        //create the DOM Document the standards way
        objDOM = document.implementation.createDocument(strNamespaceURI, strRootTagName, null);    
    
        //add the event listener for the load event
        objDOM.addEventListener("load", _Document_onload, false);
        
    } else if (isIE) {
    
        //create the DOM Document the IE way
        objDOM = new ActiveXObject(STR_ACTIVEX);

        //if there is a root tag name, we need to preload the DOM
        if (strRootTagName) 
		{
            if (strNamespaceURI) {
                objDOM.loadXML("<" + strRootTagName + " xmlns=\"" + strNamespaceURI + "\" />");
            } else {
                objDOM.loadXML("<" + strRootTagName + "/>");        
            }
        
        }
    }
    
    //return the object
    return objDOM;
}
//add the transformNode() method
var g_strBrandPath = "blue";
var arrImages = new Array;
function preLoadImages()
{
	var arrImagesPath = new Array("document.gif","folder.gif","rename.gif","delete_icon.gif","arrow_up.gif","arrow_dwn.gif","download_icon.gif","icon_help.gif","audit.gif","convert.gif");
	getBranding();
	for(i = 0; i < arrImagesPath.length; i++)
	{
		arrImages[i] = new Image();
		arrImages[i].src = "../skin/" + g_strBrandPath + "/images/" + arrImagesPath[i];
	}
}
function getBranding()
{
	var strURL = location.href.substr(12);
	strURL = strURL.substr(0,strURL.indexOf("/"));
	if (strURL == "greggfax.com")
	{
		g_strBrandPath = "greggfax";
		return true;
	}
	else if (strURL == "faxafile.com")
	{
		g_strBrandPath = "faxafile";
		return true;
	}
	return false;	//non-branded
}
jsXML.transformXSL = function(xmlDoc,strXSL) 
{
	xmlDoc.documentElement.setAttribute("SortSelect","@FileSize");
	try
	{
		var strPageHTML = "";
		var strXSLBuffer = strXSL;
		if (isMoz) 
		{
			var xsltProcessor = new XSLTProcessor();
			//xslStylesheet = myXMLHTTPRequest.responseXML;
			xslStylesheet = jsXML.createDOMDocument("","");

			var myXMLHTTPRequest = new XMLHttpRequest();
			myXMLHTTPRequest.open("GET", strXSL, false);
			myXMLHTTPRequest.send("");
			strXSLBuffer = myXMLHTTPRequest.responseText;
			if (getBranding())
			{
				var regExp = new RegExp("blue/","gi");
				strXSLBuffer = strXSLBuffer.replace(regExp,g_strBrandPath + "/");
			}
			xslStylesheet.loadXML(strXSLBuffer);
			
			xsltProcessor.importStylesheet(xslStylesheet);

			var fragment = xsltProcessor.transformToFragment(xmlDoc, document);
			var regExp = new RegExp("a0:","gi");
			strPageHTML = fragment.xml.replace(regExp,"");
		}
		else
		{
			var xsl = new ActiveXObject("Microsoft.XMLDOM");
			xsl.async = false;

			var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			xmlhttp.Open("GET", strXSL, false);
			xmlhttp.Send();
			strXSLBuffer = xmlhttp.responseText;
			if (getBranding())
			{
				var regExp = new RegExp("blue/","gi");
				strXSLBuffer = strXSLBuffer.replace(regExp,g_strBrandPath + "/");
			}
			xsl.loadXML(strXSLBuffer);
			strPageHTML = xmlDoc.transformNode(xsl);
		}
		return strPageHTML;
	}catch(e){}
}
function _Node_getXML() {
    
    //create a new XMLSerializer
    var objXMLSerializer = new XMLSerializer;
    
    //get the XML string
    var strXML = objXMLSerializer.serializeToString(this);
    
    //return the XML string
    return strXML;
}

function _Document_load(strURL) {

    //set the parseError to 0
    this.parseError = 0;

    //change the readyState
    changeReadyState(this, 1);
    
    //watch for errors
    try {
        //call the original load method
        this.__load__(strURL);
        
    } catch (objException) {
    
        //set the parseError attribute
        this.parseError = -9999999;
        
        //change the readystate
        changeReadyState(this, 4);

    } // End: try...catch
}
function _Document_onload() {

    //handle the onload event
    handleOnLoad(this);
}
function handleOnLoad(objDOMDocument) {
    //check for a parsing error
    if (!objDOMDocument.documentElement || objDOMDocument.documentElement.tagName == "parsererror")
        objDOMDocument.parseError = -9999999;

    //change the readyState
    changeReadyState(objDOMDocument, 4);
}
function changeReadyState(objDOMDocument, iReadyState) {

    //change the readyState
    objDOMDocument.readyState = iReadyState;
    
    //if there is an onreadystatechange event handler, run it
    if (objDOMDocument.onreadystatechange != null && typeof objDOMDocument.onreadystatechange == "function")
        objDOMDocument.onreadystatechange();
}


document.write("<script language='javascript'>try{preLoadImages()}catch(e){}</script>");