var submitcount = 0;
var calcchanged = 0;
var searchno = 0;
var formset = false;

function delformelement(childelement)
{
	var nodetodel = document.getElementById('srchel'+childelement);
	nodetodel.parentNode.removeChild(nodetodel);
}

function AddFormItem(colspan, searchselect, field2sel, initialsearchno) { 


	div=document.getElementById("formitems"); 
	
	if (!formset)
	{
		searchno = initialsearchno;
		formset = true;
	}

	searchno += 1;
	var newitem = '<input type="hidden" name="searches[]" value="'+searchno+'">';
	newitem += '<table class="formgrid">';
	newitem += '<tr>';
	newitem += '<td class="ssearch">';
	newitem += '<input type="radio" name="logic'+searchno+'" value="AND" checked>AND &nbsp;';
	newitem += '<input type="radio" name="logic'+searchno+'" value="OR">OR &nbsp;';
	newitem += '<input type="radio" name="logic'+searchno+'" value="NOT">NOT &nbsp;';
	newitem += '</td>';
	newitem += '<td class="sfilter" colspan="2">&nbsp;</td>';
	newitem += '<td class="scalc" colspan="2">&nbsp;</td>';
	newitem += '<td class="scalc" colspan="1">&nbsp;</td>';
	newitem += '<td class="sgrowth" colspan="1">&nbsp;</td>';
	newitem += '</tr>';
	newitem += '<tr>';
	newitem += '<td class="ssearch">'+searchselect.replace("~~name~~","searchfield"+searchno)+'</td>';
	newitem += '<td class="sfilter"><select name=mathcomp'+searchno+'>';
	newitem += '<option value="" selected></option>';
	newitem += '<option value="&gt;">&gt;</option>';
	newitem += '<option value="&lt;">&lt;</option>';
	newitem += '<option value="&#61;">&#61;</option>';
	newitem += '</select></td>';
	newitem += '<td class="sfilter"><input type="text" size="7" name="criteria'+searchno+'" value=""></td>';

	newitem += '<td class="scalc"><select name="mathop'+searchno+'">';
	newitem += '<option value="" selected></option>';
	newitem += '<option value="/">/</option>';
	newitem += '<option value="+">+</option>';
	newitem += '<option value="-">-</option>';
	newitem += '<option value="*">*</option>';
	newitem += '</select></td>';

	newitem += '<td class="scalc">'+field2sel.replace("~~name~~","field2sel"+searchno)+'</td>';
	newitem += '<td class="scalc"><select name=ffactor'+searchno+'>';
	newitem += '<option value="1" selected>1</option>';
	newitem += '<option value="100">100</option>';
	newitem += '<option value="1000">1000</option>';
	newitem += '</select></td>';
	newitem += '<td class="sgrowth"><select name="cgrowth'+searchno+'">';
	newitem += '<option value="" selected></option>';
	newitem += '<option value="2">1 year</option>';
	newitem += '<option value="4">3 year average</option>';
	newitem += '</select></td>';
	var rembutton = '<td><input type="button" class="smallbutton" onclick="javascript:delformelement('+searchno+');" value="remove"></td>';
	newitem += rembutton;
	newitem += '</tr>';
	newitem += '</table>';

	newnode=document.createElement('div'); 
	newnode.innerHTML=newitem; 
	newnode.setAttribute('id', 'srchel'+searchno);
	newnode.setAttribute('ID', 'srchel'+searchno);
	add_div=document.getElementById("div_addformitem"); 
	div.insertBefore(newnode, add_div);

} 

function AddDocRow() { 


        var theTable = document.getElementById('doclist');

        // append new row to the end of the table
        var newRow = theTable.insertRow(theTable.rows.length-2);
        // give the row its own ID
        
        // declare cell variable
        var newCell;
        
        // an inserted row has no cells, so insert the cells
        newCell = newRow.insertCell(0);

        // give this cell its own id
        newCell.id = newCell.uniqueID;

        newCell.innerHTML = '&nbsp;';


        // reuse cell var for next cell insertion

        newCell = newRow.insertCell(1);
        newCell.id = newCell.uniqueID;

        newCell.innerHTML = '&nbsp;';
	
        // reuse cell var for next cell insertion
        newCell = newRow.insertCell(2);
        newCell.id = newCell.uniqueID;

        newCell.innerHTML = '<input name="newdescription" type="text" size="40">';

        // reuse cell var for next cell insertion
        newCell = newRow.insertCell(3);
        newCell.id = newCell.uniqueID;

        newCell.innerHTML = '<input name="newsourceURL" type="text" size="40">';

        // reuse cell var for next cell insertion
        newCell = newRow.insertCell(4);
        newCell.id = newCell.uniqueID;

        newCell.innerHTML = '<input type="file" name="newfilename">';

        // reuse cell var for next cell insertion
        newCell = newRow.insertCell(5);
        newCell.id = newCell.uniqueID;

        newCell.innerHTML = '&nbsp;';

	return true;

} 

