// Javascript routines for keepmystats.com
function submitform() {
/*	submitform		Function checks for existance of document.saved before submitting the form
*/

	var action		= "SAVE";
	var dosubmit	= true;
	if (arguments.length>=1) {
		action = arguments[0];
	}
	if (arguments.length==2) {
		/* don't need to issue submit command for a submit button */
		dosubmit = (arguments[1].type!="submit");
	}
	if (document.forms[0].formaction.value!="") {
		alert("This Form Has Already Been Submitted.");
		return false;
	}
	else {
		document.forms[0].formaction.value = action;
		if (dosubmit) {
			document.forms[0].submit();
		}
	}
	return true;
}


function closewindow() {
/*	closewindow		Closes the current window and performs the following action
						based on values of two optional parameters.  If no parameters are included
						then the just the window is closed:
	Parameters:
		action:		CLOSE				=> no action (same as no arguments)
						CLOSESUBMIT		=> submit form[0] of opener document
						CLOSEREFRESH	=> refresh opener document
						CLOSEREDIRECT	=> redirect opener document
		urlstr:		url for CLOSEREDIRECT, formaction.value for CLOSESUBMIT, otherwise ignored
*/

	var args		= closewindow.arguments;
	// default values
	var action	= "";
	var urlstr	= "";
	// assign from passed arguments
	if (args.length>0)
		action	= args[0].toUpperCase();
	if (args.length>1)
		urlstr	= args[1];
	// Perform requested action if present and opener window still around
	if (opener) {
		if (action!="") {
			switch (action) {
				case "CLOSESUBMIT":
					if (urlstr=="")
						alert("closewindow:  No formaction supplied with CLOSESUBMIT argument.");
					else
						opener.document.forms[0].formaction.value = urlstr;
					break;
				case "CLOSEREFRESH":
					opener.document.location.href = opener.document.location.href;
					break;
				case "CLOSEREDIRECT":
					if (urlstr=="")
						alert("closewindow:  No URL supplied with CLOSEREDIRECT argument.");
					else {
						opener.document.location.href = urlstr;
					}
					break;
			}
		}
	}
	// close the window
	top.close();
}

function popupwindow(urlstr,winname,t,l,w,h) {
/*	popupwindow		Pops up a window with the passed url page.  If dimension parameters
						are not included, the windowdimensions() is called.
	Parameters
	urlstr			Url page to load in the window
	winname			Name of the window to be opened
	t					(optional)  Top dimension of the window.
	l					(optional)  Left dimension of the window.
	w					(optional)  Width dimension of the window.
	h					(optional)  Height dimension of the window.
*/

	var a_url	= urlstr.toLowerCase().split(".");
	if (popupwindow.arguments.length<2) {
		var winname = a_url[0];
	}	else {
		if (winname=="") {
			winname = a_url[0];
		}
	}
	if (popupwindow.arguments.length<=2) {
		var windim	= windowdimensions(winname);
		var a_dims	= windim.split(",");
		var t			= a_dims[0];
		var l			= a_dims[1];
		var w			= a_dims[2];
		var h			= a_dims[3];
	}
	// add random number to window name to allow simultaneous open windows for certain URLs
	if (winname=="lookup" || winname=="edit_salesreps") {
		winname = winname+replace(Math.random().toString(10),".","");
	}
	open(urlstr,winname,"toolbar=no,directories=no,menubar=no,resizable=yes,screenX="+t+",screenY="+l+",top="+t+",left="+l+",width="+w+",height="+h+",location=no,scrollbars=yes");
}

function windowdimensions(winname) {
/*	windowdimensions	Returns a comma delimited string of top,left,width,height corresponding
							to the value of winname.
	Parameters
	winname				template name of the page to load in a popup window.
*/

	var retval = "75,10,400,280";
	switch (winname) {
		case "statdefs":
			retval = "75,10,525,430";
			break;
	}
	
	return retval;	
}

function replace(s, sub1, sub2) {
/*	replace		Given a string and 2 substrings, returns a string which is calculated
					by replacing all occurances of sub1 in s with sub2.
	Parameters:
	s				original string
	sub1			substring to search for in s
	sub2			substring to replace sub1
*/
	var split = s.split(sub1);
	var retval = split[0];
	var i;
	for (i=1;i<=split.length-1;i++) {
		retval = retval + sub2 + split[i];
	}
	return retval;
}

