String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function tkweblib_findFrame( frameName, startWindow ) {

	if ( !frameName.length ) return(false);
	if ( !startWindow.frames.length ) return(false);

	var foundFrame = false;

	for ( var i = 0; i < startWindow.frames.length; i++ ) {
		if ( startWindow.frames[i].name == frameName ) var foundFrame = startWindow.frames[i];
	}

	return(foundFrame);
}

function tkweblib_confirmExit() {

	var ignorePages = new Array( "http://" + document.domain + "/signin.php",
								 "http://" + document.domain + "/login.php");
	var myRosterRegExp = new RegExp("^http:\/\/" + document.domain + "\/intralink", "i");

	// Locate the frame object
	var mainFrame = tkweblib_findFrame("mainFrame", window.top);

	if ( mainFrame ) {

		// URL of the current page loaded in the frame
		var url = mainFrame.document.location.toString();

		// We're not going to show the alert if the current page is the admin redirect screen.
		// This test is to make sure that it's not
		if ( url.match(myRosterRegExp) == null ) {

			// If the cookie value 'fortune' is greater than zero and we're not on an ignore page,
			// then confirm that we want to exit
			if ( (getCookie("fortune") > 0) && (!tkweblib_inArray(url, ignorePages)) ) {

				// Otherwise, confirm the user wants to exit
				var confirmMsg  = "You are about to be signed out of ToolkitCMA.com!\n";
					confirmMsg += "Data you have entered may not be saved.";
				return confirmMsg;
			}
		}
	}
}

function tkweblib_createCSUM() {

	var curmls = getCurrentInterface();
	var csum = curmls + "csum.def";
	var dataIni = curmls + "data.ini";
	var mlsIni = curmls + ".ini";

	var section = tkweb.getPrivateIniSection("Field Definitions", 16384, dataIni);
	var lines = new Array();
	lines = section.split("\n");

	for ( var i = 0; i < lines.length; i++ ) {

		if ( lines[i] == "" ) continue;

		var excluded = false;
		var parts = new Array();
		parts = lines[i].split(/=|\|/);

		for ( var s = 0; s < document.excludefield.length; s++ ) {

			if ( parts[0] == document.excludefield[s] ) {
				excluded = true;
				break;
			}
		}

		if ( !excluded ) {

			var key = parts[0];
			var length = parseInt(parts[3]);  // from <IF>DATA.INI

			if ( (length <= 0) && (key.match(/price$/i) != null) ) length = 10;
			if ( length <= 0 ) length = tkweblib_getLengthFromPropIni(key);
			if ( length < 4 ) length = 4;

			var label = parts[0].replace(/\d+$/, "");
			if ( label.length > length ) label = label.substr(0, length);

			var value = label + "|" + length;
			tkweb.setPrivateIniString("Field Definition", key, value, csum);
		}
	}

	tkweb.setPrivateIniString("Custom", "csum", "1", mlsIni);
}

function tkweblib_delimString2Array( strEmailList ) {

	var arrEmailList = new Array(); // Array to hold potential email addresses to return
	var delimRE = / *[,;] */g;      // Regular Expression to match the delimiter
	var emptyRE = /^\s*$/;          // Regular Expression to match an empty element

	// Replace delimiters and adjacent spaces with a single comma
	// and split into array at the commas
	var arrTemp = strEmailList.replace(delimRE, ",").split(",");
	
	// Remove empty elements from the array by pushing non-empty elements onto a new array
	for ( var i = 0; i < arrTemp.length; i++ ) {
		if ( arrTemp[i].match(emptyRE) == null ) arrEmailList.push(arrTemp[i]);
	}

	return(arrEmailList);
}

function tkweblib_getAvailableMlsAliases() {

	var aliases = new Array();
	var mlsCount = tkweb.getPrivateIniInt("Interfaces", "Count", 0, "mls.ini");

	for ( var i = 1; i <= mlsCount; i++ ) {
		var alias = tkweb.getPrivateIniString("Interfaces", i, "", 255, "mls.ini");
		if ( alias.length > 0 ) aliases[aliases.length] = alias;
	}

	return(aliases);
}

function tkweblib_getCmaFields() {

	var filesArray = new Array("3pic.def", "6col.def", "adjm.def", "comp.def", "smry.def", "subj.def", ".fmk");
	var curmls = getCurrentInterface();
	var uniqueFields = new Array();

	for ( var f = 0; f < filesArray.length; f++ ) {

		var addFields = new Array();

		if ( filesArray[f].match(/\.def$/) ) {
			addFields = tkweblib_getFieldsFromDef(curmls + filesArray[f]);
			uniqueFields = tkweblib_mergeUnique(uniqueFields, addFields);
		}

		if ( filesArray[f].match(/\.fmk$/) ) {
			addFields = tkweblib_getFieldsFromFmk(curmls + filesArray[f]);
			uniqueFields = tkweblib_mergeUnique(uniqueFields, addFields);
		}
	}

	return(uniqueFields.sort());
}

function tkweblib_getFieldsFromDef( defFile ) {

	var lines = new Array();
	var fields = new Array();

	lines = tkweb.getPrivateIniSection("Field Definition", 16384, defFile).split("\n");

	for ( var i = 0; i < lines.length; i++ ) {

		if ( lines[i].match(/=/) != null ) {
			var temp = lines[i].split("=");
			fields[fields.length] = temp[0].toUpperCase();
		}
	}

	return(fields);
}