function pagecalced() {                       // has there been a change in the figures?

	if (calcchanged == 0)
		return false;

	return true;
}


function checksubmit() {                       // field validation -

	if (submitcount == 0)
	{
		submitcount++;
		return true;
	}
	else 
	{
		alert("Please wait. This page is being processed..");
		return false;
	}
}

function firsttextbox()
{
	if (document.forms.length > 0) 
	{
		var el, type, i = 0, j, els = document.forms[0].elements;
		while (el = els[i++]) 
		{
			j = 0;
			while (type = arguments[j++]) 
				if (el.type == type) return el.name;
		}
	}
	return null;
}
	
function confirmmessage(message, functoconfirm)
{
	// functoconfirm passed as string.
	// if it exists, then executing it 
	// will return a true/false
	// false means that no confirmation
	// message is required
	
	// used mainly to indicate that
	// the calculations on a form 
	// have been updated, and that
	// resetting will lose those changes
	if (!(null == functoconfirm))
	{
		if (!("undefined" == functoconfirm) && eval(functoconfirm))
		{
			return confirm(message);
		}
	}
	return true;
}
	

function confirmnav(link, message, functoconfirm)
{
	// functoconfirm passed as string.
	// if it exists, then executing it 
	// will return a true/false
	// false means that no confirmation
	// message is required
	
	// used mainly to indicate that
	// the calculations on a form 
	// have been updated, and reports 
	// that navigation away from a page will
	// result in loss of that data
	if (!(null == functoconfirm))
	{
		if (!("undefined" == functoconfirm) && !eval(functoconfirm))
		{
			this.location = link;
			return true;
		}
	}
	
	var resp = confirm (message);
	if (!resp)
	{
		return false;
	}
	this.location = link;
	return true;
	
}
	
function setFocus() 
{
	if ((document.forms.length > 0) && document.getElementById("noautofocus") == null)
	{
		var el, type, i = 0, j, els = document.forms[0].elements;

		while (el = els[i++]) 
		{
			j = 0;
			while (type = arguments[j++]) 
				if (el.type == type) return el.focus();
		}
	}
}

function calcinvassets(frm, invassetid, thiselement)
{
	calcchanged = 1;
	var listoftotals = frm.listoftotals.value;
	var totalsarray = frm.listoftotals.value.split(";");
	thiselement.value = filterinput(round_decimals(pF(thiselement.value), 3));

	for (var i=0; i < totalsarray.length; ++i) 
	{
		var thistotal = frm.elements[totalsarray[i]].value.split(";");
		var thisvalue = 0;
		for (var j=0; j < thistotal.length; ++j) 
		{
			var cellname = 'fedit'+invassetid+'_'+thistotal[j];
			thisvalue += pF(frm.elements[cellname].value);
		}
		frm.elements['fedit'+invassetid+'_'+totalsarray[i]].value = round_decimals(thisvalue, 3);
	}

}

function CalculateTotals(frm, thiselement, thisformat) {

	calcchanged = 1;
	thisval = filterinput(thiselement.value, thisformat);


	if (thisformat == "integer")
		thiselement.value = round_decimals(pF(thisval), 0);
	else if (thisformat == "float" || thisformat == "number")
		thiselement.value = round_decimals(pF(thisval), 3);
	else
		thiselement.value = thisval;

	var order_total = 0;

	// Run through all the form fields
	for (var i=0; i < frm.elements.length; ++i) 
	{
	
		// Get the current field
		form_field = frm.elements[i];
		
		// Get the field's name
		fieldname = form_field.name;
		
		// Is it a "total" field?

		if (fieldname.substring(0,6) == "ftotal") 
		{
	            	// If so, update the value
	
			var exec_str = '';
			
			// formfield.value
	
			var elarray = form_field.value.split(";");
			var sumtotal = 0;
			var newnum = 0;
			for (var e=0; e < elarray.length; ++e) 
			{
				newnum = eval(elarray[e]);

				if (isNumber(newnum))
				{
					sumtotal += eval(elarray[e]);
				}
			}
	
			sumtotal = round_decimals(sumtotal, 3)
			exec_str = 'frm.'+fieldname.substring(6)+'.value=\''+sumtotal+'\'';

			eval(exec_str);
	        }
	}
}


function pF(mydata)
{
	
	if (isNaN(parseFloat(mydata)))
		return 0;

	var retval = parseFloat(mydata);
		
	return retval;
}



function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

function alphanum(){
	
	var alphastr = '';
	
	alphastr += String.fromCharCode(32);	// space

	for (var i = 40; i < 60; i++)
		alphastr += String.fromCharCode(i);

	alphastr += String.fromCharCode(61);

	for (var i = 64; i < 91; i++)
		alphastr += String.fromCharCode(i);

	alphastr += String.fromCharCode(93);

	alphastr += String.fromCharCode(95);

	for (var i = 97; i < 123; i++)
		alphastr += String.fromCharCode(i);
	
	return alphastr;
}