function lookup() {
/*	lookup			function opens a window with lookup.cfm as the url.  Builds the URL string
						with parameters for lookup.cfm.
	Parameters:
	lu_t				top dimension of window.
	lu_l				left dimension of window.
	lu_w				width dimension of window.
	lu_h				height dimension of window.
	(see arglist)	remaining arguments are defined below by arglist.  See lookup.cfm for
						explanation of the parameters.
*/

	// process function parameters into url parameters
	var url		= "lookup.cfm?";
	var delim	= "";
	var arglist = "size,mode,prmpt,sql,val,disp,fill,qry,rec,tab,obj,page,key";
	var a_names	= arglist.split(",");
	if (arguments.length!=a_names.length+4) {
		alert("Error in call to Lookup().  Expecting "+a_names.length+4+" parameters.");
	}
	else {
		var skipnum = 4;
		// assign window sizes from first 4 parameters
		var lu_t = arguments[0];
		var lu_l = arguments[1];
		var lu_w = arguments[2];
		var lu_h = arguments[3];
		// add parameters to url
		for (i=0;i<a_names.length;i++) {
			url	= url + delim + "lkup_" + a_names[i] + "=" + arguments[i+skipnum];
			delim	= "&";
		}
		// open lookup window 
		url = replace(url," ","%20");
		popupwindow(url,lu_t,lu_l,lu_w,lu_h);
	}
}

function listaction() {
/*	listaction			Calculates the URL corresponding to the action parameter and the value
							portion of the select object and calls popupwindow()
	Parameters:
	selobjname			name of the select object (the list we are maintaining)
	action				string for the action= parameter
	popupflag			(optional default=false) 
*/

	
	if (listaction.arguments.length<2) {
		alert("listaction:  Error - Expecting At Least 2 Arguments.");
		return;
	}
	var objname	= listaction.arguments[0];
	var action 	= listaction.arguments[1];
	if (listaction.arguments.length=3) {
		var popupflag = listaction.arguments[2];
	}
	else {
		var popupflag = false;
	}
	/* does the named select object and its associated fields exist? */
	if (!eval("document.forms[0]."+objname)) {
		alert("listaction:  Error - Select List "+objname+" Not Present.");
		return;
	}
	if (!eval("document.forms[0]."+objname+"_actionpage")) {
		alert("listaction:  Error - Field "+objname+"_actionpage Not Present.");
		return;
	}
	if (!eval("document.forms[0]."+objname+"_prompt")) {
		alert("listaction:  Error - Field "+objname+"_prompt Not Present.");
		return;
	}
	var selobj = eval("document.forms[0]."+objname);
	if (action=="ADD") {
		var id	= "0";
	}
	else {
		if (selobj.selectedIndex==-1) {
			alert("Please Highlight At Least One Item In The List Before Clicking Edit Or Delete.");
			return;
		}
		var id	= selobj.options[selobj.selectedIndex].value;
		if (action=="DELETE") {
			var desc = selobj.options[selobj.selectedIndex].text;
			var prmpt = eval("document.forms[0]."+objname+"_prompt.value");
			if (!confirm("Are You Sure You Want To Delete "+prmpt+" '"+desc+"'?")) {
				return;
			}
		}
	}
	var urlstr 	= eval("document.forms[0]."+objname+"_actionpage.value");
	if (urlstr.indexOf("=")==0) {
		urlstr = eval(urlstr.substring(1,urlstr.length))+"&";
	} else {
		urlstr = urlstr+"?";
	}
	urlstr = urlstr+"action="+action+"&id="+id;
	if (popupflag) {
		popupwindow(urlstr);
	}
	else {
		if (document.dummyform) {
/*			if (urlstr.indexOf("?")!=-1) {
				var a_urlparts	= urlstr.split("?");
				document.dummyform.action				= a_urlparts[0];
				document.dummyform.linkvals.value	= "&"+a_urlparts[1];
			} else {
				document.dummyform.action = urlstr;
			}*/
			document.dummyform.method	= "post";
			document.dummyform.action 	= urlstr;
			document.dummyform.submit();
		} else {
			var linknum = findlink("dummylink");
			if (linknum==-1 || navigator.userAgent.indexOf('Firefox')!=-1) {
				document.location.href = urlstr;
			} else {
				document.links[linknum].href = urlstr;
				document.links[linknum].click();
			}
		}
	}
}


