// ~/scripts/dajslib1b.js
// Copyright Doug Ashbaugh 2009 2010

var tcDebug = false;
var tcScriptName = '~/scripts/dajslib1b.js';
var tcCustomValidatorFn = function tcDoNothing(){ alert('override tcPageValidatorFn()'); }  // override with validator function name.

// Setup crude function aliases to help programmers.
function getDomObj(id) { return(tcGetDomObj(id)); }
function showhide(id) { return(tcShowHide(id)); }

// Begin core functions.
function tcGetDomObj(id) {
	try {
		if (document.getElementById){
			return(document.getElementById(id));
		} else {
			alert("Your web browser does not support JavaScript sufficient for use. Please use a modern web browser that fully support JavaScript and the DOM object model.");
			return(false);
		}
	} catch(e) {
		alert("Error occurred in tcDomObj() during attempt to access DOM object: " + id);
	}
}

function tcLogit(msg){
	try {
		if (tcDebug == false) {
			return(true);
		}
		var finalMsg;
		finalMsg = 'Survey Debug (' + tcScriptName +'): ' + msg + '<br>';
		var logObj = tcGetDomObj('logger');
		logObj.innerHTML+=finalMsg;
		tcShowDiv('logger');
	} catch(e) {
		alert('Error occurred in tcLogit function with msg = ' + msg + ", error: " + e);
		return(false);
	}
	return(true);
}

tcLogit('Loading started.');