function tkweblib_getFieldsFromFmk(fmkFile) {

	var lines = new Array();
	var fields = new Array();

	lines = tkweb.getPrivateIniSection("Flyer Bullets", 16384, fmkFile).split("\n");

	for ( var i = 0; i < lines.length; i++ ) {

		if ( lines[i].match(/=/) != null ) {
			var temp1 = new Array();
			var temp2 = new Array();
			temp1 = lines[i].split("=");

			if ( temp1[1].match(/\|/) != null ) {
				temp2 = temp1[1].split("|");
				fields[fields.length] = temp2[0].toUpperCase();;
			}
		}
	}

	return(fields);
}

function tkweblib_getIEVersion() {

	var mvMatch = navigator.userAgent.match(/MSIE (\d+)\./);
	if ( mvMatch ) var mv = parseInt(mvMatch[1]);
	else return(false);
	
	var triMatch = navigator.userAgent.match(/Trident\/(\d+)\./);
	if ( triMatch ) var tri = parseInt(triMatch[1]);

	if ( mv - tri != 4 ) mv = tri + 4;

	return(mv);
}

function tkweblib_getLengthFromPropIni( fieldName ) {

	var section = tkweb.getPrivateIniSection("FieldNames", 16384, propIni())
	var lines = new Array();
	lines = section.split("\n");

	for ( var i = 0; i < lines.length; i++ ) {

		if ( lines[i] != "" ) {

			var parts = new Array();
			parts = lines[i].split("=");

			if ( parts[1] == fieldName ) {
				var length = tkweb.getPrivateIniInt("FieldSizes", parts[0], 10, propIni());
				return(length);
			}
		}
	}

	return(10);
}

function tkweblib_getNextPage() {

	// Array of all of the presentation screens in the order they are encountered
	var screenFiles = new Array(
		"tkprospect",
		"tkletter",
		"tkloadlistings",
		"tkselectmls",
		"tkproperties",
		"tkselectssfields",
		"tktourorder",
		"tkselectfields",
		"tksubjprop",
		"tkhomefinder",
		"tkadjcma",
//		"tkadjcma2",
		"tkprcrange",
		"tkabsorption",
		"tkstrategy",
		"tknetsheet",
		"tkmktplan",
		"tkprint"
	);
	
	// Array of modules for each screen
	var modules = new Array();
	modules["tkletter"] = 256;
	modules["tkloadlistings"] = 64;  // tkproperties always follows this screen
	modules["tktourorder"] = 16384;
	modules["tkselectfields"] = 512;
	modules["tksubjprop"] = 32;
	modules["tkhomefinder"] = 16;
	modules["tkadjcma"] = 1;         // tkadjcma2 always follows this screen
	modules["tkprcrange"] = 4096;
	modules["tkabsorption"] = 8192;
	modules["tkstrategy"] = 8;
	modules["tknetsheet"] = 2;
	modules["tkmktplan"] = 4;
	
	var reqd_modules = parseInt(tkweb.getIniString("Documents", "Modules", "0", 255));
	var presType = tkweb.getIniString("Presentation", "Type", "Print", 255);

	// Determine what screen we are on
	var url = document.URL;
	for ( var i = 0; i < screenFiles.length; i++ ) {
		var re = new RegExp(screenFiles[i] + "[12]{0,}\.php$");
		if ( url.match(re) ) break;
	}
	var currentScreen = i;

	// If we are on tkproperties.php and doing a slide show
	// we need to bring up the select slideshow fields screen
	var doclist = tkweb.getIniString("User", "Doclist", "", 255);
	var inputPPT = tkweb.getPrivateIniString("Info", "InputPPT", "", 255, doclist);
	var slideshow = (inputPPT.match(/\.pptx?$/i) ? true: false);

	if ( slideshow && screenFiles[currentScreen].match(/^tkproperties$|^tkselectmls$/) ) var nextScreen = "tkselectssfields";
	else {

		// Determine the next screen
		for ( var i = currentScreen + 1; i < screenFiles.length; i++ ) {
			if ( !modules[screenFiles[i]] ) continue;
			var mod = modules[screenFiles[i]];
			if ( (reqd_modules & mod) == mod) break;
		}

		// Make sure we don't go to tksubjprop or tkhomefinder without first going
		// to tkloadlistings or tkselectmls
		if ( ((screenFiles[i] == "tksubjprop") || (screenFiles[i] == "tkhomefinder")) && (currentScreen < 2) ) {
			var nextScreen = "tkselectmls";
		}
		else if ( screenFiles[i] ) var nextScreen = screenFiles[i];
		else if ( presType != "E-mail" ) var nextScreen = "tkprint";
		else var nextScreen = "tkemail";
	}

	// DEBUG 	alert("Current Screen: " + screenFiles[currentScreen-1] + "\nNext Screen: " + nextScreen);
	return(nextScreen + ".php");
}

function tkweblib_getPresSide() {
	var doclist = tkweb.getIniString("User", "Doclist", "", 255);
	var presType = tkweb.getPrivateIniString("Info", "PresType", "L", 1, doclist).toUpperCase();
	return(presType);
}

function tkweblib_getPresList( strIniFile, strSectionName ) {

	var arrPresentations = new Array();
	var arrTemp = tkweb.getPrivateIniSection(strSectionName, 4098, strIniFile).split("\n");

	for ( var i = 0; i < arrTemp.length; i++ ) {
		if ( arrTemp[i] != "" ) arrPresentations[arrPresentations.length] = arrTemp[i];
	}

	return(arrPresentations);
}