function findlink(linkname) {
/*	findlink		function searches the links array for a link with name linkname
					and returns the index of the link.  Returns -1 if not found
*/
	
	var retval = -1;
	var i = 0;
	while (retval==-1 && i<document.links.length) {
		if (document.links[i].name==linkname) {
			retval = i;
		}
		i++;
	}
	return retval;

}


function openhelp() {
/*	openhelp		function determines the helptopic from either the form.formpage object
					or the window name if available.  Otherwise undefined is used.
*/
	
	var htopic = "undefined";
	if (openhelp.arguments.length==1) {
		htopic = openhelp.arguments[0];
	}
	else {
		if (document.forms[0]) {
			if (document.forms[0].formpage) {
				htopic = document.forms[0].formpage.value;
			}
		}
		else {
			if (window.name!="") {
				htopic = window.name;
			}
		}
	}
	popupwindow("help.cfm?topic="+htopic);
}

function setupdatedrec(metaname,recnum) {
/*	setupdatedrec		Given a metaname and a record number (recnum), adds the recnum to the
							metaname_modreclist field (if it exists).
*/

	if (recnum=="") {
		recnum = "Y";
	}
	if (recnum.charAt(0)!="N") {
		if (eval("document.forms[0]."+metaname+"_modreclist")) {
			var recobj = eval("document.forms[0]."+metaname+"_modreclist");
			recobj.value = listappend(recobj.value,recnum,",",true);
		}
	}
	return true;
}

function onpageload() {
/*	onpageload		function executed when page is loaded.  Performs 3 functions:
						1.  If form.formmessage exists and is not blank, pops up an alert window 
								with the contents of form.formmessage.
						2.  If form.formfunc exists and is not blank, evaluates the expression
								specified by form.formfunc.
						3.  If form.formfocus exists and is not blank, places focus on the field
								specified by form.formfocus.
						Any of these functions can be activated by setting the corresponding 
						request.formprocess value.
*/

	if (document.forms.length>0) {
		/* defaults */
		var msg = ""
		var fld = -1
		var func = ""
		/* scan fields for message, function, and focus values */
		if (typeof(document.forms[0].formmessage)=="object")
			msg = document.forms[0].formmessage.value;
		if (typeof(document.forms[0].formfocus)=="object") {
			if (document.forms[0].formfocus.value!="") {
				fld = eval("document.forms[0]."+document.forms[0].formfocus.value);
				document.forms[0].formfocus.value = "";
			}
		}
		if (typeof(document.forms[0].formfunc)=="object") {
			func = document.forms[0].formfunc.value;
			if (func.charAt(func.length-1)=="*") { 
				func = func.substring(0,func.length-1);
				fld = "";
			}
		}
		/* display message */
		if (msg!="") {
			alert(msg);
		}
		/* run function */
		if (func!="") {
			if (func=="goback") {
				history.go(-1);
			}
			else {
				eval(func);
			}
		}
		/* set focus on specified field */
		if (typeof(fld)=="object") {
			if (fld.type!="hidden") {
				fld.focus();
			}
		}
	}
}

function onsubmitevent() {
/*	onsubmitevent		function called from onsubmit parameter of the form tag.  Checks the 
							value of form.formaction.  If blank, sets it to 'SAVE'.
*/

	if (document.forms[0].formaction) {
		if (document.forms[0].formaction.value=="") {
			document.forms[0].formaction.value = "SAVE";
			return true;
		}
		/*else {
			alert("This Form Has Already Been Saved.");
			return false;
		}*/
	}
}