tcLogit('Initializing function tcGetValFromList...'); 
function tcGetValFromList(id, adj){
	try {
		var pagesObj = tcGetDomObj(id);
		var index = pagesObj.selectedIndex;
		var val = 0;
		//alert('tcGetValFromList index is: ' + index);
		//if (index > 0) {
			val = pagesObj.options[index].value*1.0 + adj*1.0;
			if (val == '' || isNaN(val)) { // Nothing selected, return 0. Handled fifferently in IE || FireFox
				val=0;
			}
		//}
		return(val);
	} catch(e){
		alert('Error occured in getValFromList on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

function tcGetStrValFromList(id){
	try {
		var pagesObj = tcGetDomObj(id);
		var index = pagesObj.selectedIndex;
		var val = pagesObj.options[index].value;
		return(val);
	} catch(e){
		alert('Error occured in pscGetStrValFromList on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcShowDiv..."); 
function tcShowDiv(id){
	try {
		var divObj = tcGetDomObj(id);
		divObj.style.display='block';
	} catch(e){
		alert('The page is still loading. Try again in a moment. System Message: tcShowDiv(' + id + ')');
		return(false);
	}
	return(true);
}

tcLogit("Initializing function tcHideDiv...");
function tcHideDiv(id){
	try {
		var divObj = tcGetDomObj(id);
		divObj.style.display='none';
	} catch(e){
		alert('Error occured in tcHideDiv on id ' + id + '. Error msg: ' + e);
		return(false);
	}
	return(true);
}

tcLogit("Initializing function tcShowHide...");
function tcShowHide(id){
	try {
		var domobj = tcGetDomObj(id);
		var divDisplayState = domobj.style.display;
		if (divDisplayState == "none"){
			tcShowDiv(id);
		} else {
			tcHideDiv(id);
		}
	} catch(e){
		alert('Error occured in tcShowHide() on id ' + id + '. Error msg: ' + e);
		return(false);
	}
	return(true);
}

function tcShowImg(id){
	try {
		tcShowDiv(id);
	} catch(e){
		alert('Error occurred in tcShowImg function with e.message=' + e.message + ", e.name=" + e.name);
		return(false);	
	}
}

function tcHideImg(id){
	try {
		tcHideDiv(id);
	} catch(e){
		alert('Error occurred in tcHideImg function with e.message=' + e.message + ", e.name=" + e.name);
		return(false);	
	}
}

tcLogit("Initializing function tcGetVal...");
function tcGetVal(id) {
	try {
		var domObj = tcGetDomObj(id);
		var v = domObj.value;
		return(v);
	} catch(e) {
		alert('Error occured in tcGetVal on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcIsChecked..."); 
function tcIsChecked(id){
	try {
		var domObj = tcGetDomObj(id);
		return(domObj.checked);
	} catch(e) {
		alert('Error occured in tcIsChecked on id ' + id + '. Error msg: ' + e);
		return(-1);
	}
}

tcLogit("Initializing function tcUncheck..."); 
function tcUncheck(id){
	try {
		var domObj = tcGetDomObj(id);
		domObj.checked = false;
		return(true);
	} catch(e) {
		alert('Error occured in tcUncheck on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcCheck..."); 
function tcCheck(id){
	try {
		var domObj = tcGetDomObj(id);
		domObj.checked = true;
		return(true);
	} catch(e) {
		alert('Error occured in tcCheck on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcSetVal..."); 
function tcSetVal(id, v) {
	try {
		var domObj = tcGetDomObj(id);
		domObj.value = v;
		return(true);
	} catch(e) {
		alert('Error occured in tcSetVal on id=[' + id + '] and v=[' + v + '] Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcGetHtml..."); 
function tcGetHtml(id) {
	try {
		var domObj = tcGetDomObj(id);
		return( domObj.innerHTML );
	} catch(e) {
		alert('Error occured in getHtml on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcSetHtml..."); 
function tcSetHtml(id, v) {
	try {
		var domObj = tcGetDomObj(id);
		domObj.innerHTML = v;
		return(true);
	} catch(e) {
		alert('Error occured in setHtml on id=[' + id + '] and v=[' + v + '] Error msg: ' + e);
		return(false);
	}
}

// tcMakeReadable deprecated and replaced with tcMakeWriteable starting in v1b. DLA
tcLogit("Initializing function tcMakeReadable...");
function tcMakeReadable(id){		
	try {
		var domObj = tcGetDomObj(id);
		domObj.readOnly=false;
		domObj.style.backgroundColor='#FFFFFF';
	} catch(e) {
		alert('Error occured in tcMakeReadable on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcMakeWriteable...");
function tcMakeWriteable(id){
	try {
		var domObj = tcGetDomObj(id);
		domObj.readOnly=false;
		domObj.style.backgroundColor='#FFFFFF';
	} catch(e) {
		alert('Error occured in tcMakeWriteable on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcMakeReadOnly...");
function tcMakeReadOnly(id){
	try {
		document.getElementById(id).readOnly=true;
		document.getElementById(id).style.backgroundColor='#DEDEDE';
	} catch(e) {
		alert('Error occured in tcMakeReadable on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcEnableTextBox...");
function tcEnableTextBox(id){
	try {
		document.getElementById(id).disabled=false;
		document.getElementById(id).style.backgroundColor='#FFFFFF';
	} catch(e) {
		alert('Error occured in enableTextBox on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcEnableTextBoxColor...");
function tcEnableTextBoxColor(id, color){
	var c = '#FFFFFF';
	try {
		if ( c != '' ) {
			c = color;
		}
		document.getElementById(id).disabled=false;
		document.getElementById(id).style.backgroundColor=c;
	} catch(e) {
		alert('Error occured in enableTextBoxColor on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcDisableTextBox...");
function tcDisableTextBox(id){
	try {
		document.getElementById(id).disabled=true;
		document.getElementById(id).style.backgroundColor='#DDDDDD';
	} catch(e) {	
		alert('Error occured in disableTextBox on id ' + id + '. Error msg: ' + e);
		return(false);
	}
}

tcLogit("Initializing function tcDisableTextBoxColor...");
function tcDisableTextBoxColor(id, color){
	var c = '#DDDDDD';
	if ( c != '' ) {
		c = color;
	}
	try {
		document.getElementById(id).disabled=true;
		document.getElementById(id).style.backgroundColor=c;
	} catch(e) {
		alert('Error occured in disableTextBoxColor on id ' + id + '. Error msg: ' + e);
		return(false);	
	}
}

/*
	Attach event methods; supporting browsers like NS4 or IE5Mac which don't support either attachEvent or addEventListener.	
*/
tcLogit("Initializing function tcMyAttachEvent...");
function tcMyAttachEvent(obj,evt,fnc){
	try {
		if (!obj.myEvents) obj.myEvents={};
		if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
		var evts = obj.myEvents[evt];
		evts[evts.length]=fnc;
	} catch(e) {
		alert("Error occurred in tcMyAttachEvent");
		return(false);
	}
	return(true);
}

tcLogit("Initializing function tcMyFireEvent...");
function tcMyFireEvent(obj,evt){
    try {
		if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
		var evts = obj.myEvents[evt];
		for (var i=0,len=evts.length;i<len;i++) evts[i]();
	} catch(e) {
		alert("Error occurred in tcMyFireEvent");
		return(false);
	}
	return(true);
}

/* 
 tcAttachEvent(document.getElementById(strId), strEventType, refFn, false (capture event), 'dbg comments');
*/
tcLogit("Initializing function tcAttachEvent...");
function tcAttachEvent(obj,evt,fnc,useCapture,note){
	try {
		tcLogit('tcAttachEvent entered for ' + note);
		if (!useCapture) useCapture=false;
		if (obj.addEventListener){
		    tcLogit('tcAttachEvent method 1 used.');
			obj.addEventListener(evt,fnc,useCapture);
			return true;
		} else {
			tcLogit('tcAttachEvent method 2 used.');
			if (obj.attachEvent) {
				return obj.attachEvent("on"+evt,fnc);
			} else {
				tcLogit('tcAttachEvent method 3 used.');
				tcMyAttachEvent(obj,evt,fnc);
				obj['on'+evt]=function(){ tcMyFireEvent(obj,evt) };
			}
		}
	} catch(e) {
		alert("Error occurred in tcAttachEvent for " + note);
		return(false);
	}
	return(true);
}

/* 
	Attach an onload event to the master form (chains events)
	Example: tcAddLoadEvent(fToRunOnLoad);
*/
tcLogit("Initializing function tcAddOnLoadEvent...");
function tcAddOnLoadEvent(func) {
	//tcLogit("tcAddOnLoadEvent() adding onLoad function: " + func);
	try {
		var oldonload = window.onload;	
		if ( typeof window.onload != "function" ) {
			window.onload = func;
		} else {
			window.onload = function(){
				oldonload();
				func();		
			}
		}
	} catch(e) {
		alert("Error occurred in function tcAddOnLoadEvent(). Error: " + e);
	}
}

/*
	Send the standard CSS string to hide the standard button set
*/
tcLogit("Initializing function tcHideButtons...");
function tcHideButtons(){
	try {
  		var cssStr = '<link rel="stylesheet" type="text/css" href="https://surveycenter.tc.com/surveys/tc/css/generic/hide_buttons.css" />';  
	  	document.write(cssStr);
	} catch(e) {
		alert("Error occurred while trying to hide buttons via dynamic CSS");
	}
}

tcLogit("Initializing function tcCustomButtons...");
function tcCustomButtons(prev, next, save, jump, subm, rset, efmFirst) {
	var strBut='';
	if ( prev == true ) { prev = "Previous Page"; }
	if ( next == true ) { next = "Next Page"; }
	if ( save == true ) { save = "Save Responses for Later Processing"; }
	if ( jump == true ) { jump = "Jump To Other Page"; }
	if ( subm == true ) { subm = "Submit Survey Responses"; }
	if ( rset == true ) { rset = "Clear Fields on this Page"; }
	var algo = '';
	if ( efmFirst ) {
		algo = 'tcValidateEfmCustom()'; // call EFMs validators before custom
	} else {
		algo = 'tcValidateCustomEfm()'; // call custom validators before EFMs
	}
	try {
		// Previous Page Button
		if (prev) {
			strBut = "<input class='submit-button-custom' type='submit' name='back' value='" + prev + 
				"' onclick=\"document.PdcSurvey.PdcButtonPressed.value='back';\" />";
			document.write(strBut);
		}
	
		// Next Page Button
		if ( next ) {
			strBut = "<input class='submit-button-custom' type='submit' name='next' value='" + next +
				"' onclick=\"document.PdcSurvey.PdcButtonPressed.value='next'; return("+algo+");\" />";
			document.write(strBut);
		}
		
		// Save for Later Button
		if ( save ) {
			strBut = "<input class='submit-button-custom' type='submit' name='save' value='" + save +
				"' onclick=\"document.PdcSurvey.PdcButtonPressed.value='save'; return("+algo+");\" />";
			document.write(strBut);
		}

		// Jump Pges Button
		if ( jump ) {
			strBut = "<input onclick='PdcShowJumpPageEx();' class='submit-button-custom' type='button' name='jump' value='"+jump+"' />";
			document.write(strBut);
		}
		
		// Submit Survey Button
		if ( subm ) {
			strBut = "<input class='submit-button-custom' type='submit' name='submit' value='" + subm +
				"' onclick=\"document.PdcSurvey.PdcButtonPressed.value='submit';\" />";
			document.write(strBut);
		}
		// Reset Form Button
		if ( rset ) {
			strBut = "<input class='submit-button-custom' type='reset' name='reset' value='" + rset + "' onclick=\"confirm('Ok to Clear all fields on this page?');\" />";
			document.write(strBut);
		}
	} catch(e) {
		alert("Error occurred during write of custom button set.");	
	}
}

/* 
	validateAllEfm(strFname) - used to call our validator function and then if tests pass, call EFMs validator.
	Example: onclick="return(tcValidateAllEfm(ourValidatorFunction));"
	tcPageValidatorFn should be set to the current custom validator. Default validator function can be used.
*/
tcLogit("Initializing function tcValidateCustomEfm...");
function tcValidateCustomEfm() {
	try {
		if ( tcCustomValidatorFn() ) {
			return(PdcProcessPage()); // standard EFM page processing.
		} else {
			return(false);
		}
	} catch(e) {
		alert('Error in function tcValidateCustomEfm() Error: ' + e);
	}
}

// This simply reverses the oder to call EFM validator first and then ours.
tcLogit("Initializing function tcValidateEfmCustom..");
function tcValidateEfmCustom() {
	try {
		if ( PdcProcessPage() ) {
			return( tcCustomValidatorFn() ); // standard EFM page processing.
		} else {
			return(false);
		}
	} catch(e) {
		alert('Error in function tcValidateEfmCustom() Error: ' + e);
	}
}

// Function to test N radio buttons by ids separated by pipe char to see if any are checked
// Ex: tcRadiosCheckedByIds('Q35_1|Q35_2|Q35_3');
function tcRadiosCheckedByIds( idChain ) {
	var radButIds = new Array();
	radButIds = idChain.split("|");
	var radCnt = radButIds.length;
	var rc = false;
	for (var i=0; i<radCnt; i++){
		if ( tcIsChecked(radButIds[i]) ) {
			rc = true;
			break;
		} 
	}
	return(rc);
}

// Function to test N radio buttons to see if any are checked
// Ex: tcRadiosChecked('Q35', 3) // tests Q35_1, Q35_2, Q35_3
function tcRadiosChecked(baseId, range) {
	var rc = false;
	var id = baseId;
	for (var i=1; i<=range; i++){
		id = baseId + '_' + i;
		if ( tcIsChecked(id) ) {
			rc = true;
			break;
		}
	}
	return(rc);
}

// Function tcToggleDiv(id1, id2)
// Ex: tcToggleDiv(strId, strDiv)
function tcToggleDiv( strId, strDivId ) {
	try {		
		if ( tcIsChecked(strId) ) {
			tcShowDiv( strDivId );
		} else {
			tcHideDiv( strDivId );
		}
	} catch(e) {
		alert('Error in function tcToggleDiv('+strId+','+strDivId+'). Exception: ' + e);
		return(false);
	}
}

// Function tcClearVal(strId) - clears the value of an element.
// Ex: tcClearVal(strId)
function tcClearVal( strId ) {
	try {
		tcSetVal(strId, '');
	} catch(e) {
		alert('Error in function tcClearVal('+strId+'). Exception: ' + e);
		return(false);
	}
}

// Function tcClearHtml(strId) - Clears the innerHTML of an element.
// Ex: tcClearHtml(strId)
function tcClearHtml( strId ) {
	try {
		tcSetHtml(strId, '');
	} catch(e) {
		alert('Error in function tcClearHtml('+strId+'). Exception: ' + e);
		return(false);
	}
}

function tcJumpToAnchor(strId){
	try {
		document.location.href=strId;
	} catch(e) {
		alert('Error in function tcJumpToAnchor('+strId+'). Exception: ' + e);
		return(false);
	}
}

// Function to get the value from a radio button set. 
// Returned empty string if no radio button is selected. 
// Form name is optional. Default form is ad submitter (frmSed)
function tcGetRadioButtonValue(form, id){ 
	try { 
		var v = ''; 
		var step=0; 
		
		if ( form == '' ){ 
				form = 'frmSed'; // default to ad editor form
		} 

		step = 1; 
		tcLogit('tcGetRadioButtonValue(): form = '+ form); 

		step = 2; 
		var radObj = document.forms[form].elements[id]; 
		
		step = 3; 
		for (var i=0; i < radObj.length; i++) { 
			if (radObj[i].checked){ 
				v = radObj[i].value;
				break;
			} 
		} 
		return(v); 
			
	} catch(e) { 
			alert('Error in function jslib::getRadioButtonValue(). step='+step + ', name=' + e.name + ', msg=' + e.message + ', error:' + e); 
	}         
}

// Convert string or number to integer
function tcIntVal( mixed_var ) { 
	try {
		return( parseInt( mixed_var ) );
	} catch(e) {
		alert('Error in function jslib::tcIntVal('+strId+'). Exception: ' + e); 
		return(0); 
	}
} 

function tcPause(ms){
	try {
		var date = new Date();
		var curDate = null;
		do { curDate = new Date(); } while( curDate - date < ms ); 	
	} catch(e) {
		alert('Error in function jslib::tcPause('+ms+'). Exception: ' + e.name + '/' + e.message); 
		return(0); 
	}
}

function tcLtrim(s){var pat = /^\s+/;return(s.replace(pat,''));}
function tcRtrim(s){var pat = /\s+$/;return(s.replace(pat,''));}
function tcTrim(str){return(tcRtrim(tcLtrim(str)));}

tcLogit('Loading complete.');
//alert('dajslib1b.js loaded.');
/* EOF */