function filterinput(mydata, mydatatype){
	
	// strip mydata of any incorrect chars
	
	
	if (mydatatype == 'number' || mydatatype == 'float')
		var allowedchars = '-0123456789.';

	else if(mydatatype == 'integer')
		var allowedchars = '-0123456789';
	else
		var allowedchars = alphanum();

	var returnstring = "";
	
	for (var i = 0; i < mydata.length; i++) 
	{  
		var mychar = mydata.charAt(i);
		if (allowedchars.indexOf(mychar) != -1)
			returnstring += mychar;
	}

	if ((mydatatype == 'float' || mydatatype == 'integer' || mydatatype == 'number') && isNaN(parseFloat(mydata)))
	{	
		if (!(null == mydata))
			alert('Error in input. \''+mydata+'\' is not a valid number');
	}

	return returnstring;		
}

function statbuttontarget(tablename, fieldname, fieldlabel) {
	targeturl = 'fundstat.php?tablename='+tablename+'&fieldname='+fieldname+'&fieldlabel='+fieldlabel;
	newwin = popupcentrewindow(targeturl, 350, 300, "location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes", "Statistics");
	newwin.focus();
	
}


function popupcentrewindow(URL, w, h, props, name) {

	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;

	var windowprops = props +",left=" + l + ",top=" + t + ",width=" + w + ",height=" + h;

	return window.open(URL, name, windowprops);

}


function lookupbuttontarget(category, refid, descid) {

//	alert('dsffds');
//	targeturl = 'lookup.php?eledesc='+descid+'&eleref='+refid+'&elecon='+category;
//	newwin = popupcentrewindow(targeturl, 350, 300, "location=no,scrollbars=no,menubars=yes,toolbars=no,resizable=yes", "Lookup");
//	newwin = window.showModalDialog(targeturl);
//	newwin.focus();


	targeturl = 'lookup.php?eledesc='+descid+'&eleref='+refid+'&elecon='+category;
	newwin = popupcentrewindow(targeturl, 450, 400, "location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=yes");
	newwin.focus();

}

function seteditbutton(appid, buttonindex, persid) {

	targeturl = 'seteditor.php?app='+appid+'&idx='+buttonindex+'&persid='+persid;
	newwin = popupcentrewindow(targeturl, 450, 400, "location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=yes");
	newwin.focus();

}

function checkrequired(which) 
{
	var pass=true;
	var emailok = false;
	
	if (document.images) 
	{
		for (i=0;i<which.length;i++) 
		{
			var tempobj=which.elements[i];
			if (tempobj.name.substring(0,8)=="required") 
			{
				if (tempobj.name == "requiredemail")
				{
					// check valid format
					emailok = checkEmail(tempobj.value)
				}
					
				if (((tempobj.type=="text"||tempobj.type=="textarea")&&tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s" && tempobj.selectedIndex==0)) 
				{
					pass=false;
					break;
         			}
      			}
   		}
	}
	if (!pass) 
	{
		shortFieldName=tempobj.name.substring(8,30);
		alert("Please make sure the "+shortFieldName+" field is properly completed.");
		return false;
	}
	else
	{
		if (emailok)
			return true;
		else
		{
			alert("your email address does not appear to be in the correct format");
			return false;
		}
	}
}


function emailCheck (emailStr) {

<!-- V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
<!-- Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com) -->


var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

alert("Email address seems incorrect (check @ and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("Ths username contains invalid characters.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Ths domain name contains invalid characters.");
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

alert("The username doesn't seem to be valid.");
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("The domain name does not seem to be valid.");
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("The address must end in a well-known domain or two letter " + "country.");
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
alert("This address is missing a hostname!");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}



/***********************************************
* IFrame SSI script II- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
* Visit DynamicDrive.com for hundreds of original DHTML scripts
* This notice must stay intact for legal use
***********************************************/

//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
var iframeids=["myframe"]

//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
var iframehide="no"

var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 16 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeCaller() {
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++){
if (document.getElementById)
resizeIframe(iframeids[i])
//reveal iframe for lower end browsers? (see var above):
if ((document.all || document.getElementById) && iframehide=="no"){
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i])
tempobj.style.display="block"
}
}
}

function resizeIframe(frameid){
var currentfr=document.getElementById(frameid)
if (currentfr && !window.opera){
currentfr.style.display="block"
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight; 
else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
if (currentfr.addEventListener)
currentfr.addEventListener("load", readjustIframe, false)
else if (currentfr.attachEvent){
currentfr.detachEvent("onload", readjustIframe) // Bug fix line
currentfr.attachEvent("onload", readjustIframe)
}
}
}

function readjustIframe(loadevt) {
var crossevt=(window.event)? event : loadevt
var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
if (iframeroot)
resizeIframe(iframeroot.id);
}

function loadintoIframe(iframeid, url){
if (document.getElementById)
document.getElementById(iframeid).src=url
}

if (window.addEventListener)
window.addEventListener("load", resizeCaller, false)
else if (window.attachEvent)
window.attachEvent("onload", resizeCaller)
else
window.onload=resizeCaller