function tkweblib_getPresRank() {

	var doclist = tkweb.getIniString("User", "Doclist", "", 255);
	
	if ( !doclist.match(/^doclist\.\d\d\d$/i) ) return("");
	
	var section = new Array();
	section = tkweb.getPrivateIniSection("Documents", 16384, doclist).split("\n");

	var presRank = 0;
	for ( var i = 0; i < section.length; i++ ) {
		if ( section[i].match(/=/) ) {
			var temp = section[i].split("=");
			var docname = temp[0];
			var docrank = tkweb.getPrivateIniInt(docname, "PresRank", 0, doclist);
			if ( docrank > presRank ) presRank = docrank;
		}
	}

	if ( presRank == 0 ) presRank = "";
	return(presRank);
}

function tkweblib_getPrintPresentations( boolFineHomes ) {

	var arrPrintPres = tkweblib_getPresList("pres.ini", "Presentations");

	if ( boolFineHomes ) {
		var arrFineHomes = tkweblib_getPresList("pres.ini", "Fine Homes");
		for ( var i = 0; i < arrFineHomes.length; i++ ) arrPrintPres[arrPrintPres.length] = arrFineHomes[i];
	}

	return(arrPrintPres);
}

function tkweblib_inArray( needle, arrHaystack ) {

	if ( !arrHaystack.length ) return(false);

	for ( var i = 0; i < arrHaystack.length; i++ ) {
		if ( arrHaystack[i] == needle ) return(i);
	}
	return(false);
}

function tkweblib_isBrowserIE8() {
// This is really a test for IE version 8 or greater
	var reMatch = navigator.userAgent.match(/MSIE (\d)\./);

	if ( reMatch ) {

		var ver = reMatch[1];
		if ( document.documentMode && document.documentMode < 8 ) {
			try {
				var xd = new XDomainRequest();
				var ver = "8";
			}
			catch(e) { }
		}
		return(ver=="8");
	}
	else return(false);
}

function tkweblib_isEmailValid( strEmail ) {

	var emailRE = /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|aero|arpa|asia|biz|cat|com|coop|edu|gov|info|jobs|mil|mobi|museum|name|net|org|pro|tel)$/ig;

	if ( strEmail.match(emailRE) ) return(true);
	else return(false);
}

function tkweblib_isSlideShow() {

	// Are we doing a slide show?
	var doclist = tkweb.getIniString("User", "Doclist", "", 255);
	var inputPPT = tkweb.getPrivateIniString("Info", "InputPPT", "", 255, doclist);
	var slideshow = (inputPPT.match(/\.pptx?$/i) ? true: false);
	return(slideshow);
}

function tkweblib_mergeUnique( uniqueArray, addArray ) {

	for ( var i = 0; i < addArray.length; i++ ) {

		if ( tkweblib_inArray(addArray[i], uniqueArray) === false ) {
			uniqueArray[uniqueArray.length] = addArray[i];
		}
	}

	return(uniqueArray);
}

function tkweblib_ocxVer() {

	try {
		var ocxVer = tkweb.version();
	}
	catch(e) {
		return(false);
	}

	return(ocxVer);
}

function tkweblib_pausecomp( millis ) {

	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); } 
	while(curDate-date < millis);
} 

function tkweblib_setCookie(sName, sValue) {
	document.cookie = sName + "=" +escape(sValue) + ";path=/;domain=." + document.domain.match(/[^.]+\.[^.]+$/) + ";";
}

/* * * * * * * * * * * * * * * * * *
 * Check for valid e-mail address  *
 * * * * * * * * * * * * * * * * * */
function emailCheck (emailStr) {
  var emailPat=/^(.+)@(.+)$/
  var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
  var validChars="\[^\\s" + specialChars + "\]"
  var quotedUser="(\"[^\"]*\")"
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
  var atom=validChars + '+'
  var word="(" + atom + "|" + quotedUser + ")"
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

  var matchArray=emailStr.match(emailPat)
  if (matchArray==null) {
    alert("Email address '" + emailStr + "' is invalid.")
    return false
  }
  var user=matchArray[1]
  var domain=matchArray[2]

  if (user.match(userPat)==null) {
    alert("Email address '" + emailStr + "' is invalid.")
    return false
  }

  var IPArray=domain.match(ipDomainPat)
  if (IPArray!=null) {
    for (var i=1;i<=4;i++) {
      if (IPArray[i]>255) {
        alert("Destination IP address is invalid!")
        return false
      }
    }
    return true
  }

  var domainArray=domain.match(domainPat)
  if (domainArray==null) {
    alert("Email address '" + emailStr + "' is omitted or invalid.")
    return false
  }

  var atomPat=new RegExp(atom,"g")
  var domArr=domain.match(atomPat)
  var len=domArr.length
  if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) {
    alert("Email address '" + emailStr + "' is omitted or invalid.")
    return false
  }

  if (len<2) {
    var errStr="Email address '" + emailStr + "' is omitted or invalid."
    alert(errStr)
    return false
  }

  return true;
}

function getFieldValue(propNum, kwdNum) {
  var size = new Number(tkweb.getPrivateIniString("FieldSizes", kwdNum, "", 3, propIni()));
  var result = new String(tkweb.getPrivateIniString("Property" + propNum, kwdNum, "", size, propIni()));
  return result;
}

/***************************************
 * Get the ID of the current interface *
 ***************************************/
function getCurrentInterface() {
	var curMls = tkweb.getPrivateIniString("Interfaces", "CurrentInterface", "", 4, "mls.ini");
	return(curMls.toLowerCase());
}