function listappend() {
/*	listappend		Appends newval to list
	Parameters:
	list				list
	newval			value to be appended
	delim				list delimiter (default is ",")
	unique			unique flag - when set don't append newval if it is already in the list
*/

	if (listappend.arguments.length<=1) {
		alert("Error in call to listappend():  At least 2 arguments required.");
		return "";
	}
	var list		= listappend.arguments[0];
	var newval	= listappend.arguments[1];
	var delim	= ",";
	var unique	= false;
	var proceed = true;
	if (listappend.arguments.length>=3)	delim		= listappend.arguments[2];
	if (listappend.arguments.length>=4) unique	= listappend.arguments[3];
	var a_vals = list.split(delim);
	if (unique) {
		var valnum = 0;
		while (proceed && valnum<a_vals.length) {
			proceed = (a_vals[valnum]!=newval);
			valnum++;
		}
	}
	if (proceed) {
		if (list=="") delim = "";
		list = list+delim+newval;
	}
	return list;
}

function listdelete() {
/*	listdelete		deletes a value from a list
	Parameters:
	list				list
	delval			value to delete from list
	delim				list delimiter (default is ",")
*/

	if (listdelete.arguments.length<=1) {
		alert("Error in call to listdelete():  At least 2 arguments required.");
		return "";
	}
	var list		= listdelete.arguments[0];
	var delval	= listdelete.arguments[1];
	var delim	= ",";
	if (listdelete.arguments.length>=3)	delim	= listdelete.arguments[2];
	var a_vals		= list.split(delim);
	var newlist		= "";
	var newdelim	= "";
	for (i=0;i<a_vals.length;i++) {
		if (a_vals[i]!=delval) {
			newlist	= newlist+newdelim+a_vals[i];
			newdelim	= delim;
		}
	}
	return newlist;
}



	//	openeditwin		open a new window
	function openeditwin() {
		var template	= "";
		var winname		= "";
		var winwidth	= 400;
		var winheight	= 280;
		var wintop		= 75;
		var winleft		= 10;
		var args = openeditwin.arguments;
		if (args.length>=6) winleft	= args[5];
		if (args.length>=5) wintop		= args[4];
		if (args.length>=4) winheight = args[3];
		if (args.length>=3) winwidth	= args[2];
		if (args.length>=2) winname	= args[1];
		if (args.length>=1) template	= args[0];
		open(template,winname,"toolbar=no,directories=no,menubar=no,resizable=no,screenX=50,screenY=30,top="+wintop+",left="+winleft+",width="+winwidth+",height="+winheight+",location=no,scrollbars=yes");
	}
	
function setuseraction(ua,sbmt) {
/*	setuseraction		assigns formaction field to the value of ua.  If
							sbmt is 1 then the form is submitted
*/
	document.forms[0].formaction.value = ua;
	if (sbmt==1) {
		document.forms[0].submit();
	}
}
	
function markasdeleted(metaname,rec,key) {
/*	markasdeleted		given a metaname, record number and keyfld name,
							adds the record to the delreclist field for the 
							metaname.  The form is submitted with 'REFRESH' as
							the action
*/

	if (rec.indexOf("N")!=-1) {
		/* record is a new record, remove from newreclist */
		var listobj = eval("document.forms[0]."+metaname+"_newreclist");
		listobj.value = listdelete(listobj.value,replace(rec,"N",""),",");
	}
	else {
		/* record is an existing record, add to delreclist and delkeylist */
		var listobj = eval("document.forms[0]."+metaname+"_delreclist");
		listobj.value = listappend(listobj.value,rec,",",true);
		var listobj = eval("document.forms[0]."+metaname+"_delkeylist");
		listobj.value = listappend(listobj.value,key,",",true);
	}
	setuseraction("REFRESH",1);
	return true;
}

