<!--

// ======================================================================
//
// jsBSWGeneric.js
// 
// Generic useful javascript functions
//
// ======================================================================
// MODULE CHANGES
// ======================================================================
// 07-May-2005	Errol
// - ENH -		Added LoadCombo and ClearCombo
//			-	Condensed the two IsDisabledSelfOrParents functions
//
// 02-May-2005	Errol
// - ENH -		Added ReplaceTokens and CountSubStr
//
// 15-Apr-2005	Errol
// - ENH -		Added SelectAllCheckboxes, SetControlValue, SetVisibility
//
// 25-Oct-2004	Errol
// - ENH -		Added IsDisabledSelfOrParents_Ctl as I had hoped that then 
//              a simple form based check CheckSubmit using 
//              activeElement could be used, but that crapped out as
//              it works as expected when click is on enabled grid, 
//              but when on disabled grid, a submit is still fired, 
//              but the activeElement is a <TD> object?!?!?!?!?
//
// 20-Oct-2004  Errol
// - NEW -      Initial implementation,
//				(mostly taken from TDOC and improved)
//
// ======================================================================



// ======================================================================
// Gets count of characters in source 
// Places it into target
// Returns the count
// ======================================================================
function UpdateTextCount(strSource, strTarget) {
    //alert("UpdateTextCount called.");
    
//    var ctlSource = document.getElementById(strSource);
//    if (!ctlSource) return
    //alert(src.value);
    
//    var ctlTarget = document.getElementById(strTarget);
//    if (!ctlTarget) return
    //alert(tar.value);
    
    var cnt = GetControlValue(strSource).length;
    SetControlValue(strTarget, cnt);
    
    return cnt;
}


// ======================================================================
// Confirms
// 1. Requesting ctl is not on a disabled parent (ie div etc)
// 2. That the user wishes to delete 
//
// NOTE: THERE IS A DEPENDENT PROCEDURE IN modBSWSWEBForms
// ======================================================================
function ConfirmDelete(ctl, strDetails) {
    //alert("ConfirmDeleteRow called. strRowID=" + strRowID + " strDetails=" + strDetails);
    //debugger;
    if (IsDisabledSelfOrParents(ctl)) { return false; }

    return confirm("Are you sure you wish to delete [" 
            + strDetails + "] and all its details?");
            
}



// ======================================================================
// Determines if any parent element of passed ctl has been disabled
// ======================================================================
function IsDisabledSelfOrParents(ctl) {
    //debugger;

    ctl = CtlFromRefOrId(ctl);
    for (var i = 0; ctl.tagName.toLowerCase() != "body" && i < 100; i++) {

        ctl = ctl.parentElement;                

        if (!ctl) { return false; }        
        //alert(ctl.tagName);
        if (ctl.disabled) { return true; }
    }
    
    return false;
    
}


// ======================================================================
// Determines if any parent element of passed ctl has been disabled
// ======================================================================
function CheckSubmit() {
    //debugger;
    
    //alert(document.activeElement.name);
    return !IsDisabledSelfOrParents(document.activeElement);
    
}


// ======================================================================
// Return a control validation token string to be passed to 
// ValidateControlTokens that checks approp controls before adding
// data to grid.
// arrParams[i]		= control to validate
//			[i + 1] = bln setfocus on fail
// strReplace = Replacement text in "to select xxxx"
// ======================================================================
function GetTokenString_Add(arrParams, strReplace){
	var strEllipsis = "Please click the 'ellipsis' (...) button to select :::::.";
	var i = 0;
	var strCheck = "";
	
	strEllipsis = strEllipsis.replace(":::::", strReplace);
	
	for (i = 0; i < arrParams.length; i+=2) {
		//alert(i + "::" + arrParams[i]);
		strCheck = strCheck + arrParams[i] + "|" + strEllipsis + "|" + arrParams[i + 1] + "|";
	}
	
	return strCheck;
}


// ======================================================================
// Return a control validation token string to be passed to 
// ValidateControlTokens that checks approp controls before adding
// data to grid.
// arrParams[i]		= control to validate
//			[i + 1] = bln setfocus on fail
// strReplace = Replacement text in "to restrict xxxx"
// ======================================================================
function GetTokenString_Popup(strCTLName, strReplace){
	var strRestrict = "Please enter some text to narrow the search for :::::.";

	//alert(strCTLName + "|" + strRestrict.replace(":::::", strReplace) + "|1");
	return strCTLName + "|" + strRestrict.replace(":::::", strReplace) + "|1";
	
}


// ======================================================================
// Set the hidden field on the form to flag that an unload button has 
// been pressed.
//
// NOTE: Relies on existence of hidden field hidnUnloading
// ======================================================================
function SetUnloading(){

	document.getElementById("hidnUnloading").value="TRUE";

}