/* * * * * * * * * * * * * * * * * * * * * *
 * Searches the xxxxprop.ini file for sold *
 * properties. Writes a list of property   *
 * numbers (matching the prop.ini) to the  *
 * TKWEB.INI. Also returns an array of the *
 * property numbers.                       *
 * * * * * * * * * * * * * * * * * * * * * */
function getSoldProps() {
// What are the valid sold statuses
  var thisIF = getCurrentInterface();
  var iniFile = thisIF.toLowerCase() + ".ini";
  var dataIni = parseDataIni(thisIF, "", "");
  var re = /^STATUS$/;
  var dataIniNames = dataIni[0];
  var dataIniKwds = dataIni[1];
  for (var i = 0; i < dataIniNames.length; i++) {
    if (dataIniNames[i].match(re) != null) var statKwd = dataIniKwds[i];
  }

  var soldStatus = codeToRegExp(tkweb.getPrivateIniString("SoldStatus", "SoldStatus", "", 255, iniFile));
  var soldProps = new Array();
  var otherProps = new Array();
  var soldIdx = 0;
  var otherIdx = 0;
  var propCount = tkweb.GetIniString("Properties", "Count", "", 3);
  for (var i = 1; i <= propCount; i++) {
    var prop = tkweb.getIniString("Properties", i, "", 3);
    var status = getFieldValue(prop, statKwd);
    if (status.match(soldStatus) != null) soldProps[soldIdx++] = prop;
	else otherProps[otherIdx++] = prop;
  }
  tkweb.setIniString("Properties", "AdjCMAprops", soldProps);
  tkweb.setIniString("Properties", "AdjCMAprops_sold", soldProps);
  tkweb.setIniString("Properties", "AdjCMAprops_unsold", otherProps);
  return soldProps;
}

function getUserArray() {
// will return 0 length array if unable to get any one part of the user array.
  var size = 255;
  var fran = tkweb.getIniString("User", "Franchise", "", size);
  var comp = tkweb.getIniString("User", "Company", "", size);
  var offc = tkweb.getIniString("User", "Office", "", size);
  var agnt = tkweb.getIniString("User", "Agent", "", size);
  
  var result = new Array();

  if ( ( fran != "") && 
       ( comp != "") &&
       ( offc != "") &&
       ( agnt != "") ) {
    result [ 0 ] = fran;
    result [ 1 ] = comp;
    result [ 2 ] = offc;
    result [ 3 ] = agnt;
  }

  return result;
}

function isDemo() {
  var user = getUserArray();
  return (user[user.length - 1].toLowerCase() == "demo");
}

/*****************************************
 * Conjure up the property .INI filename *
 *****************************************/
function propIni() {
  var thisIf = getCurrentInterface();
  return thisIf.toLowerCase() + "prop.ini";
}

/*****************************************
 * Reads the xxxxdata.ini and returns an *
 * array containing the field names as   *
 * the first element of an array and an  *
 * array containing the field keyword    *
 * numbers as the 2nd element.           *
 *****************************************/
function parseDataIni(thisIf, firstFields, lastFields) {
  var dataIni = thisIf.toLowerCase() + "data.ini";
  var section = tkweb.GetPrivateIniSection("Field Definitions", 4096, dataIni);
  var keys = section.split("\n");
  var fieldNames = new Array();
  var fieldKwds = new Array();
  for (var i = 0; i < keys.length; i++) {
    if (keys[i] != "") {
      var keypair = keys[i].split("=");
      if (keypair.length > 1) {
        fieldNames[i] = keypair[0];
        var value = keypair[1].split("|");
        fieldKwds[i] = value[0];
      }
    }
  }

  if (firstFields != "") {
    bubbleFields = firstFields.split(",");
    for (var j = 0; j < bubbleFields.length; j++) {
      for (var i = j; i < fieldNames.length; i++) {
        if (fieldNames[i] == bubbleFields[j]) {
          tempName = fieldNames[j];
          tempKwd = fieldKwds[j];
          fieldNames[j] = fieldNames[i];
          fieldKwds[j] = fieldKwds[i];
          fieldNames[i] = tempName;
          fieldKwds[i] = tempKwd;
        }
      }
    }
  }

  if (lastFields != "") {
    stoneFields = lastFields.split(",");
    for (var j = 0; j < stoneFields.length; j++) {
      for (var i = 0; i < fieldNames.length; i++) {
        if (fieldNames[i] == stoneFields[j]) {
          if (i + 1 < fieldNames.length) {
            tempName = fieldNames[i + 1];
            tempKwd = fieldKwds[i + 1];
            fieldNames[i + 1] = fieldNames[i];
            fieldKwds[i + 1] = fieldKwds[i];
            fieldNames[i] = tempName;
            fieldKwds[i] = tempKwd;
          }
        }
      }
    }
  }

  return new Array(fieldNames, fieldKwds);
}

/********************************************
 * Reads the specified def file and returns *
 * an array containing the field names as   *
 * the first element of an array, an array  *
 * containing the display names as the 2nd  *
 * element, and an array containing the     *
 * the keyword numbers as the 3rd element.  *
 ********************************************/