function validatefld(fobj,metaname,recnum,datatype,validfunc) {
/*	validatefld		Validation function called from onchange events in <input> tags
	Parameters:
	fobj				(this) - A reference to the input tag object field
	datatype			The type of data the field holds
	validfunc		additional function to call for validation
*/

	var fname		= fobj.name;
	if (recnum=="") {
		recnum = "1";
	}
	// format data
	if (datatype=="$") {
		dollarformat(fobj);
	}
	if (datatype=="D") {
		dateformat(fobj);
	}
	// if checkbox, update related field
	if (fobj.type=="checkbox") {
		var fname = "document.forms[0]."+replace(fobj.name,"_checkbox","");
		if (fname!=fobj.name) {
			tempobj = eval(fname);
			if (fobj.checked) {
				if (datatype=="C") {
					tempobj.value = "Y";
				}
				if (datatype=="N") {
					tempobj.value = "1";
				}
			}
			else {
				if (datatype=="C") {
					tempobj.value = "N";
				}
				if (datatype=="N") {
					tempobj.value = "0";
				}
			}
		}
	}
	// if radio button, update related field
	if (fobj.type=="radio") {
		var fname = "document.forms[0]."+replace(fobj.name,"_radio","");
		tempobj = eval(fname);
		tempobj.value = fobj.value;
	}
	// if file object, copy filename value to related field
	if (fobj.type=="file") {
		var fname = "document.forms[0]."+replace(fobj.name,"_file","");
		tempobj = eval(fname);
		if (tempobj) {
			tempobj.value = fobj.value;
		}
	}
	// call further validation function if present
	if (validfunc!="") {
		a_rec = validfunc.split("=");
		if (a_rec[0]=="lookup") {
			validfunc = "lookup('"+a_rec[1]+"','"+a_rec[2]+"','"+fobj.value+"')";
		}
		retval = eval(validfunc);
	}
	else {
		retval = true;
	}
	// mark record as updated
	if (metaname!="") {
		setupdatedrec(metaname,recnum);
	}
	if (document.forms[0].cancelbttn) {
		document.forms[0].cancelbttn.value = "Cancel";
	}
	return retval;
}

function dollarformat(fobj) {
/*	dollarformat	Formats the passed input object as currency.
*/
	var paramtype = typeof(fobj)
	switch (paramtype) {
		case "object":
			var paramval = fobj.value
			break
		case "string":
			var paramval = fobj
			break
		default:
			var paramval = ""+fobj
	}
	paramval = replace(replace(paramval,"$",""),",","")
	if (paramval.indexOf(".")==-1) {
		var charpos = paramval.length-1
		var retval = ".00"
	}
	else {
		var charpos = paramval.indexOf(".")-1
		var retval = paramval.substring(charpos+1)
		while (retval.length<3) {
			retval = retval + "0"
		}
	}
	sepcount = 0
	while (charpos>=0) {
		var sepcount = sepcount + 1
		if (sepcount%3==0 && charpos!=0) {
			retval = ","+paramval.charAt(charpos)+retval
		}
		else {
			retval = paramval.charAt(charpos)+retval
		}
		charpos = charpos - 1
	}
	retval = "$"+retval
	if (paramtype=="object") {
		fobj.value = retval
		return true
	}
	else {
		return retval
	}
}
	
function about() {
/*
	about		function called from menu to load SolutionsOne About page
*/
	open("http://www.solutions1consulting.com/about.cfm","About","toolbar=no,directories=no,menubar=no,resizable=no,screenX=75,screenY=100,top=100,left=75,width=300,height=250,location=no,scrollbars=yes");
}

