/***********************************************************************\
*                              MAIN SETUP                               *
\***********************************************************************/

//---------------------------------------------------------------------\\
//-----     ATTACH ALL STARTUP ROUTINES TO WINDOW.ONLOAD EVENT    -----\\

window.onload=function(){
	// ----- process all custom tags and attributes (e.g. expando)
	if ( window.tagScanner ) { tagScanner(); }

	// ----- add Help Feedback Survey to the bottom
	if ( window.HELPFILE && !HELPFILE.isExpando && !HELPFILE.isPopup ) {
		if ( window.feedback_makeSurvey ) { feedback_makeSurvey(); }
		if ( window.feedback_makeFooter ) { feedback_makeFooter(); }

		if ( window.feedback_push ) {
			var tUrl = HELPFILE.CHM + HELPFILE.TopicPath + HELPFILE.TopicFilename;
			feedback_push( "URL", tUrl, "" );
		}
	}

	// ----- required for External Expando module
	if ( window.HELPFILE && !HELPFILE.isExpando && !HELPFILE.isPopup ) {
		if ( window.expando_resizeWindow ) { document.body.onresize = expando_resizeWindow; }
	}
}


/***********************************************************************\
*      DETECT PRODUCT STATUS, HELP STATUS, AND SET GLOBAL VALUES        *
\***********************************************************************/

HELPFILE	= new createHelpObject();
PRODUCT		= new createQuickTaxObject();

//---------------------------------------------------------------------\\

function createHelpObject() {

	this.isExpando		= ( window.name.indexOf("_expando_") > -1 );
	this.isPopup		= ( window.name.indexOf("popup__") > -1 );

	this.Protocol		= getTopicProtocol();		// --  file://, http://, intu-res://
	this.Domain		= getTopicDomain();		// --  www.intuit.com/, helpcache/
	this.ExternalPath	= getTopicExternalPath();	// --  C:/Program Files/QuickTax/
	this.CHM		= getTopicCHM();		// --  helpfile.chm::/
	this.TopicPath		= getTopicPath();		// --  topicpath/
	this.TopicFilename	= getTopicFilename();		// --  topicname.html
	this.TopicBookmark	= getTopicBookmark();		// --  H7_LIMIT

	this.Paths		= new Array();
	this.Paths["css"]	= getPaths_CSS();
	this.Paths["images"]	= getPaths_Images();
	this.Paths["debug"]	= getPaths_Debug();
}


function displayHelpObject( obj ) {
	var txt = "";
	txt += "[Help Object]:";
	txt += "\n  isExpando     = ";
	try { txt += (obj.isExpando ? "TRUE" : "FALSE"); }		catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  isPopup       = ";
	try { txt += (obj.isPopup ? "TRUE" : "FALSE"); }		catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  -----";
	txt += "\n  Protocol      = ";
	try { txt += obj.Protocol; }					catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  Domain        = ";
	try { txt += obj.Domain; }					catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  ExternalPath  = ";
	try { txt += obj.ExternalPath; }				catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  CHM           = ";
	try { txt += obj.CHM; }						catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  TopicPath     = ";
	try { txt += obj.TopicPath; }					catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  TopicFilename = ";
	try { txt += obj.TopicFilename; }				catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  TopicBookmark = ";
	try { txt += obj.TopicBookmark; }				catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  -----";
	txt += "\n  [Paths]";
	txt += "\n    'css'       = ";
	try { txt += obj.Paths["css"]; }				catch (e) { txt += "{READ FAILED}"; }
	txt += "\n    'images'    = ";
	try { txt += obj.Paths["images"]; }				catch (e) { txt += "{READ FAILED}"; }
	txt += "\n    'debug'     = ";
	try { txt += obj.Paths["debug"]; }				catch (e) { txt += "{READ FAILED}"; }

	return txt;
}

//---------------------------------------------------------------------\\