function parseDef(defFile) {
  dataIni = new String(defFile.substr(0,4));
  dataIni += "data.ini";
  section = new String(tkweb.GetPrivateIniSection("Field Definition", 8192, defFile));
//  re = /\n/ig;
//  test = section.replace(re,"&amp;br<br>");
//  document.write(test);
  var keys = new Array();
  keys = section.split("\n");
  fieldNames = new Array();
  displayNames = new Array();
  fieldKwds = new Array();
  for (var i = 0; i < keys.length; i++) {
    if (keys[i] != "") {
      pair = keys[i].split("=");
      if (pair.length > 1) {
        fieldNames[i] = pair[0];
        temp = pair[1].split("|");
        displayNames[i] = temp[0];
    	  fieldKwds[i] = tkweb.GetPrivateIniInt("Field Definitions", fieldNames[i], -1, dataIni);
      }
    }
  }
  result = new Array(fieldNames, displayNames, fieldKwds);
  return result;
}

/*******************************
 * Function to display a table *
 * listing all of the modules  *
 * used by the presentation.   *
 *******************************/
function moduleRow(mod) {
  document.write('<tr><td nowrap class="tableLabel">');
  if (mod == 128) document.write("Prospect Information");
  if (mod == 64) document.write("MLS Property Data");
  if (mod == 32) document.write("Subject Property");
  if (mod == 16) document.write("Home Finder's Profile");
  if (mod == 8) document.write("Pricing Strategy Worksheet");
  if (mod == 4) document.write("Marketing Plan of Action");
  if (mod == 2) document.write("Net Proceeds Worksheet");
  if (mod == 1) document.write("Price Adjusted CMA");
  document.write('</td><td align="center" nowrap class="tableValue">&nbsp;</td></tr>');
}

/****************************
 * Function to retrieve the *
 * agent's name.            *
 ****************************/
function getAgentName() {
  var name = tkweb.getIniString("User", "Name", "", 35);
  if (name == "") return ("Unknown User");
  else return (name);
}

/*****************************
 * Functions used to control *
 * display the online help   *
 *****************************/
/*function helpOver() {
  try {
    if (document.helpState == "Closed") {
      window.status = "Display Online Help for this page.";
      helpButton.src = "/images/help_over.gif";
    }
    else window.status = "Close Online Help.";
  }
  catch ( e ) { }
}

function helpDown() {
  try {
    if (document.helpState == "Closed") {
      helpButton.src = "/images/help_down.gif";
    }
  }
  catch ( e ) { }
}

function helpClick() {
  if (document.helpState == "Closed") {
    var helpURL = "help.php#" + document.title;
    var wHeight = screen.availHeight - 30;
    var wWidth = 450;
    var wLeft = screen.availWidth - 460;
    var wTop = 0;
    help = window.open( "/sys/" + helpURL, 'help', 'location=no, toolbar=no, scrollbars=yes, resizable=yes, height=' + wHeight + ', top=' + wTop + ', left=' + wLeft + ', width=' + wWidth);
    help.focus();
    document.helpState = "Open";
    window.status = "Close Online Help.";
  }
  else {
    helpButton.src = "/images/help_over.gif";
    help.close();
    document.helpState = "Closed";
    window.status = "Display Online Help for this page.";
  }
}

function helpCheck() {
  try {
    if ((document.helpState == "Open") && help.closed) {
      helpButton.src = "/images/help.gif";
      document.helpState = "Closed";
    }
  }
  catch ( e ) { }
}

function helpOut() {
  try {
    window.status = "";
    if (document.helpState == "Closed")
      helpButton.src = "/images/help.gif";
  }
  catch ( e ) { }
}

function helpClose() {
  try {
    helpButton.src = "/images/help.gif";
    help.close();
    document.helpState = "Closed";
  }
  catch ( e ) { }
}
*/
/*****************************
 * Functions used to control *
 * the display of the save   *
 * button.                   *
 *****************************/
/*function saveOver() {
  saveButton.src = "/images/save_over.gif";
  window.status = "Save your work at this point.";
}

function saveDown() {
  saveButton.src = "/images/save_down.gif";
}

function saveClick() {
  document.location = "/sys/savedialog.php";
}

function saveOut() {
  saveButton.src = "/images/save.gif";
  window.status = "";
}
*/
/*****************************
 * Functions used to control *
 * user signout              *
 *****************************/
/*function closeOver() {
  try {
    window.status = "Sign out of ToolkitCMA.com.";
    closeButton.src = "/images/close_over.gif";
    btmCloseButton.src = "/images/close_over.gif";
  }
  catch ( e ) { }
}

function closeDown() {
  try {
    closeButton.src = "/images/close_down.gif";
    btmCloseButton.src = "/images/close_down.gif";
  }
  catch ( e ) { }
}

function closeClick() {
  try {
    setCookie("fortune", "0");
    document.location = "/signin.php";
  }
  catch ( e ) { }
}

function closeOut() {
  try {
    window.status = "";
    closeButton.src = "/images/close.gif";
    btmCloseButton.src = "/images/close.gif";
  }
  catch ( e ) { }
}
*/
function showHistory() {
	// Search the History for the current page.
	// If found, make it the last page.
	var count = new Number(tkweb.getIniString("History", "Count", "0", 2));
	var title = new String(document.title);
	var url = new String(window.location);
	var found = false;
	for (var i = 1; i <= count; i++) {
		if (tkweb.getIniString("History", i, "", 255) == title + "|" + url) {
			count = i;
			tkweb.setIniString("History", "Count", count);
			found = true;
			break;
		}
	}

	// If current page was not in the history, add it.
	if (!found) {
		count++;
		tkweb.setIniString("History", "Count", count);
		tkweb.setIniString("History", count, title + "|" + url);
	}

	// Show the history links
    for (var i = 1; i <= count; i++) {
		var temp = tkweb.getIniString("History", i, "", 255);
		var tempAry = temp.split("|");
		if (temp != document.title + "|" + new String(window.location)) {
			var relURL = tempAry[1].substr( tempAry[1].search( /\/sys/ ) )
			document.write('<a href="' + relURL + '"');
			document.write(' class="navtext" onMouseOver="this.className=');
			document.write("'navtext-over'");
			document.write('" onMouseOut="this.className=');
			document.write("'navtext'");
			document.write('" onmousedown="this.className=');
			document.write("'navtext-click'");
			document.write('">');
			document.write(tempAry[0] + '</a>');
		}
		else {
			document.write('<span class="navtext" style="text-decoration: none"><b>' + tempAry[0] + '</b></span>');
		}
		if (i != count) {
			document.write(' <span class="navtext" style="text-decoration: none">&#187;</span> ');
		}
    }
}