function dateformat() {
/*	dateformat		Given either a field object or string value argument, returns
						a string as mm/dd/yyyy.
						Dates must be entered as mdd, mmdd, mddyy, mmddyy, mddyyyy, or mmddyyyy,
						otherwise an error occurs
*/

	var args = dateformat.arguments;
	if (args.length==1) {
		// assign datestr
		if (typeof(args[0])=="object") {
			var fldobj	= args[0];
			var datestr	= fldobj.value;
			// If Blank then return true
			if (datestr=="") {
				return true;
			}
		}
		else {
			var datestr = args[0];
			// If Blank then return blank
			if (datestr=="") {
				return "";
			}
		}
		// create newstr by stripping all non numbers from datestr
		var newstr	= "";
		var onechar	= "";
		var numlist = "0123456789";
		for (i=0;i<datestr.length;i++) {
			onechar = datestr.charAt(i);
			if (numlist.indexOf(onechar)!=-1) {
				newstr = newstr + onechar;
			}
		}
		// seperate date parts
		var currentdate = new Date();
		var yy = currentdate.getFullYear();
		if (newstr.length>=3 && newstr.length<=8) {
			var validmsg = "";
			if (newstr.length==7 || newstr.length==8) {
				// mddyyyy or mmddyyyy
				yy = newstr.substring(newstr.length-4);
				newstr = newstr.substring(0,newstr.length-4);
			}
			if (newstr.length==5 || newstr.length==6) {
				// mddyy or mmddyy
				yy = "20" + newstr.substring(newstr.length-2);
				newstr = newstr.substring(0,newstr.length-2);
			}
			if (newstr.length==3 || newstr.length==4) {
				// mdd or mmdd
				dd = newstr.substring(newstr.length-2);
				mm = newstr.substring(0,newstr.length-2);
				if (mm.length==1) {
					mm = "0" + mm;
				}
				if ("01,02,03,04,05,06,07,08,09,10,11,12".indexOf(mm)==-1) {
					validmsg = "Invalid Month.";
				}
			}
		}
		else {
			var validmsg = "Invalid Date. Please Enter Dates In One Of These Formats:  mdd, mmdd, mddyy, mmddyy, mddyyyy, or mmddyyyy.";
		}
		if (validmsg=="") {
			// Build New Date with / seperator
			var retval = mm+"/"+dd+"/"+yy;
			if (typeof(args[0])=="object") {
				fldobj.value = retval;
				if (args.length==2) {
					// eval additional function
					eval(args[1]);
				}
				return true;
			}
			else {
				return retval;
			}
		}
		else {
			alert(validmsg);
			if (typeof(args[0])=="object") {
				return false;
			}
			else {
				return retval;
			}
		}
	}
}
/*
	alertmsg		function displays the first argument as a message and then calls closewindow()
					with the second two arguments.  Used with popup pages that only do processing
					and have no real content.
*/
function alertmsg() {
	var args 	= alertmsg.arguments;
	var msg		= "";
	var action	= "";
	var urlstr	= "";
	if (args.length>0)
		msg		= args[0];
	if (args.length>1)
		action	= args[1];
	if (args.length=2)
		urlstr	= args[2];
	// display message if there was one
	if (msg!="")
		alert(msg);
	// call closewindow (will do nothing if action and urlstr are "")
	closewindow(action,urlstr);
}

function moveselected(srcobj,destobj) {
/*	moveselected		function srcs srcobj select object for selected items and adds
							them to the destobj select object.  Depending on the value of the first
							part of the srcobj being "0" or not, adds or removes the value from the
							corresponding list object.
*/

	var srclen	= srcobj.options.length;
	var addlen	= 0;
	var i=0;
	while (i<srclen) {
		if (srcobj.options[i].selected) {
			// add to destobj and remove from srcobj
			var optval	= srcobj.options[i].value;
			var opttxt	= srcobj.options[i].text;
			var newopt	= new Option(opttxt,optval);
			addlen		= destobj.options.length;
			destobj.options[addlen]	= newopt;
			srcobj.options[i]			= null;
			srclen = srcobj.options.length;
			var a_ids = optval.split("|");
			/* add to source object's removed list */
			if (eval("document.forms[0]."+srcobj.name+"_removed")) {
				var addobj = eval("document.forms[0]."+srcobj.name+"_added");
				var delobj = eval("document.forms[0]."+srcobj.name+"_removed");
				/* try to remove from added list */
				var newaddlist = listdelete(addobj.value,optval,",");
				/* if added list remains the same, add to removed list */
				if (addobj.value==newaddlist) {
					delobj.value = listappend(delobj.value,optval,",",true);
				}
				else {
					addobj.value = newaddlist;
				}
			}
			/* add to destination objects added list */
			if (eval("document.forms[0]."+destobj.name+"_added")) {
				var addobj = eval("document.forms[0]."+destobj.name+"_removed");
				var delobj = eval("document.forms[0]."+destobj.name+"_added");
				/* try to remove from added list */
				var newaddlist = listdelete(addobj.value,optval,",");
				/* if added list remains the same, add to removed list */
				if (addobj.value==newaddlist) {
					delobj.value = listappend(delobj.value,optval,",",true);
				}
				else {
					addobj.value = newaddlist;
				}
			}
		}
		else {
			i++;
		}
	}
}