// ======================================================================
// Set the hidden field on the form to flag that a cancel button has 
// been pressed.
//
// NOTE: Relies on existence of hidden field hidnCancelled
// ======================================================================
function SetCancelled() {

	document.getElementById("hidnCancelled").value="TRUE";

}


// ======================================================================
// Reload the contents frame 
//
// NOTE: Relies on the existence of a frame named contents
// ======================================================================
function ReloadContentsFrame() {
	// alert("reloading");
	window.parent("contents").location.reload();
	// alert("after reloading");
}


// ======================================================================
// Show an alert saying a feature is not implemented.
// ======================================================================
function ShowNotImplemented(strService) {

    alert("The '" + strService + "' service is currently under development.");

}


// ======================================================================
// Show help popup dialog box
//
// NOTE: Relies on existence of HelpPopup.aspx AND IE
// ======================================================================
function ShowHelp() {  
    //var theURL = "HelpPopup.asp?Topic=" + strTopic + "&SubTopic=" + strSubTopic; 
    var theURL = "HelpPopup.aspx"; 
    var winName = "Help"; 
    //var features = 'scrollbars=yes,resizable=yes,width=300,height=200'; 
    var features = "dialogHeight:378px;dialogWidth:590px;scroll:no;resizable:yes"; 

    //ie5 and above - don't want toolbar etc. 
    if (document.getElementById) { features = features + ";status:no;toolbar:no"; } 

    //window.open(theURL,winName,features); 
    window.showModalDialog(theURL, 0, features);                    // ie 4 and above only 

} 


// ======================================================================
// Removes leading and trailing spaces from the passed string. Also removes
// consecutive spaces and replaces it with one space. If something besides
// a string is passed in (null, custom object, etc.) then return the input.
// ======================================================================
function trim(inputString) {
  if (typeof inputString != "string") { return inputString; }
  var retValue = inputString;
  var ch = retValue.substring(0, 1);
  while (ch == " ") { // Check for spaces at the beginning of the string
     retValue = retValue.substring(1, retValue.length);
     ch = retValue.substring(0, 1);
  }
  ch = retValue.substring(retValue.length-1, retValue.length);
  while (ch == " ") { // Check for spaces at the end of the string
     retValue = retValue.substring(0, retValue.length-1);
     ch = retValue.substring(retValue.length-1, retValue.length);
  }
  while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
     retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
  }

  return retValue; // Return the trimmed string back to the user

} // Ends the "trim" function


// ======================================================================
// Shows inputbox and returns the user input.
// Optionally puts it into the passed control
// ======================================================================
function PromptEx(strPrompt, strDefault, strCtlName) {
	//alert("GetUserInput");
	var ctlReturn 

	if (strCtlName) { ctlReturn = CtlFromRefOrId(strCtlName); }
	
	var strReturn = prompt(strPrompt, strDefault);

	// assign return value to approp control
	if (strReturn && ctlReturn) {
		SetControlValue(ctlReturn, strReturn);
	} else {
		if (ctlReturn) { SetControlValue(ctlReturn, strDefault); }
	}
	
	return strReturn;
	
}

// ======================================================================
// Pops up the url in target
// ======================================================================
function PopupNewWindow(url, target) {

	var newWindow = window.open(url, target);
	
}

// ======================================================================
// Set the window focus to the passed control
// ======================================================================
function SetFocus(ctl) {

    ctl = CtlFromRefOrId(ctl);
	if (ctl) { ctl.focus(); }

}


// ======================================================================
// Sets arguments.IsValid true if a selection made in passed source dropdown
// ======================================================================
function ValidateDropdown (source, arguments) {
	//alert(document.getElementById(source.controltovalidate).value);

	arguments.IsValid = (document.getElementById(source.controltovalidate).value != -1);

	//alert(arguments.IsValid);
}


function DateAdd(startDate, numDays, numMonths, numYears)
{
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;
	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);
	
	return returnDate;

}

function YearAdd(startDate, numYears) {
	
	return DateAdd(startDate,0,0,numYears);
	
}

function MonthAdd(startDate, numMonths) {

	return DateAdd(startDate,0,numMonths,0);

}

function DayAdd(startDate, numDays) {

	return DateAdd(startDate,numDays,0,0);

}

// ======================================================================
// Set the visibility of the passed control
// ======================================================================
function SetVisibility(ctl, blnVisible) {
    ctl = CtlFromRefOrId(ctl);

    if (!ctl || !ctl.style) return 0;
    
    ctl.style.visibility = (blnVisible)?"visible":"hidden";
}