function clearHistory() {
	return;
	/*
  var count = new Number(tkweb.getIniString("History", "Count", "0", 2));
  var title = new String(document.title);
  var url = new String(window.location);
  var found = 0;
  if (found!=0) {
	tkweb.setIniString("History", "Count", found);
  }
  */
}

function addToHistory() {
	return;
	/*
  var count = new Number(tkweb.getIniString("History", "Count", "0", 2));
  var title = new String(document.title);
  var url = new String(window.location);
  var found = false;
  for (var i = 1; i <= count; i++) {
    if (tkweb.getIniString("History", i, "", 255) == title + "|" + url) found = true;
  }
  if (!found) {
    count++;
    tkweb.setIniString("History", "Count", count);
    tkweb.setIniString("History", count, title + "|" + url);
  }
  */
}

/*
function showHistory() {
  var count = new Number(tkweb.getIniString("History", "Count", "0", 2));
  var HistoryCount = new Number(tkweb.getIniString("History", "Count", "0", 2));
  if (HistoryCount > 0) {
    for (var i = 1; i <= count; i++) {
      var temp = tkweb.getIniString("History", i, "", 255);
      var tempAry = temp.split("|");
      if (tempAry[1] != new String(window.location)) {
        var relURL = tempAry[1].substr( tempAry[1].search( /\/sys/ ) )
        document.write('<a href="' + relURL + '"');
        document.write(' class="navtext" onMouseOver="this.className=');
        document.write("'navtext-over'");
        document.write('" onMouseOut="this.className=');
        document.write("'navtext'");
        document.write('" onmousedown="this.className=');
        document.write("'navtext-click'");
        document.write('">');
        document.write(tempAry[0] + '</a>');
      }
      else document.write('<span class="navtext" style="text-decoration: none"><b>' + tempAry[0] + '</b></span>');
      if (i != count) {
        document.write(' <span class="navtext" style="text-decoration: none">&#187;</span> ');
      }
    }
  }
}
*/

/********************************************
 * Returns an array containing the location *
 * of the calling html document             *
 * Array[0] contains the server part        *
 * Array[1] contains the path part          *
 * Array[2] contains the filename part      *
 * NOTE: "http://" + Array[0] + "/" +       *
 *       Array[1] + [Array[2] will          *
 *       yield the complete URL             *
 ********************************************/
function getURL() {
  var url = new String(window.location);
  var parts = new Array();
  var parts = url.split("/");
  var server = new String(parts[2]);
  var file = new String(parts[parts.length - 1]);
  var path = new String("");
  if (parts.length > 4) {
    for (var i = 3; i < parts.length - 1; i++) {
      path += parts[i] + "/";
    }
  }
  path = path.substr(0,path.length-1);
  var result = new Array(server,path,file);
  return result;
}

/***************************************
 * Resize the window to fit the screen *
 ***************************************/
function fitWindow() {
  var scrWidth = screen.availWidth;
  var scrHeight = screen.availHeight;
  if (scrWidth > 800) scrWidth = 800;
  xPos = window.screenLeft;
  if (xPos + scrWidth > screen.availWidth) xPos = (screen.availWidth - scrWidth) / 2;
  window.moveTo(xPos,window.screenTop);
  window.resizeTo(scrWidth,document.body.scrollHeight);
}

/***************************
 * Writes the Presentation *
 * Description Table       *
 ***************************/
function doPresDescrTable() {
  document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="tableHeading"><tr><td colspan="2">');
  document.writeln('<table border="0" align="center"><tr><td class="tableHeading" nowrap>');
  document.writeln('<b>Presentation Description</b></td></tr></table></td></tr>');
  document.writeln('<tr><td><table border="0" class="tableBackground" width="250"><tr><td align="right" nowrap class="tableLabel"><b>Agent:</b></td>');
  document.writeln('<td nowrap class="tableValue">');
  document.write(tkweb.getPrivateIniString("Contact Information", "agentname", "", 255, "agentinfo.ini"));
  document.writeln('</td></tr>');
  document.writeln('<tr><td align="right" nowrap class="tableLabel"><b>Company:</b>');
  document.writeln('</td><td nowrap class="tableValue">');
  document.write(tkweb.getPrivateIniString("Contact Information", "company", "", 255, "agentinfo.ini"));
  document.writeln('</td></tr><tr><td align="right" nowrap class="tableLabel">');
  document.writeln('<b>Presentation:</b></td><td class="tableValue">');
  document.write(tkweb.getIniString("User", "Pres", "", 255));
  document.writeln('</td></tr>');
  if (tkweb.getIniString("User","PRESINFO","",4)=="Done") {
    document.writeln('<tr><td align="right" nowrap class="tableLabel">');
    document.writeln('<b>Prospect:</b></td><td nowrap class="tableValue">');
    document.writeln(tkweb.getPrivateIniString("Prospect", "mail_name", "", 255, "prospect.ini"));
    document.writeln('</td></tr>');
  }
  document.writeln('</table></td></tr></table>');
}