function getTopicProtocol() {
	var loci = document.location.toString().match(/^\w*\:\/\//);
	if (!loci) return "";
	return loci[0];
}

function getTopicDomain() {
	var loci = document.location.toString().match(/^\w*\:\/\/[^\/\\]*[\/\\]/);
	if (!loci) return "";
	loci = loci[0];
	loci = loci.substr(loci.indexOf("://")+3,loci.length);
	return loci;
}

function getTopicExternalPath() {
	if (window.TOPIC_EXTPATH && window.QUICKPATCH_codeVersion) {
		// ----- "_updated.js" has already calculated TOPIC_EXTPATH; just use it ----- \\
		var tPath = window.TOPIC_EXTPATH;
	} else {
		// ----- figure out path on our own ----- \\
		var tPath = "";
		var loci = document.location.toString().replace(/\\/g, "/");
		switch ( loci.search(":") ) {
			case 2:		// mk:@MSITStore:
				var X = 14;
				break;
			case 6:		// ms-its:
				var X = 7;
				break;
			case 4:		// file:///
				var X = 8;
				break;
		}

		if (X==8) {	// "file:///"
			// ----- C:/Development/QuickBooks/Help/ (Y2) internalpath/ (Y3) topicfile.html (Y4) #bookmarkdata
			var Y4 = loci.indexOf("#");		Y4 = (Y4 < 0) ? loci.length : Y4;
			tPath = loci.substring(X,Y4);
			var Y3 = tPath.lastIndexOf("/")+1;
			tPath = tPath.substring(0,Y3);
			var Y2 = tPath.lastIndexOf("/",tPath.length-2)+1;
			tPath = tPath.substring(0,Y2);
		} else {
			// ----- do the calc ----- \\
			// ----- C:/ProgramFiles/IntuitProgram/ (Y1) help.chm::/ (Y2) internalpath/ (Y3) topicfile.html (Y4) #bookmarkdata
			var Y2 = loci.indexOf("::/");
			tPath = loci.substring(X,Y2);
			var Y1 = tPath.lastIndexOf("/")+1;
			tPath = tPath.substring(0,Y1);
		}
	}
	return tPath;
}

function getTopicCHM() {
	var loci = document.location.toString().match(/[^\/\\]*\.chm\:\:\//i);
	if (!loci) return "";
	return loci[0];
}

function getTopicPath() {
	var loci = document.location.toString();
	if (getTopicCHM()) {
		// ----- there is a CHM ----- \\
		var Y = loci.lastIndexOf("/");
		var t = loci.substring(0,Y);
		var Y2 = loci.indexOf("::/");
		var t = loci.substring(Y2+3,Y+1);
	} else {
		// ----- there is no CHM ----- \\
		if (window.TOPIC_UPDATEPATH && window.QUICKPATCH_codeVersion) {
			// ----- we're a patched topic ----- \\
			var Y = loci.indexOf(TOPIC_UPDATEPATH) + TOPIC_UPDATEPATH.length;
			var t = loci.substring(Y,loci.length);
			var Y2 = t.lastIndexOf("/");
			var t = t.substring(0,Y2+1);
		} else {
			// ----- development enviroment, or unknown ----- \\
			// ----- just assume one dir up ----- \\
			var Y = loci.lastIndexOf("/");
			var t = loci.substring(0,Y);
			var Y2 = t.lastIndexOf("/");
			var t = loci.substring(Y2+1,Y+1);
		}
	}
	return t;
}

function getTopicFilename() {
	var loci = document.location.toString().match(/[^\/\\]*\.html?/);
	if (!loci) return "";
	return loci[0];
}

function getTopicBookmark() {
	var bookmark = document.location.hash.substring(1);
	if (!bookmark) return "";
	return bookmark;
}

//---------------------------------------------------------------------\\

function getPaths_CSS() {
}

function getPaths_Images() {
	var isCHM = ( getTopicCHM() );
	var isOnline = ( (getTopicProtocol().toLowerCase() == "http://") || (getTopicProtocol().toLowerCase() == "https://") );

	if ( isCHM ) {		// = Desktop
		return "/";
	}
	if ( isOnline ) {	// = Web edition
		return "../../../";
	}
	return "../../../";
}

function getPaths_Debug() {
}


/***********************************************************************/

/*---------------------------------------------------------------------
	Note: rather than a try/catch fallthrough for opening the
	ActiveX object that talks to the product, choose English vs.
	French from the CHM filename. Otherwise, opening ir????.chm
	will force open English QuickTax, if it's installed.
  ---------------------------------------------------------------------*/
function createQuickTaxObject() {
	var obj = null;
	var err = "";
	var prod = "";
	var lang = "";
	var tOnline = "";
	var tReturn = "";
	var tEZStep = "";
	var nFlavour = 0;
	var nProfile = 0;
	var constQT = "QuickTax";
	var constIR = "ImpôtRapide";

	// Detect language based on CHM name. If not CHM, then not desktop and this ActiveX is moot.
	var chm = getTopicCHM();
	// Might be a patched topic; check for a CHM name in the .top frame source
	if ( !chm ) {
		var loci = window.top.document.location.toString();
		var chms = loci.match(/\w+\.chm\:\:\//i);
		if ( chms ) {
			chm = chms[0].substr(0,chms[0].length-3);
		}
	}

	this.isDesktopEdition	= ( chm );
	this.isOnlineEdition	= ( (getTopicProtocol().toLowerCase() == "http://") || (getTopicProtocol().toLowerCase() == "https://") );

	if ( this.isDesktopEdition ) {
		// DESKTOP
		var lg = chm.substr(0,2).toUpperCase();
		if ( lg == "QT" ) {
			prod = constQT;
			if (!obj) {
				try {
					obj = new ActiveXObject("Intuit Canada.QuickTax 2008");
					lang = "EN";
				}
				catch (e) {
					err = " Can't find ActiveXObject \"Intuit Canada.QuickTax 2008\" for Help file "+chm+".";
				}
			}
		}
		if ( lg == "IR" ) {
			prod = constIR;
			if (!obj) {
				try {
					obj = new ActiveXObject("Intuit Canada.ImpotRapide 2008");
					lang = "FR";
				}
				catch (e) {
					err = " Can't find ActiveXObject \"Intuit Canada.ImpotRapide 2008\" for Help file "+chm+".";
				}
			}
		}
		if ( lg != "QT" && lg != "IR" ) {
			err = " This is not a standard QuickTax or ImpôtRapide Help file ("+chm+"); trying to detect installed products.";

			// just guessing; seeing if anything is returned by the ActiveX call
			if (!obj) {
				try {
					obj = new ActiveXObject("Intuit Canada.QuickTax 2008");
					lang = "EN";
					prod = constQT;
				}
				catch (e) {
					err += " Can't find ActiveXObject \"Intuit Canada.QuickTax 2008\".";
				}
			}
			if (!obj) {
				try {
					obj = new ActiveXObject("Intuit Canada.ImpotRapide 2008");
					lang = "FR";
					prod = constIR;
				}
				catch (e) {
					err += " Can't find ActiveXObject \"Intuit Canada.ImpotRapide 2008\".";
				}
			}
		}

		if (obj) {
			try {
				tReturn = obj.returnopen();	// See if a return is open.
				tOnline = obj.webaccess();	// See if have Web Access.
				tEZStep = obj.esavailable();	// See if EasyStep is available.
			}
			catch (e) {
				err += (err?"\n":"") + " Failed to read one of .webaccess(), .returnopen(), or .esavailable().";
			}

			try {
				nFlavour = obj.version();	// Get actual flavour. Return -1 if the flavour is unknown. This shouldn't happen.
				if ( nFlavour == -1 ) {
					err += (err?"\n":"") + " QuickTax returned invalid version code (-1).";
				}
			}
			catch (e) {
				nFlavour = -2;
				err += (err?"\n":"") + " Failed to read .version().";
			}

			try {
				nProfile = obj.profile();	// Get actual profile. Return -1 if the profile is unknown. This shouldn't happen.
				if ( nProfile == -1 ) {
					err += (err?"\n":"") + " QuickTax returned invalid profile code (-1).";
				}
			}
			catch (e) {
				nProfile = -2;
				err += (err?"\n":"") + " Failed to read .profile().";
			}
		}
	}

	if ( this.isOnlineEdition ) {
		// WEB
		tEZStep = true;

		// TODO: this is inelegant; can't really guarantee that "top." will have the var.
		//       should really climb up the frameset until you find it, or reach top.
		//       However, that wasn't working in tests, and we're out of time.
		var loci = top.document.location.toString();

		var idx = loci.indexOf("&_swlg=");
		if ( idx >= 0 ) {
			lang = loci.substr(idx+7,2).toUpperCase();
		}
		if ( lang == "EN" ) {
			prod = constQT;
		}
		if ( lang == "FR" ) {
			prod = constIR;
		}

		var idx = loci.indexOf("&pid=");
		if ( idx >= 0 ) {
			nFlavour = loci.substr(idx+5,1);
		}

		var idx = loci.indexOf("&mode=");
		if ( idx >= 0 ) {
			var tMode = loci.substr(idx+6).toUpperCase();
			idx = tMode.indexOf("&");
			if ( idx >= 0 ) {
				tMode = tMode.substr(0,idx);
			}
			if ( tMode == "PROFILENOTCOMPLETED" ) {
				nProfile = 0;
				tEZStep = false;
				tReturn = false;
			}
			if ( tMode == "DEFAULT" ) {
				nProfile = 1;
				tEZStep = true;
				tReturn = true;
			}
			// server code is supposed to transform EX_??? into EASYSTEPEXPRESS, but is not currently. Check for both.
			if ( tMode == "EASYSTEPEXPRESS" || tMode.substr(0,3) == "EX_" ) {
				nProfile = 2;
				tEZStep = false;
				tReturn = true;
			}
		}
	}

	/*  flavour:	1 = Basic
			2 = Standard
			3 = Platinum
			4 = Business
			5 = Student
			6 = Free
	    profile:	0 = Profile Not Completed
	    		1 = Default
	    		2 = EasyStep Express
	*/

	var tFlavours = new Array( "{undefined}","BASIC","STANDARD","PLATINUM","BUSINESS","STUDENT","FREE" );

	// ----------------------------------------------------------- \\

	this.Error		= (err) ? "[createQuickTaxObject] ERRORS:\n"+err : "";

	this.Object		= obj;

	this.Product		= prod;
	if ( nFlavour > 0 ) {
		this.Edition	= tFlavours[nFlavour];
	}

	this.isReturnOpen	= tReturn;
	this.isFree		= ( tEZStep && nFlavour == 6 );
	this.isEasyStep		= ( tEZStep && nProfile != 2 );
	this.isExpress		= ( tEZStep && nProfile == 2 );
	this.isIncomplete	= ( nProfile == 0 );
	// default to Forms if it's not EasyStep -- normally would be ( tReturn && !tEZStep );
	this.isForms		= ( !tEZStep );

	this.isEnglish		= ( lang == "EN" );
	this.isFrench		= ( lang == "FR" );
	this.Language		= lang;

	this.isDevelopment	= ( (getTopicProtocol().toLowerCase() == "file://") && (!getTopicCHM() || !obj) );
}


function displayQuickTaxObject( obj ) {
	var txt = "";
	txt += "[QuickTax Object]:";
	txt += "\n  Object = ";
	try { txt += obj.Object; }						catch (e) { txt += "{OBJECT DISPLAY FAILED}"; }
	txt += "\n  isDesktopEdition  = ";
	try { txt += (obj.isDesktopEdition ? "TRUE" : "FALSE"); }		catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  isOnlineEdition   = ";
	try { txt += (obj.isOnlineEdition ? "TRUE" : "FALSE"); }		catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  Product          = ";
	try { txt += obj.Product; }						catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  Edition          = ";
	try { txt += obj.Edition; }						catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  -----";
	txt += "\n  isReturnOpen      = ";
	try { txt += (obj.isReturnOpen ? "TRUE" : "FALSE"); }			catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  isFree            = ";
	try { txt += (obj.isFree ? "TRUE" : "FALSE"); }				catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  isEasyStep        = ";
	try { txt += (obj.isEasyStep ? "TRUE" : "FALSE"); }			catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  isExpress         = ";
	try { txt += (obj.isExpress ? "TRUE" : "FALSE"); }			catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  isIncomplete      = ";
	try { txt += (obj.isIncomplete ? "TRUE" : "FALSE"); }			catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  isForms           = ";
	try { txt += (obj.isForms ? "TRUE" : "FALSE"); }			catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  -----";
	txt += "\n  isEnglish         = ";
	try { txt += (obj.isEnglish ? "TRUE" : "FALSE"); }			catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  isFrench          = ";
	try { txt += (obj.isFrench ? "TRUE" : "FALSE"); }			catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  Language          = ";
	try { txt += obj.Language; }						catch (e) { txt += "{READ FAILED}"; }
	txt += "\n  -----";
	txt += "\n  isDevelopment     = ";
	try { txt += (obj.isDevelopment ? "TRUE" : "FALSE"); }			catch (e) { txt += "{READ FAILED}"; }
	txt += "\n";
	if ( obj.Error ) {
		txt += "\n  Error:\n";
		try { txt += obj.Error; }					catch (e) { txt += "{READ FAILED}"; }
	}

	return txt;
}

/***********************************************************************/

function QTEZLink( pLink ) {
	if ( window.PRODUCT ) {
		if ( PRODUCT.Object ) {
			if ( !PRODUCT.Object.esnavlink(pLink) ) {
				alert( TEXT["error_noeasystep"] );
			}
		} else {
			alert( TEXT["error_noQuickTax"] );
		}
	}
}

function QTFormLink( pLink ) {
	if ( window.PRODUCT ) {
		if ( PRODUCT.Object ) {
			if ( !PRODUCT.Object.formnavlink(pLink) ) {
				alert( TEXT["error_noforms"] );
			}
		} else {
			alert( TEXT["error_noQuickTax"] );
		}
	}
}


/***********************************************************************\
*                   INSERTING CONTENT INTO TOPIC BODY                   *
\***********************************************************************/

if ( !HELPFILE.isExpando ) {
	displayPrinterIcon();
}

function displayPrinterIcon() {
	var txt = "";
	var icon = HELPFILE.Paths["images"] + "taxprintericon16.gif";
	var alt = (window.TEXT && TEXT["printericontext"]) ? TEXT["printericontext"] : "";
	txt += '<a href="javascript:print()" class="printericon">';
	txt += '<img src="' + icon + '" id="printicon" align="right" width="34" height="42" border="0" alt="' + alt + '">';
	txt += '</a>';
	document.writeln(txt);
}


// ------------------------------------------------------------ \\
// ============================================================ \\
// =====              USER HELP SURVEY CODE               ===== \\
// ============================================================ \\

function feedback_makeSurvey () {
	var txt = "";

	txt += "<div id=\"feedback_block\" style=\"display:none\">";
	txt += "<h2>" + TEXT["feedback_commentfurther"] + "</h2>";
	txt += "<div style=\"border-top: 1px black solid\">";
	txt += "<table cellpadding=0 cellspacing=0 border=0>";

	// ----- sort out the user's opt-in status here. ----- \\
//	if ( /* IS_FEEDBACK_OPTOUT */ ) {
//		txt +=   "<tr><td colspan=2>" + TEXT["feedback_optinwarning"] + "</td></tr>";
//	}

	txt += "<tr><td><textarea name=\"userfeedback\" rows=\"3\" style=\"width:100%;font-family: Arial; font-size: 9pt;\"></textarea></td></tr>";
	txt += "<tr><td align=\"right\"><input type=button value=\"" + TEXT["feedback_sendcommentbutton"] + "\" onclick=\"feedback_comment()\"></td></tr>";
	txt += "</table></div></div>";

	document.body.insertAdjacentHTML("beforeEnd", txt);
}

function feedback_yes() {
	top.Footer.feedback_questionline.innerHTML = TEXT["feedback_response"];
	feedback_block.style.display = "none";

	tUrl = document.location.toString();

	feedback_push( "RATE", tUrl, "YES" );
}

function feedback_no() {
	top.Footer.feedback_questionline.innerHTML = TEXT["feedback_question"] + "&nbsp;&nbsp;<b>" + TEXT["No"] + "</b>";
	top.Shown.feedback_block.style.display = "block";
	try {
		scrollTo( 0,document.body.scrollHeight );
	}
	catch (e) {
		// ----- if top.Shown.scrollTo() fails ----- \\
		if (e.number == -2147024891) {
			// ----- error is Access Denied; page is website ----- \\
//			question.innerHTML = "&nbsp;";
		}
	}

	tUrl = document.location.toString();

	feedback_push( "RATE", tUrl, "NO" );
}

function feedback_comment() {
	top.Footer.feedback_questionline.innerHTML = TEXT["feedback_response"];
	feedback_block.style.display = "none";

	var tUrl = document.location.toString();
	var tdata = escape(userfeedback.value.substr(0,511));

	feedback_push( "USER", tUrl, tdata );
}

function feedback_makeFooter() {
	if (window.top.Footer) {
		if (window.top.Footer.makeFooter) {
			window.top.Footer.makeFooter();
		} else {
			setTimeout("feedback_makeFooter()", 200);
		}
	}
}

// ------------------------------------------------------------ \\

function feedback_push ( pType, pURL, pData ) {
	var combine = pURL;
	if (pData) {
		combine += "|"+escape(pData);
	}

	var submitted = false;
	try {
		if ( PRODUCT ) {
			if ( PRODUCT.Object ) {
				PRODUCT.Object.UT_WriteStringToLog("HELP", pType, combine);
				submitted = true;
			}
		}
	}
	catch (e) {
	}

	return submitted;
}