// ======================================================================
// Set the value of the passed control
// ======================================================================
function SetControlValue(ctl, objValue) {
    ctl = CtlFromRefOrId(ctl);

    if (!ctl || !objValue) return 0;
    
    // could be a label/span which doesn't set value
    if (ctl.tagName && ctl.tagName=="SPAN") {
		ctl.innerText = objValue;
    } else {
		ctl.value = objValue;
    }    
}        

// ======================================================================
// Get the value of the passed control
// If not found then default to 
//		objDefault if passed
//		Empty string if not
// ======================================================================
function GetControlValue(ctl, objDefault) {
    var ctl = CtlFromRefOrId(ctl);

	if (ctl) {
		// could be a label/span which doesn't set value
		if (ctl.tagName && ctl.tagName=="SPAN") {
			return ctl.innerText;
		} else {
			return ctl.value;
		}    
	} else {
		//control not found - which default?
		return (objDefault)?objDefault:"";
	}
}        

// ======================================================================
// Select all the checkboxes (Hotmail style)
// ======================================================================
function SelectAllCheckboxes(chk) {

    var elm = chk.form.elements;
    for(i=0; i < elm.length; i++) {
        if(elm[i].type=="checkbox" && elm[i].id!=chk.id) {
            elm[i].checked=chk.checked;
        }
    }
}

// ======================================================================
// Global replace function for a string
// strInput is the source string
// Other params are passed in 
// either 
//		as per ParamArray,
//		Replaces ParamArray(x) with ParamArray(x+1)
// or
//		one comma separated string
//		Replaces split(x) with split(x+1)
// ======================================================================
function ReplaceTokens(strInput)	{
	var strReturn = strInput;

//debugger;

	var iStartsAt = 0;
	var arrayToRead;

	if (ReplaceTokens.arguments.length == 2) {
		arrayToRead = ReplaceTokens.arguments[1].split(",");
		iStartsAt = 0;
	} else {
		arrayToRead = ReplaceTokens.arguments;
		iStartsAt = 1;
	}
			
	for (var i = iStartsAt; i != arrayToRead.length; i += 2) {
		var reg = new RegExp(arrayToRead[i], 'gi');				
		strReturn = strReturn.replace(reg, arrayToRead[i + 1]);
	}	

	return strReturn;
}

// ======================================================================
// Returns count of strSubString in strInput
// ======================================================================
function CountSubStr(strInput, strSubString) {
	
	var reg = new RegExp(strSubString, 'gi');
	var splits = strInput.match(reg);
	
	if (splits) {
		return splits.length;
	} else {
		return 0;
	}
}

// ======================================================================
// If passed;
//		string - Returns the control with the name as passed
//		control - Returns that control 
// ======================================================================
function CtlFromRefOrId(CtlRefOrId) {
	if (CtlRefOrId.type || CtlRefOrId.tagName) {
		return CtlRefOrId;
	} else {
		return document.getElementById(CtlRefOrId);
	}
}

// ======================================================================
// Clears and then loads a combo
// Items to load are passed in 
// either 
//		as per ParamArray,
//		Text = ParamArray(x) Value = ParamArray(x+1)
// or
//		one comma separated string
//		Text = split(x) Value = split(x+1)
//
// To select a given item, put "*" as the first char in the value
//
// NOTE: THERE IS A DEPENDENT PROCEDURE IN modBSWSWEBForms
// ======================================================================
function LoadCombo(ctl) {
    ctl = CtlFromRefOrId(ctl);

//debugger;

	var iStartsAt = 0;
	var arrayToRead;

	if (LoadCombo.arguments.length == 2) {
		arrayToRead = LoadCombo.arguments[1].split(",");
		iStartsAt = 0;
	} else {
		arrayToRead = LoadCombo.arguments;
		iStartsAt = 1;
	}
	
	ClearCombo(ctl);
	
	for (var i = iStartsAt; i != arrayToRead.length; i += 2) {
		// add item dynamically to the list box
		var NewItem = document.createElement("OPTION");
		NewItem.text = arrayToRead[i];
		NewItem.value = arrayToRead[i + 1];

		// selected if necessary
		if (NewItem.value.charAt(0) == "*") {
			NewItem.value = NewItem.value.replace("*", "");
			NewItem.selected = true;
		}

		ctl.add(NewItem);
	}
}

// ======================================================================
// Clears a combo
// ======================================================================
function ClearCombo(ctl) {
    ctl = CtlFromRefOrId(ctl);

//debugger;
	if (!ctl.options) return;
	
	for (var i = ctl.options.length - 1; i >= 0; i -= 1) {
		ctl.options[i] = null;
	}
}

//-->