/****************************
 * Writes the Modules Table *
 ****************************/
function doModulesTable() {

  if ( tkweb.getIniString ( "Presentation", "Type", "", 255) == "Flyers" ) {
    return;
  }
  mods = new Number(tkweb.GetIniString("Documents", "Modules", "", 255));
  if (mods > 0) {
    document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="tableHeading"><tr><td>');
    document.writeln('<table border="0" align="center">');
    document.writeln('<tr align="center"><td nowrap class="tableHeading" colspan="2">');
    document.writeln('<b>Additional Information Required</b></td></tr></table>');
    document.writeln('</td></tr><tr><td><table border="0" class="tableBackground" width="250">');
    if ((mods & 128) == 128) {
      document.writeln('<tr><td nowrap class="tableLabel">');
      document.writeln('Prospect Information</td><td align="center" class="tableValue">');
      if (tkweb.GetIniString("User","PRESINFO","",4)=="Done") {
        document.writeln('<img src="/images/check.gif"></td></tr>');
      }
      else document.writeln('&nbsp;</td></tr>');
    }
    if ((mods & 64) == 64) {
      document.writeln('<tr><td nowrap class="tableLabel">');
      document.writeln('MLS Property Data</td><td align="center" class="tableValue">');
      if (tkweb.GetIniString("User","DATAMLS","",4)=="Done") {
        document.writeln('<img src="/images/check.gif"></td></tr>');
      }
      else document.writeln('&nbsp;</td></tr>');
    }
    if ((mods & 32) == 32) {
      document.writeln('<tr><td nowrap class="tableLabel">');
      document.writeln('Subject Property</td><td align="center" class="tableValue">');
      if (tkweb.GetIniString("User","SUBJPROP","",4)=="Done") {
        document.writeln('<img src="/images/check.gif"></td></tr>');
      }
      else document.writeln('&nbsp;</td></tr>');
    }
    if ((mods & 16) == 16) {
      document.writeln('<tr><td nowrap class="tableLabel">');
      document.writeln('Home Finders Profile</td><td align="center" class="tableValue">');
      if (tkweb.GetIniString("User","HOMEFINDER","",4)=="Done") {
        document.writeln('<img src="/images/check.gif"></td></tr>');
      }
      else document.writeln('&nbsp;</td></tr>');
    }
    if ((mods & 8) == 8) {
      document.writeln('<tr><td nowrap class="tableLabel">');
      document.writeln('Pricing Strategy Worksheet</td><td align="center" class="tableValue">');
      if (tkweb.GetIniString("User","STRATEGY","",4)=="Done") {
        document.writeln('<img src="/images/check.gif"></td></tr>');
      }
      else document.writeln('&nbsp;</td></tr>');
    }
    if ((mods & 4) == 4) {
      document.writeln('<tr><td nowrap class="tableLabel">');
      document.writeln('Marketing Plan of Action</td><td align="center" class="tableValue">');
      if (tkweb.GetIniString("User","MKTPLAN","",4)=="Done") {
        document.writeln('<img src="/images/check.gif"></td></tr>');
      }
      else document.writeln('&nbsp;</td></tr>');
    }
    if ((mods & 2) == 2) {
      document.writeln('<tr><td nowrap class="tableLabel">');
      document.writeln('Net Proceeds Worksheet</td><td align="center" class="tableValue">');
      if (tkweb.GetIniString("User","NETSHEET","",4)=="Done") {
        document.writeln('<img src="/images/check.gif"></td></tr>');
      }
      else document.writeln('&nbsp;</td></tr>');
    }
    if ((mods & 1) == 1) {
      document.writeln('<tr><td nowrap class="tableLabel">');
      document.writeln('Price Adjusted CMA</td><td align="center" class="tableValue">');
      if (tkweb.GetIniString("User","CMA_ADJ","",4)=="Done") {
        document.writeln('<img src="/images/check.gif"></td></tr>');
      }
      else document.writeln('&nbsp;</td></tr>');
    }
    document.writeln('</table></td></tr></table>');
  }
}

function currencyToNum (num) {
  var re = /\$|,/g;
  r = num.replace(re,"");
  return new Number(r);
}

function numToCurrency (num) {
  num = Math.round(num);
  var numStr = new String(num);
  var re = /\./;
  var leftDigits = new Number(numStr.search(re));
  if (leftDigits == -1) leftDigits = numStr.length;
  var rightDigits = numStr.length - leftDigits - 1;
  var commas = parseInt(leftDigits / 3);
  var lead = leftDigits % 3;
  if (lead == 0) {
    commas--;
    lead = 3;
  }
  curStr = "$";
  for (var i = 0; i < numStr.length; i++) {
    curStr += numStr.charAt(i);
    if ((commas != 0)&&(--lead == 0)) {
      lead = 3;
      curStr += ",";
      commas--;
    }
  }
  if (rightDigits == 1) curStr += "0";
  return curStr;
}

function getServerVersion ( versionFile ) {
  tkweb.downloadToCache( versionFile );
  var result = tkweb.getPrivateIniString("Version", "Version", "0", 10, versionFile);
  return result;
}

function applyChanges( changeFile ) {
  tkweb.downloadToCache( changeFile );
  var section = tkweb.getPrivateIniSection("Changes", 8192, changeFile);
  var pairs = section.split("\n");
  tkweb.setPrivateIniString("Test", "pairs", pairs, "results.ini");
  for (var i = 0; i < pairs.length; i++) {
    var temp = pairs[i].split("=");
    tkweb.deleteFromCache(temp[1]);
    tkweb.setPrivateIniString("Test", "temp" + i, temp[1], "results.ini");
  }
}

function updatePres() {
  deleteVersions();
  var temp = tkweb.getIniString("Versions", "Pres", "", 15);
  if (temp == "") temp = "0.0.0";
  var versions = temp.split(".");
  var vLevels = new Array("f","o","a");
  for (var i = 0; i < vLevels.length; i++ ) {
    var serverVersion = getServerVersion( vLevels[i] + "version.ini" );
    for (var j = new Number(versions[i]) + 1; j <= serverVersion; j++) {
      var filename = vLevels[i] + "change." + j;
      applyChanges( filename );
    }
    versions[i] = serverVersion;
  }
  tkweb.setIniString("Versions", "Pres", versions[0] + "." + versions[1] + "." + versions[2]);
}

function updateInterface() {
  deleteVersions();
  var curIF = getCurrentInterface();
  var version = new Number(tkweb.getIniString("Versions", curIF, "0", 5));
  var serverVersion = getServerVersion( "iversion.ini" );
  for (var j = version + 1; j <= serverVersion; j++) {
    var filename = "ichange." + j;
    applyChanges( filename );
  }
  tkweb.setIniString("Versions", curIF, serverVersion);
}

function deleteVersions() {
  tkweb.deleteFromCache("?version.ini")
  tkweb.deleteFromCache("?change.*")
}

// This function remains for backwards compatibility
function setCookie(sName, sValue) {
	tkweblib_setCookie(sName, sValue);
}

function getCookie(sName) {
  var aCookie = document.cookie.split("; ");
  for (var i = 0; i < aCookie.length; i++) {
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) return unescape(aCrumb[1]);
  }
  return null;
}

function codeToRegExp(codes) {
  var s = codes.split(",")
  var expr = "";
  for (var i = 0; i < s.length; i++) {
    if (i < s.length - 1) expr += s[i] + "|";
    else expr += s[i];
  }
  return expr;
}

function round(num) {
  var method = tkweb.GetPrivateIniString("Pricing", "rounding", "none", 12, "options.ini");
  var num = Math.round(num);
  if (method == "none") var result = num;
  if (method == "nextHundred") {
    if (num % 100 == 0) var result = num;
    else var result = 100 + num - (num % 100);
  }
  if (method == "nextThousand") {
    if (num % 1000 == 0) var result = num;
    else var result = 1000 + num - (num % 1000);
  }
  if (method == "hundred") var result = Math.round(num/100) * 100;
  if (method == "thousand") var result = Math.round(num/1000) * 1000;
  return result;
}

///////////////////////////////////////////////////////////////
// AJAX Functions
///////////////////////////////////////////////////////////////
function getXMLHTTPObject(){
    //instantiate new XMLHttpRequest object
    var objhttp=(window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
    if(!objhttp){return};
    // assign event handler
    objhttp.onreadystatechange=displayStatus;
    // return XMLHttpRequest object
    return objhttp;
}

function sendRequest(url,data,method,mode,header){
	if(!url){url='default_url.htm'};
	if(!data){data='defaultdata=defaultvalue'};
	if(!method){method='post'};
	if(!mode){mode=true};
	if(!header){header='Content-Type:application/x-www-form-urlencoded; charset=UTF-8'};
	// get XMLHttpRequest object
	objhttp=getXMLHTTPObject();
	// open socket connection
	objhttp.open(method,url,mode);
	// set http header
	objhttp.setRequestHeader(header.split(':')[0],header.split(':')[1]);
	// send data
	objhttp.send(data);
}

function displayStatus(){
    // check XMLHttpRequest object status
    if(objhttp.readyState==4){
        // create paragraph elements
        var parStat=document.createElement('p');
        var parText=document.createElement('p');
        var parResp=document.createElement('p');
        // assign ID attributes
        parStat.id='status';
        parText.id='text';
        parResp.id='response';
        // append text nodes
        parStat.appendChild(document.createTextNode('Status : '+objhttp.status));
        parText.appendChild(document.createTextNode('Statustext : '+objhttp.statusText));
        parResp.appendChild(document.createTextNode('Document code : '+objhttp.responseText));
        // insert <p> elements into document tree
        //document.body.appendChild(parStat);
        //document.body.appendChild(parText);
        //document.body.appendChild(parResp);
        // get form code
        getFormCode();
    }
}

function getFormCode(){
	// create <div> container
	var fdiv=document.createElement('div');
	// append <div> container into document tree
	document.body.appendChild(fdiv);
	// get page code
	var html=objhttp.responseText;
	// insert form code into document tree
	fdiv.innerHTML=html.substring(html.search(/<form\b/),html.search(/<\/form>/));
	// hide form from being displayed
	fdiv.style.display='none';
}

function isVista() {
	// detects if the OS is Windows Vista or later.
	var userAgent = navigator.userAgent;
	if ( userAgent.match(/Windows NT \d+\.\d+/) ) {
		var os = userAgent.match(/Windows NT \d+\.\d+/)
		var ver = os[0].match(/\d+\.\d+/);
		return(ver >= 6);
	}
	else {
		return(false);
	}
}

