///
///
var browserName = navigator.appName;
var browserVer = parseInt(navigator.appVersion, 10);
var unloadWontClearOutage = false;
//Detect if MSIE version in case > v4
if (browserName == "Microsoft Internet Explorer" && browserVer >= 4) {
var sAgent = navigator.userAgent;
var sMSIEVer = sAgent.substr(sAgent.indexOf("MSIE ")+("MSIE ").length, 4);
var nMSIEVer = parseInt(sMSIEVer,10);
if (nMSIEVer > browserVer) {
browserVer = nMSIEVer;
}
}
// set up the crow object and children
window.crow = {
page: {},
controls: {},
clientRules: {},
selectors: new StandardChoosers(),
dates: new DateClass()
};
showAlert = function (className, innerHtml) {
var alert = $('#alertMessage');
alert.removeClass('errorAlert successAlert noAlert processingAlert');
alert.addClass(className);
alert.html(innerHtml);
alert.show().focus();
};
hideAlert = function () {
$('#alertMessage').hide();
};
hideProcessing = function () {
$('#processingMessage').hide();
};
showProcessing = function () {
var alert = $('#processingMessage');
alert.show();
};
function ajaxError(xhr, textStatus) {
showAlert('errorAlert', 'ajax failed:' + textStatus);
}
function tabMouseOver(name) {
if (tabAllowClick(name)) {
$('#' + name).addClass('tab-highlighted');
}
}
function tabMouseOut(name) {
if (tabAllowClick(name)) {
window.status = '';
$('#' + name).removeClass('tab-highlighted');
}
}
function tabAllowClick(name) {
var form = document.forms[0];
if (!form[name + 'Visible'])
return true;
var isVisible = form[name + 'Visible'].value;
var isEnabled = form[name + 'Enabled'].value;
var isSelected = form[name + 'TabSelected'].value;
return isVisible.toString() == 'true' &&
isEnabled.toString() == 'true' &&
isSelected.toString() == 'false';
}
// old school code look to remove some time.
var isCompatible = 0;
if ((browserName == "Netscape" && browserVer >= 3) ||
(browserName == "Microsoft Internet Explorer" && browserVer >= 4))
isCompatible = 1;
function submitFormToServer() {
if(window.preprocessSubmit!==undefined)
window.preprocessSubmit();
document.forms[0].submit();
}
function rowHover(query,on) {
if (on)
$(query).addClass('rowHover');
else
$(query).removeClass('rowHover');
}
function padLeft(text, padString, length) {
text = String(text);
while (text.length < length)
text = padString + text;
return text;
}
function filterInt(event) {
var e;
if (window.event) e = window.event;
else if (event) e = event;
else return true;
var keyChar = e.keyCode;
var returnVal = false;
if ((keyChar >= 46 && keyChar <= 57) || (keyChar >= 37 && keyChar <= 40) || (keyChar == 8) || (keyChar == 9) ||
(keyChar >= 96 && keyChar <= 105) || (keyChar == 109) || (keyChar == 189)) {
returnVal = true;
}
e.returnValue = returnVal;
return returnVal;
}
function filterFloat(event, textField) {
var e;
if (window.event) e = window.event;
else if (event) e = event;
else return true;
var keyChar = e.keyCode;
var returnVal;
if ((keyChar >= 46 && keyChar <= 57) || (keyChar == 46) || (keyChar >= 37 && keyChar <= 40) || (keyChar == 8) || (keyChar == 9) || (keyChar == 13) ||
(keyChar >= 96 && keyChar <= 105) || (keyChar == 110) || (keyChar == 109) || (keyChar == 189)) {
returnVal = true;
} else {
if (keyChar == 190) { // period character
returnVal = (textField.value.indexOf('.') < 0);
} else {
returnVal = false;
}
}
e.returnValue = returnVal;
return returnVal;
} // filterFloat
function isNumber(theString) {
if (!theString)
return false;
var retVal = true;
for (var i = 0; i <= theString.length -1; i++) {
if ((theString.charAt(i) < "0") || (theString.charAt(i) > "9")) {
retVal = false;
}
}
return retVal;
} // function isNumber
function PadDigits(n, totalDigits) {
n = n.toString();
var pd = '';
if (totalDigits > n.length)
{
for (var i=0; i < (totalDigits-n.length); i++)
pd += '0';
}
return pd + n.toString();
}
/********************************* Date Class ******/
function DateClass() {
var me = this;
// private
function getDateControls(fieldName) {
var form = document.forms[0];
return {
Year: form[fieldName + '_year'],
Month: form[fieldName + '_month'],
Day: form[fieldName + '_day'],
Time: form[fieldName + '_time']
};
}
function dateControlAllNullValue(form, name) {
var dayField = form[name + "_day"];
var yearField = form[name + "_year"];
var monthField = form[name + "_month"];
if (yearField.value === "" && monthField.value === "" && dayField.value === "") {
clearError(dayField);
clearError(yearField);
clearError(monthField);
return true;
}
return false;
}
function weekDay(weekDayNo) {
if (weekDayNo === 0) {
return "Sunday";
} else if (weekDayNo == 1) {
return "Monday";
} else if (weekDayNo == 2) {
return "Tuesday";
} else if (weekDayNo == 3) {
return "Wednesday";
} else if (weekDayNo == 4) {
return "Thursday";
} else if (weekDayNo == 5) {
return "Friday";
} else {
return "Saturday";
}
} // weekDay
//----- public
this.getMaxDay = function(theMonth, theYear) {
if ((theMonth == 4) || (theMonth == 6) || (theMonth == 9) || (theMonth == 11)) {
return 30;
} else {
if (theMonth == 2) {
if ((theYear % 4 === 0) && (theYear % 100 !== 0)) {
return 29;
} else {
return 28;
}
} else {
return 31;
}
}
}; // function getMaxDay
this.validYear = function (event, showErr, fromOtherValidate, errorAlert) {
var changedField = (event.target ? event.target : (event.srcElement ? event.srcElement : event));
if (errorAlert === undefined)
errorAlert = createAlert(changedField, showErr);
var form = document.forms[0];
var controlName = changedField.name.replace("_year", "");
var theWeekDay = form[controlName + "_weekday"];
if (changedField.value === "") { // If changed field is not null
if (dateControlAllNullValue(form, controlName))
return true;
errorAlert("Year field must not be blank.");
if (event.stopPropagation) event.stopPropagation();
else if (event.cancelBubble != undefined) event.cancelBubble = true;
return false;
}
if (!isNumber(changedField.value)) {
errorAlert("Year field must be a valid number.");
if (event.stopPropagation) event.stopPropagation();
else if (event.cancelBubble != undefined) event.cancelBubble = true;
return false;
}
// Format modified date with field with leading zeros
var newValue = parseInt(changedField.value, 10);
if ((newValue >= 60) && (newValue < 100))
newValue = newValue + 1900;
if (newValue < 60)
newValue = newValue + 2000;
newValue = "00" + newValue;
changedField.value = newValue.substring(newValue.length - 4, newValue.length);
if ((changedField.value < 1960) || (changedField.value > 2100)) {
errorAlert("Year field must be between 1960 and 2100.");
if (event.stopPropagation) event.stopPropagation();
else if (event.cancelBubble != undefined) event.cancelBubble = true;
return false;
}
if (!fromOtherValidate && showErr) {
var result = me.validMonth(form[controlName + "_month"], false, true);
result = me.validDay(form[controlName + "_day"], false, true) && result;
if (!result) {
clearError(changedField);
return false;
}
}
if (theWeekDay !== undefined) {
me.setWeekday(theWeekDay);
}
clearError(changedField);
return true;
}; // function validYear
this.validMonth = function(changedField, showErr, fromOtherValidate, errorAlert) {
if (errorAlert === undefined)
errorAlert = createAlert(changedField, showErr);
var form = document.forms[0];
var controlName = changedField.name.replace("_month", "");
var theWeekDay = form[controlName + "_weekday"];
if (changedField.value === "") { // If changed field is not null
if (dateControlAllNullValue(form, controlName))
return true;
errorAlert("Month field must not be blank.");
return false;
}
// Format modified date with field with leading zeros
if (!isNumber(changedField.value)) {
errorAlert("Month field must be a valid number.");
return false;
}
var newValue = parseInt(changedField.value, 10);
newValue = "00" + newValue;
changedField.value = newValue.substring(newValue.length - 2, newValue.length);
if (changedField.value < 1 || changedField.value > 12) {
errorAlert("Month field must be between 1 and 12.");
return false;
}
if (!fromOtherValidate && showErr) {
var result = me.validYear(form[controlName + "_year"], false, true);
result = me.validDay(form[controlName + "_day"], false, true) && result;
if (!result) {
clearError(changedField);
return false;
}
}
if (theWeekDay !== undefined) {
me.setWeekday(theWeekDay);
}
clearError(changedField);
return true;
}; // function validMonth
this.validDay = function(changedField, showErr, fromOtherValidate, errorAlert) {
if (errorAlert === undefined)
errorAlert = createAlert(changedField, showErr);
var form = document.forms[0];
var controlName = changedField.name.replace("_day", "");
var theWeekDay = form[controlName + "_weekday"];
var yearField = form[controlName + "_year"];
var monthField = form[controlName + "_month"];
// Changed field is null
if (changedField.value === "") { // If changed field is not null
if (dateControlAllNullValue(form, controlName))
return true;
errorAlert("Day field must not be blank.");
return false;
}
// Format modified date with field with leading zeros
if (!isNumber(changedField.value)) {
errorAlert("Day field must be a valid number.");
return false;
}
var newValue = parseInt(changedField.value, 10);
newValue = "00" + newValue;
changedField.value = newValue.substring(newValue.length - 2, newValue.length);
var monthDays = 31;
if ((monthField.value >= 1 && monthField.value <= 12) &&
(yearField.value >= 1980 && yearField.value <= 2100))
monthDays = me.getMaxDay(monthField.value, yearField.value);
if (changedField.value < 1 || changedField.value > monthDays) {
errorAlert("Day field must be between 1 and " + monthDays + ".");
return false;
}
if (!fromOtherValidate && showErr) {
var result = me.validYear(yearField, false, true);
result = me.validMonth(monthField, false, true) && result;
if (!result) {
clearError(changedField);
return false;
}
}
if (theWeekDay !== undefined) {
me.setWeekday(theWeekDay);
}
clearError(changedField);
return true;
}; // function validDay
this.validDateControl = function(form, name, description, writeMessage) {
var errorAlert = function(message) {
writeMessage(description + ": " + message);
};
var result = me.validYear(form[name + "_year"], false, true, errorAlert);
result = me.validMonth(form[name + "_month"], false, true, errorAlert) && result;
result = me.validDay(form[name + "_day"], false, true, errorAlert) && result;
return result;
};
this.timeError = function (event, showErr) {
var timeField = (event.target ? event.target : (event.srcElement ? event.srcElement : event));
if (event.stopPropagation) event.stopPropagation();
else if (event.cancelBubble != undefined) event.cancelBubble = true;
else timeField = event;
if (showErr) {
jqAlert("You have entered an invalid time.");
if (event.stopPropagation)
setTimeout('var e= document.forms[0]["' + timeField.name + '"];e.focus();e.select();', 10);
else {
timeField.focus();
timeField.select();
}
}
return false;
};
this.validTime = function (event, showSeconds, showMilliseconds, showErr) {
var timeField = (event.target ? event.target : (event.srcElement ? event.srcElement : event));
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)?:?([0-5]\d)?\.?(\d{1-3})?\s*([aApP])?[mM]?\s*$/;
var m = re.exec(timeField.value === "" ? "00:00" : timeField.value);
if (m) {
var result = (m[1].length == 2 ? "" : "0") + m[1];
var len = m.length;
if (len > 0 && m[len - 1] && m[len - 1].match(/[aApP]/)) {
len--;
var h = parseInt(m[1], 10);
if (h > 12) return this.timeError(event, showErr);
if (m[len].match(/[pP]/)) h += 12;
if (h == 24)h = 0;
if (h >= 24) return this.timeError(event, showErr);
result = "" + (h > 9 ? h : "0" + h);
}
result = result + ":" + (len > 1 && m[2] ? m[2] : "00");
if (showSeconds)
result += ":" + (len > 2 && m[3] ? m[3] : "00");
if (showSeconds)
result += "." + (len > 3 && m[4] ? m[4] : "000");
timeField.value = result;
return true;
}
return this.timeError(event, showErr);
}; // function validTime
this.openCalendar = function(fieldName, rootPath, returnMethod) {
var controls = getDateControls(fieldName);
var url = rootPath + "Resources/calendar.aspx?fieldname=" + fieldName +
"&calDate=" + controls.Year.value + "/" + controls.Month.value + "/" + controls.Day.value +
"&rtnMethod=" + returnMethod;
// This is for the Calendar pop-up window
// Will open to an new window to show the Calendar
if (typeof jQuery != 'undefined') {
url += '&jquery=1';
var ds = "
";
$(ds).dialog({
dialogClass: 'modalDialogNoTitlebar', bgiframe: true, modal: true, resizable: false,
close: function() { $('#calendarFrame').attr('src', "about:blank"); $(this).remove(); },
open: function () { $('#calendarFrame').attr('src', url); },
width: 470, height: $.browser.msie && parseFloat($.browser.version) < 10 ? 480 : 260,
buttons: { "Cancel": function() { $(this).dialog('close'); } }
});
return;
}
openDialog(url, "_blank", 470, 325);
}; // openCalendar
this.doClearButton = function(fieldName) {
var controls = getDateControls(fieldName);
// Clear the input date/time fields
controls.Year.value = "";
controls.Month.value = "";
controls.Day.value = "";
controls.Time.value = "";
clearError(controls.Year);
clearError(controls.Month);
clearError(controls.Day);
clearError(controls.Time);
}; // function doClearButton
this.doNowButtonOffset = function(fieldName, showSeconds, showMilliseconds, iTimeDiffMinutes) {
var controls = getDateControls(fieldName);
// Set the input date/time fields to current date/time
var todayDate = new Date();
// Adjust for the time difference in minutes
var iDateValue = Date.parse(todayDate) + (iTimeDiffMinutes * 60 * 1000);
todayDate.setTime(iDateValue);
var thisYear = todayDate.getFullYear();
var thisMonth = ("0" + (todayDate.getMonth() + 1));
var thisDay = ("0" + todayDate.getDate());
controls.Year.value = thisYear;
controls.Month.value = thisMonth.substring(thisMonth.length - 2, thisMonth.length);
controls.Day.value = thisDay.substring(thisDay.length - 2, thisDay.length);
var thisHour = ("0" + todayDate.getHours());
var thisMinute = ("0" + todayDate.getMinutes());
var thisSecond = ("0" + todayDate.getSeconds());
controls.Time.value =
thisHour.substring(thisHour.length - 2, thisHour.length) + ":" +
thisMinute.substring(thisMinute.length - 2, thisMinute.length);
if (showSeconds === true) {
controls.Time.value += ":" + thisSecond.substring(thisSecond.length - 2, thisSecond.length);
}
if (showMilliseconds === true) {
controls.Time.value += ".000";
}
clearError(controls.Year);
clearError(controls.Month);
clearError(controls.Day);
clearError(controls.Time);
};
this.doNowButton = function(fieldName, showSeconds, showMilliseconds) {
var controls = getDateControls(fieldName);
// Set the input date/time fields to current date/time
var todayDate = new Date();
var thisYear;
var thisYearInt = parseInt(todayDate.getYear(), 10);
if (thisYearInt <= 100) {
if (thisYearInt > 50) {
thisYear = thisYearInt + 1900;
} else {
thisYear = thisYearInt + 2000;
}
} else {
thisYear = thisYearInt;
}
var thisMonth = ("0" + (todayDate.getMonth() + 1));
var thisDay = ("0" + todayDate.getDate());
controls.Year.value = thisYear;
controls.Month.value = thisMonth.substring(thisMonth.length - 2, thisMonth.length);
controls.Day.value = thisDay.substring(thisDay.length - 2, thisDay.length);
var thisHour = ("0" + todayDate.getHours());
var thisMinute = ("0" + todayDate.getMinutes());
var thisSecond = ("0" + todayDate.getSeconds());
controls.Time.value =
thisHour.substring(thisHour.length - 2, thisHour.length) + ":" +
thisMinute.substring(thisMinute.length - 2, thisMinute.length);
if (showSeconds === true) {
controls.Time.value += ":" + thisSecond.substring(thisSecond.length - 2, thisSecond.length);
}
if (showMilliseconds === true) {
controls.Time.value += ".000";
}
clearError(controls.Year);
clearError(controls.Month);
clearError(controls.Day);
clearError(controls.Time);
}; // function doNowButton
this.doWeekdayClick = function(theWeekday) {
// Set the input date/time fields to the value specified in the
// input Weekday select box.
// Get the year, month and day field names
var controls = getDateControls(theWeekday.name.replace("_weekday", ""));
var dateValue = new Date(theWeekday.options[theWeekday.selectedIndex].value);
// PH: getYear() has been deprecated. Use getFullYear
//var yearValue = ("0000" + dateValue.getYear());
var monthValue = ("00" + (dateValue.getMonth() + 1));
var dayValue = ("00" + dateValue.getDate());
if (dateValue > new Date("1900/01/01")) {
controls.Year.value = dateValue.getFullYear();
controls.Month.value = monthValue.substring(monthValue.length - 2, monthValue.length);
controls.Day.value = dayValue.substring(dayValue.length - 2, dayValue.length);
} else {
controls.Year.value = "";
controls.Month.value = "";
controls.Day.value = "";
}
}; // doWeekdayClick
this.filterTime = function (event) {
var k = event.keyCode;
if ((k >= 48 && k <= 57) || (k >= 37 && k <= 40) || (k == 8) || (k == 9) || (k == 13) || (k == 16) || (k == 46) || (k == 59) || (k == 32) || (k == 190) || (k == 110) || (k == 65) || (k == 77) || (k == 80) ||
(k >= 96 && k <= 105) || (k == 109) || (k == 186) || (k == 189)) {
event.returnValue = true;
return true;
} else {
event.returnValue = false;
return false;
}
}; // filterTime
this.setWeekday = function(theWeekday) {
var optionDate;
// Get the year, month and day field names
var yearName = theWeekday.name.replace("_weekday", "_year");
var monthName = theWeekday.name.replace("_weekday", "_month");
var dayName = theWeekday.name.replace("_weekday", "_day");
var form = document.forms[0];
var theYear = form[yearName];
var theMonth = form[monthName];
var theDay = form[dayName];
var dateValue = new Date(theYear.value + "/" +
theMonth.value + "/" +
theDay.value);
// Reset the option list
for (var i = theWeekday.options.length - 13; i <= theWeekday.options.length - 1; i++) {
optionDate = crow.dates.DateAdd("d", i - 7, dateValue);
theWeekday.options[i].value = optionDate;
theWeekday.options[i].text = weekDay(optionDate.getDay());
}
// Locate the entry in the combo box that matches the date value
for (i = 0; i < theWeekday.options.length; i++) {
optionDate = new Date(theWeekday.options[i].value);
if (optionDate.valueOf() == dateValue.valueOf()) {
theWeekday.selectedIndex = i;
}
}
}; // function setWeekday
//Creates a monthDetail object used in populating the monthData Array
function monthDetail(iJavaNum, iCalNum, sName, iNumDays) {
this.javaNum = iJavaNum;
this.calendarNum = iCalNum;
this.name = sName;
this.numDays = iNumDays;
}
//Create a global monthData array for use in date functions:
//items are Java Month Number, Calendar Number, Month Name, Number of Days in the month - eg (1,2,"February",28)
var monthData = [
new monthDetail(0, 1, "January", 31),
new monthDetail(1, 2, "February", 28),
new monthDetail(2, 3, "March", 31),
new monthDetail(3, 4, "April", 30),
new monthDetail(4, 5, "May", 31),
new monthDetail(5, 6, "June", 30),
new monthDetail(6, 7, "July", 31),
new monthDetail(7, 8, "August", 31),
new monthDetail(8, 9, "September", 30),
new monthDetail(9, 10, "October", 31),
new monthDetail(10, 11, "November", 30),
new monthDetail(11, 12, "December", 31)];
//DateAdd
this.DateAdd = function(sInterval, iNumber, dDate) {
var dateInMilliSeconds;
var oneMinute;
var oneHour;
var oneDay;
var dReturnDate;
//Set up time values for date math calculations
oneMinute = 60 * 1000;
oneHour = oneMinute * 60;
oneDay = oneHour * 24;
dReturnDate = new Date(dDate);
dateInMilliSeconds = dReturnDate.getTime();
switch (sInterval) {
case "m":
dateInMilliSeconds += oneMinute * iNumber;
break;
case "h":
dateInMilliSeconds += oneHour * iNumber;
break;
case "d":
dateInMilliSeconds += oneDay * iNumber;
break;
default:
dateInMilliSeconds += oneDay * iNumber;
break;
}
dReturnDate.setTime(dateInMilliSeconds);
return dReturnDate;
};
this.DateDiff = function(sInterval, dDate1, dDate2) {
var iDateDiff;
var iDate1InMS;
var iDate2InMS;
var iMonth1;
var iYear1;
var iMonth2;
var iYear2;
var iSecond;
var iMinute;
var iHour;
var iDay;
var iWeek;
var iYear;
var iDenominator;
var iDateDiffInMS;
iSecond = 1000;
iMinute = iSecond * 60;
iHour = iMinute * 60;
iDay = iHour * 24;
iWeek = iDay * 7;
iYear = iDay * 365;
iDate1InMS = dDate1.valueOf();
iDate2InMS = dDate2.valueOf();
iDateDiffInMS = iDate2InMS - iDate1InMS;
if ((sInterval != "ss") && (sInterval != "mi") && (sInterval != "hh") && (sInterval != "dd") &&
(sInterval != "ww") && (sInterval != "mm") && (sInterval != "yy")) {
jqAlert("Interval supplied in DateDiff function is not valid.");
iDateDiff = 0;
} else {
if (sInterval != "mm") {
if (sInterval == "ss") {
iDenominator = iSecond;
} else if (sInterval == "mi") {
iDenominator = iMinute;
} else if (sInterval == "hh") {
iDenominator = iHour;
} else if (sInterval == "dd") {
iDenominator = iDay;
} else if (sInterval == "ww") {
iDenominator = iWeek;
} else if (sInterval == "yy") {
iDenominator = iYear;
}
iDateDiff = iDateDiffInMS / iDenominator;
} else { //Special case for month
iMonth1 = dDate1.getUTCMonth();
iYear1 = dDate1.getUTCFullYear();
iMonth2 = dDate2.getUTCMonth();
iYear2 = dDate2.getUTCFullYear();
if (iYear1 <= iYear2) {
iDateDiff = (12 * (iYear2 - iYear1)) + (iMonth2 - iMonth1);
} else {
if (iMonth1 <= iMonth2) {
iDateDiff = (12 * (iYear2 - iYear1)) + (iMonth2 - iMonth1);
} else {
iDateDiff = (12 * (iYear2 - iYear1)) + (iMonth1 - iMonth2);
}
}
}
}
return parseInt(iDateDiff, 10);
}; //DateDiff
//Gets the name of the month for an input javaMonth number or calendar Month number
this.getMonthName = function(iMonthNumber, bJavaMonth) {
var i;
var monthName = new String();
for (i = 0; i <= 11; i++) {
if (bJavaMonth) {
if (monthData[i].javaNum == iMonthNumber) {
monthName.value = monthData[i].name;
}
} else {
if (monthData[i].calendarNum == iMonthNumber) {
monthName.value = monthData[i].name;
}
}
} //for iCount
return monthName.value;
}; //getMonthName
}
function findScreenOpenLeft(width) {
var left = (screen.width / 2) - (width / 2);
if (screen.left) {
// the firefox way to support multi monitors
return left + screen.left;
} else if (screen.availLeft) {
// WebKit does the pos already offset by screen so nothing needed.
return left;
} else if (window.screenLeft >= screen.width) {
// if IE and we are on another monitor we need to wing it
// work out the where we are to the midpoint of the existing window
return window.screenLeft + (document.body.offsetWidth / 2 - width / 2);
}
return left;
}
function openDialog(url, windowName, width, height) {
var left = findScreenOpenLeft(width);
var top = (screen.height/2)-(height/2);
if (browserName == "Netscape") height = height + 25;
var windowFeatures = 'width=' + width + ',top='+top+',left='+left +
',height=' + height +
',resizable=yes,' +
'toolbar=no,' +
'scrollbars=yes,' +
'menubar=no,' +
'dependent=yes' +
'status=no,' +
'modal=yes';
var windowhand = window.open(url, windowName, windowFeatures);
if (windowhand)
windowhand.focus();
} // openDialog
function openScreenHeightPopUp(sUrl, iWidth) {
var scrnHeight;
var scrnWidth;
var winWidth = iWidth;
var sOptions;
var iLeft;
scrnHeight = parent.window.screen.height - 60;
scrnWidth = parent.window.screen.width;
/*
if(browserName == "Netscape" && browserVer >= 4){
scrnHeight -= 30; // Netscape difference
winWidth = iWidth - 16;
}
*/
iLeft = ((scrnWidth - winWidth) / 2);
sOptions = "width=" + winWidth + ",height=" + scrnHeight +
",left=" + iLeft + ",top=0,toolbar=no,scrollbars=yes,resizable=yes";
window.open(sUrl, "", sOptions);
}
function swapImage(theImage, newSource) {
if (typeof theImage === "string")
theImage = document.getElementById(theImage);
theImage.src = newSource;
}
function tabHighlight(tabName, doHighlight) {
// Default to un-highlight
var highlightColor = '#9C9A9C';
if (doHighlight) {
highlightColor = '#9999CC';
}
var btnObj = document.getElementById(tabName);
btnObj.style.cursor= 'default';
btnObj = document.getElementById(tabName + '_content');
btnObj.style.backgroundColor=highlightColor;
if (doHighlight) {
btnObj.style.textDecoration = 'underline';
} else {
btnObj.style.textDecoration = 'none';
}
btnObj = document.getElementById(tabName + '_leftborder_1');
btnObj.style.backgroundColor=highlightColor;
btnObj = document.getElementById(tabName + '_leftborder_2');
btnObj.style.backgroundColor=highlightColor;
btnObj = document.getElementById(tabName + '_rightborder');
btnObj.style.backgroundColor=highlightColor;
} // tabHighlight
function validNumber(changedField) {
if (changedField.value !== "") {
if (isNumber(changedField.value) === false) {
jqAlert("You have entered an invalid number.");
changedField.focus();
changedField.select();
return false;
}
}
return true;
} // function validNumber
function piAlertValidation(sPersonnelIncidentCauseCode) {
return function(oldValue, newValue) {
var messageString;
if ((oldValue == sPersonnelIncidentCauseCode) && (newValue != sPersonnelIncidentCauseCode)) {
messageString = "This event has an associated Personnel Incident record.\n\n" +
"If you continue, any new information in this record will be not be saved.\n" +
"To save any new information, select \"Cancel\" and save the event before\n" +
"changing the cause code/prime cause.\n\n" +
"Are you sure you want to change the cause code/prime cause for this event?";
return confirm(messageString);
}
return true;
};
}
function validCode(theCodeField, theDescDropDown,submitMethod, validationMethod ) {
// Validate the input code by matching a value in the accompanying
// drop-down list.
var isValid = false;
var codeValue = theCodeField.value;
var oldValue = theDescDropDown.options[theDescDropDown.selectedIndex].value;
var strLength;
var doSubmit;
codeValue = codeValue.toUpperCase();
strLength = codeValue.length;
doSubmit = true;
if (validationMethod)
doSubmit = validationMethod(oldValue,codeValue);
if (doSubmit) {
for (var i = 0; i < theDescDropDown.length; i++) {
if (theDescDropDown.options[i].value.substring(0, strLength) == codeValue) {
theDescDropDown.options[i].selected = true;
codeValue = theDescDropDown.options[i].value;
isValid = true;
i = theDescDropDown.length; // exit loop
}
}
if (isValid === true) {
theCodeField.value = codeValue;
doSubmitRefresh();
} else {
// Revert to the selected value
theCodeField.value = oldValue;
theCodeField.focus();
jqAlert('Invalid code entered.');
}
} else {
// Revert to the selected value
theCodeField.value = oldValue;
if(submitMethod)
submitMethod();
}
return isValid;
} // function validCode
function setCode(theCodeField, theDescDropDown, submitMethod, validationMethod) {
// Set the input code field to the value selected in the dropdown.
var oldValue = theCodeField.value;
var codeValue = theDescDropDown.options[theDescDropDown.selectedIndex].value;
var doSubmit;
var strLength;
doSubmit = true;
strLength = codeValue.length;
if (validationMethod)
doSubmit = validationMethod(oldValue, codeValue);
if (doSubmit) {
theCodeField.value = codeValue;
if (submitMethod)
submitMethod();
} else {
// Revert to the selected value
for (var i = 0; i < theDescDropDown.length; i++) {
if (theDescDropDown.options[i].value.substring(0, strLength) == oldValue) {
theDescDropDown.options[i].selected = true;
i = theDescDropDown.length; // exit loop
}
}
}
return true;
} // setCode
function getOutageRequestWidowName(outageNumber, changeReqNumber) {
var name = 'sat' + outageNumber.replace('-', 'o');
if (changeReqNumber)
name += "c" + changeReqNumber;
return name;
}
//Trims the outside spaces off a string and returns the trimmed string
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
function trimString(data){return data.trim();}
function createAlert(control, showErr) {
if (showErr) {
return function(message) {
alert(message);
control.focus();
control.select();
$("#" + control.name).addClass("hasError");
};
} else {
return function(message) {
$("#" + control.name).addClass("hasError");
};
}
}
function clearError(control) {
$("#"+control.name).removeClass("hasError");
}
function dateControlDate(form, name) {
var d = form[name + "_day"].value;
var y = form[name + "_year"].value;
var m = form[name + "_month"].value;
if (d && m && y)
return new Date(y, m, d);
return null;
}
function windowFocus(){
if (browserVer >= 4) {
window.focus();
}
} //windowfocus
function getFrameWindow(frameid) {
var f = document.getElementById(frameid);
return f.contentWindow;
}
//Encloses a tring so that it can be used safely in a URL
function URLencode(sStr) {
return escape(sStr).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
} //URLencode
function reSizeMe() {
try {
var h= Math.min( document.body.scrollHeight, screen.height - 90);
var w = Math.min( document.body.scrollWidth, screen.width - 30);
self.resizeTo(w + 30, h + 90 );
}catch (e) {}
}
function submitHref(dest) {
document.forms[0].submissionParameters.value = dest;
submitFormToServer();
}
function toggle(control) {
control.checked = !control.checked;
}
function cntCheckBoxes()
{
var cntr=0;
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
if ('checkbox' == inputs[i].type.toLowerCase())
cntr++;
}
return cntr;
}
function submitenter(myfield, e, f) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
if (f === undefined) {
myfield.form.submit();
} else {
var index = f.indexOf('*');
while (index != -1) {
f = f.replace('*', '\'');
index = f.indexOf('*');
}
eval(f);
}
return false;
}
else
return true;
}
function getQueryVariable(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
function Navigation(url, wontLoseData) {
if (wontLoseData)
crow.page.unloadWontClearOutage = true;
if (!($.browser.msie))
window.location.href = url; // sends referrer in FF, not in IE
else { // IE
try {
// all this hacky goodness is to send a referrer in IE
var fakeLink = document.createElement("a");
fakeLink.href = url;
document.body.appendChild(fakeLink);
fakeLink.click(); // click() method defined in IE only
} catch (ex) {
// Get rid of the unspecifed error on user cancel
// don't want to mask a genuine error but
// lets just restrict this to our 'Unspecified' one
if (ex.message.indexOf('Unspecified') == -1) {
throw ex;
}
}
}
return false;
}
function getEventFirstPage(eventTypeId) {
var url = '../events/';
switch (eventTypeId.charAt(0)) {
case 'L':
url += 'event_entry_log';
break;
case 'M':
url += 'event_entry_emss_power';
break;
case 'S':
url += 'event_entry_system_cond';
break;
case 'O':
url += 'event_entry_init';
break;
default:
url += 'event_entry_init';
break;
}
return url + '.aspx';
}
function updateSprite(name, left, top)
{
$("#" + name).css("background-position", left + "px " + top + "px");
}
function newEvent(eventTypeId) {
var pageName = /([^\/]+[\/][^\/]+)\.aspx/.exec(document.location.pathname)[1];
document.location = getEventFirstPage(eventTypeId) + '?create_event_type=' + eventTypeId.slice(1) + '&frompage=../' + pageName;
}
function getInlineDialogWindow(id) {
if (!id)
id = 'inlineDialogFrame';
return getFrameWindow(id);
}
function findInlineDialog(item, id) {
if (!id)
id = 'inlineDialogFrame';
return $('#' + id).contents().find(item);
}
function openInlineDialog(url, options) {
var id = 'inlineDialogFrame';
if (options.id)
id = options.id;
var ds = "";
options.dialogClass= 'modalDialog';
options.bgiframe= true;
options.modal= true;
options.resizable = false;
var dia = $(ds);
options.close = function () { if (options.onClose) options.onClose(dia); $('#' + id).attr('src', "about:blank"); $(this).remove(); };
options.open = function () { $('#' + id).attr('src', url); };
options.open = function () {
if (options.dialogLoaded) {
$('#' + id).load(function () {
options.dialogLoaded(dia);
});
}
$('#' + id).attr('src', url);
};
dia.dialog(options);
return dia;
}
function newLog(title) {
var options = { title: title, width: 470, height: 560,
buttons: {
"Create": function () {
newEvent(getInlineDialogWindow().getEventTypeId());
$(this).dialog('close');
},
"Cancel": function () { $(this).dialog('close'); }
}
};
openInlineDialog('../events/new_event_type.aspx',options);
return false;
}
function doOptions() {
$('#browser-options-body').slideToggle(400, function () {
SelectionPost('browser-settings', null, { 'browser_options_hidden': $('#browser-options-body').is(':hidden') });
if (window.resizeWindow) {
window.resizeWindow();
$('#browser-options:first .ui-dropdownchecklist-text:visible').autoEllipsis();
} else $(window).trigger('resize');
});
}
function ajaxFailed(xmlRequest) {
if (xmlRequest.status == 401)
window.location = "../login.aspx?error=-108";
else
jqAlert(xmlRequest.status + ' \r\n ' +
xmlRequest.statusText + '\r\n' +
xmlRequest.responseText);
}
function SelectionSearch(name, callback, parameters) {
$.ajax({
type: "Get",
url: "../Selection/SelectionService.ashx/" + name,
cache: false,
contentType: "application/json; charset=utf-8",
data: parameters,
dataType: "json",
success: callback,
error: ajaxFailed
});
}
function SelectionPost(name, callback, parameters) {
$.ajax({
type: "POST",
url: "../Selection/SelectionService.ashx/" + name,
cache: false,
//contentType: "application/json; charset=utf-8",
data: parameters,
dataType: "json",
success: callback,
error: ajaxFailed
});
}
function SelectionPopulateCombo(serviceName, cboName, parameters) {
var cbo = $('#' + cboName);
cbo.find("option:gt(0)").remove();
cbo.find("option:first").text("Loading...");
SelectionPost(serviceName,
function(results) {
var a = results.result;
cbo.find("option").remove();
for (var i = 0; i < a.length; i++) {
$("").attr("value", a[i].id).text(a[i].name).appendTo(cbo);
}
},
parameters);
}
//showSelectPerson----------------------------------------------------------
function seachOperationSelect(name) {
return '';
}
function checkOthers(otherName, thisName) {
var otherCheckBoxes = document.getElementsByName(otherName);
var thisCheckBox = document.getElementsByName(thisName);
// FB 7412. Unchecking all was not unchecking all check boxes
// attr("checked") does not return a boolean, .prop returns a bool
//var state = $(thisCheckBox).attr("checked");
var state = $(thisCheckBox).prop('checked');
if (otherCheckBoxes != null) {
var isChecked = false;
if (state === "checked" || state === true)
isChecked = true;
$(otherCheckBoxes).attr("checked", isChecked);
}
}
function generateResultsTable(parameters, results) {
var ci;
var inputType = parameters.multipleSelection ? 'checkbox' : 'radio';
var table;
if (parameters.multipleSelection) {
table = '
';
}
else {
table = '
';
}
// generate the headers.
for (ci = 0; ci < parameters.columns.length; ci++) {
if (parameters.columns[ci].width)
table += '
';
else
table += '
';
table += parameters.columns[ci].title + '
';
}
table += '
';
var rowcount = results.length;
for (var i = 0; i < rowcount; i++) {
var item = results[i];
table += '
' : '"/>');
for (ci = 0; ci < parameters.columns.length; ci++) {
var col = parameters.columns[ci];
table += (col.isLabel ? '
');
}
}
table += '
';
return table;
}
/**
This creates a ajax search handler the pop ups a dialog if more than one match is found.
parameters.selectCallback: a function of type function(id,name) that gets called if a selection has been made
parameters.nonSelectCallback: a function of type function(noMatchs) that gets called if a selection has cancelled or not available
parameters.title: the title of the dialog
parameters.titleOutput: function(result) a function that can generate the title from the result object.
parameters.heading: function(result) a function that can generate the heading from the result object.
parameters.multipleSelection: allow mutliple selection
parameters.noMatchAlert: the string to use when no matches
parameters.tooManyResultsAlert function(result) a function that can generate the too many results warning.
parameters.onHasResults: function to call if we have results. Return true to hide dialog
parameters.filterDiv: function(dialog,divForFilter,updateTable)
parameters.getName: function(result) that returns the name of the result
parameters.columns: the columns in the result grid
title: the header title of the column
isLabel: if the item is the label for the radio button
fieldName: the field in the result item to display
output: function(item) the returns the text for custom output.
*/
function createResultCallback(parameters) {
return function (results) {
// Gets the name of the result for display when we need to return the name of the selected result.
var getName = parameters.getName ? parameters.getName : function (r) { return r.label; };
var result = results.result;
var rowcount = result.length;
// If there only one item then we don't need to get the user to select it
// just notify the callback that we have a result.
var hideDialog = rowcount === 1;
// fire the callback let the work know we have results.
if (parameters.onHasResults) {
var res = parameters.onHasResults(results);
if (typeof res === "boolean") hideDialog = res;
}
if (hideDialog) {
// send the result back.
if (parameters.multipleSelection)
parameters.selectCallback([result[0].id], [getName(result[0])], [parameters.fld]);
else
parameters.selectCallback(result[0].id, getName(result[0]), [parameters.fld]);
} else if (rowcount >= 1) { // We have muiltple results
// We need to show a dialog set get that setup.
var h = window.innerHeight - 130;
var htm = "
";
if (parameters.heading) {
htm += "
" + parameters.heading(results) + "
";
}
// If the dialog has a filter section add that to the dialog
if (parameters.filterDiv)
htm += "";
htm += "
";
var dlg = $(htm).html(htm);
var currentResults; // this stores the current result if they change.
// This function will update the table results, this could be called a couple of times
// if the filters change.
var updateTable = function (r) {
// generate the result table.
var table = generateResultsTable(parameters, r.result);
currentResults = r.result;
// If there is too many result we will only show a subset of them so warn the user.
if (r.tooManyResults) {
var errorMessage = '
';
if (parameters.tooManyResultsAlert) {
errorMessage += parameters.tooManyResultsAlert(r);
}
else {
errorMessage += 'This query returned more records than the allowed maximum.\nOnly the first ' + r.maxRows + " are displayed.";
}
table = errorMessage + "
" + table;
}
// update the UI
$("#resultsDiv", dlg).html(table);
};
// Create the filter div if neeed.
if (parameters.filterDiv)
parameters.filterDiv(dlg, $("#filterDiv", dlg), updateTable);
// do the orginal update of the table
updateTable(results);
// get the title of the dialog
var title;
if (parameters.titleOutput !== undefined) {
title = parameters.titleOutput(results);
} else {
title = parameters.title;
}
// create the result search method for finding a result based on its id.
var findInResult = function (id) {
for (var i = 0; i < currentResults.length; i++) {
if (currentResults[i].id === id)
return currentResults[i];
}
return null;
};
var valueHasBeenSelected = false;
var y = (window.innerHeight / 2) - ((h+130) / 2);
var x = (window.innerWidth / 2) - 240;
// shod the dialog in all its glory
$(dlg).dialog({
modal: true, width: 480, resizable: false, title: title, position: [ x, y],
close: function () {
$(this).remove();
if (!valueHasBeenSelected && parameters.nonSelectCallback)
parameters.nonSelectCallback(false);
},
buttons: {
"Select": function () {
var id;
var cb = $("#selection-grid input[name=\"id\"]:checked");
if (!parameters.multipleSelection) {
var textId = cb.val();
if (textId === undefined) {
jqAlert("You need to select an item.");
return false;
}
id = parseInt(cb.val(), 10);
var label = getName(findInResult(id));
if (!isNaN(id)) parameters.selectCallback(id, label, parameters.fld);
}
else {
var ids = [];
var names = [];
// mutilple selection will be in arrays
cb.each(function () {
id = parseInt(this.value, 10);
ids.push(id);
names.push(getName(findInResult(id)));
});
if (ids.length === 0) {
jqAlert("You need to select at least one item.");
return false;
}
var maxRecs = typeof maxSelectionRecords === 'number' ? maxSelectionRecords : 500;
if (maxRecs > 0 && ids.length > maxRecs ) {
jqAlert("There are too many values selected. Please reduce the number of items to " + maxRecs + " or less.");
return false;
}
parameters.selectCallback(ids, names, parameters.fld);
}
valueHasBeenSelected = true;
$(this).dialog('close');
return false;
},
"Cancel": function () {
$(this).dialog('close');
if (parameters.cancelCallback)
parameters.cancelCallback(parameters.fld);
return false;
}
}
});
if ($("#userDiv").height() > h) $("#userDiv").height(h); //i.e. not respecting maxheight
} else {
// if we have no results do an alert to has we don't have results.
if (!parameters.noMatchAlert) {
if (parameters.noMatchAlert !== false)
jqAlert('No matches were found');
} else {
jqAlert(parameters.noMatchAlert);
}
if (parameters.nonSelectCallback)
parameters.nonSelectCallback(true);
}
};
}
function showSelectPerson(fieldNameOrCallback, authRequired) {
var resultForm = {
title: "Select a person and click 'OK' below...",
columns: [{ title: 'Person', fieldName: 'label', isLabel: true },
{title:'Employer', fieldName:'employer'}]
};
// The call back to main application
if (typeof (fieldNameOrCallback) == 'string') {
resultForm.selectCallback = function (id) {
document.forms[0][fieldNameOrCallback + '_id'].value = id;
doSubmitRefresh();
};
} else {
resultForm.selectCallback = fieldNameOrCallback;
}
// The call back to when the search result has returned
var searchResultCallback = createResultCallback(resultForm);
var ds = '
Last Name:
' +
seachOperationSelect('last_name_op') +'
First Name:
' +
seachOperationSelect('first_name_op') + '
';
$(ds).dialog({
position: [(window.innerWidth / 2) - 225,(window.innerHeight / 2) - 120], bgiframe: true, modal: true, resizable: false, width: 450, title: "Find person whose: ", close: function () { $(this).remove(); }, open: function () { $('#last_name', this).focus(); },
buttons: {
"Search": function () {
var searchType = authRequired ? 'person-auth-required-search' : 'person-search';
// kick off the seach
SelectionSearch(searchType, searchResultCallback,
{ first_name_op: $('#first_name_op', this).val(),
first_name: $('#first_name', this).val(),
last_name_op: $('#last_name_op', this).val(),
last_name: $('#last_name', this).val(),
outage_number: crow.page.outageNumber
});
$(this).dialog('close'); return false;
},
"Cancel": function () { $(this).dialog('close'); return false; }
}
});
}
// end showSelectPerson----------------------------------------------------------
//========================================
// Chooser Class
function StandardChoosers() {
///This is the set of standard choosers.
// private fields
var me = this;
// private methods
var refreshPage = function () {
///this will revre
if (window.doSubmitRefresh)
window.doSubmitRefresh();
};
this.valueHandlerInpendantPageRefresh = function(labelTextbox, idField) {
var matchString = labelTextbox.value;
var oldClass = labelTextbox.className;
return {
text: matchString,
beginSearch: function() {
if (oldClass === '')
labelTextbox.className = 'validating_input';
else
labelTextbox.className += ' validating_input';
},
nonSelectCallback: function() {
labelTextbox.className = oldClass;
},
selectCallback: function(id, name) {
idField.value = id;
labelTextbox.value = name;
refreshPage();
labelTextbox.className = oldClass;
}
};
};
this.valueHandlerPageRefresh = function (fieldName) {
var form = document.forms[0];
return me.valueHandlerInpendantPageRefresh(form[fieldName + '_label'], form[fieldName + '_id']);
};
//public methods
this.selectEmployer = function(fieldOrCallback, searchAll) {
/// This allows the user to select employers from a list for a instance textbox.
///The input field to read and update.
///if true will return all employers otherwise will only
/// return the ones the match the entered text.
var employer = '';
if (!searchAll) {
employer = document.forms[0][field + '_name'].value;
if (employer.replace( / /g , '') === '') {
document.forms[0][field + '_id'].value = 0;
refreshPage();
return;
}
}
var resultForm = {
title: "Select an employer and click 'Select' below...",
columns: [{ title: 'Employer', isLabel: true, fieldName: 'label' }],
selectCallback: typeof fieldOrCallback === 'string'
? function(id) {
document.forms[0][field + '_id'].value = id;
refreshPage();
}
: fieldOrCallback
};
SelectionSearch('employer-search', createResultCallback(resultForm), { text: employer });
};
this.selectDocument = function (formTitle, options) {
var resultForm = {
title: formTitle,
columns: [{ title: 'Title', isLabel: true, fieldName: 'title' }]
}
if (typeof options.selectCallback !== 'undefined') {
resultForm.selectCallback = options.selectCallback;
}
if (typeof options.onHasResults !== 'undefined') {
resultForm.onHasResults = options.onHasResults;
}
SelectionSearch('select-document', createResultCallback(resultForm), { });
};
this.selectEquipmentForControl = function(fieldName, options) {
if (fieldName === undefined)
fieldName = 'instance';
var control = crow.selectors.valueHandlerPageRefresh(fieldName);
crow.selectors.selectEquipment(control, options);
};
this.selectEquipment = function (control, options) {
if (control.text === '' && !options.allowBlank) {
control.selectCallback(0, '');
return;
}
var resultForm = {
title: options.title ? options.title : "Select one piece of circuit/equipment...",
columns: options.useAbbreviation ? [{ title: options.abbrLabel, fieldName: 'abbr' }, { title: 'Name', fieldName: 'label', isLabel: true }] : [{ title: 'Name', fieldName: 'label', isLabel: true }],
selectCallback: control.selectCallback,
cancelCallback: control.cancelCallback,
nonSelectCallback: control.nonSelectCallback,
noMatchAlert: control.noMatchAlert,
getName: options.returnAbbrIfAvailable ? function (r) { if(r.abbr.length > 0) return r.abbr; else return r.label; } : null
};
if (control.beginSearch)
control.beginSearch();
var resultCallback = createResultCallback(resultForm);
options.match_string = control.text;
SelectionSearch("equipment-search", resultCallback,options);
};
//public methods
this.selectStation = function (field, exactMatch, selectCallback, nonSelectCallback) {
/// This allows the user to select employers from a list for a instance textbox.
///The input field to read and update.
///Find an exact Match.
var form = document.forms[0];
if (!selectCallback) {
selectCallback = function (id, name) {
$('#' + field + '_id').val(id).trigger('change');
$('#' + field + '_name').val(name);
refreshPage();
};
}
var station = form[field + '_name'].value;
var resultForm = {
title: "Select an station and click 'Select' below...",
columns: [{ title: 'Abbrev', isLabel: true, fieldName: 'abbrev' },
{ title: 'Name', isLabel: true, fieldName: 'name' }
],
selectCallback: selectCallback,
nonSelectCallback: nonSelectCallback,
noMatchAlert: 'No stations were found.',
getName: function (result) { return result.abbrev === "" ? result.name : result.abbrev; }
};
SelectionSearch('station-search', createResultCallback(resultForm), { text: station, exact_match: exactMatch });
};
this.selectParentResource = function (field, childClassId, relationshipId, selectCallback, nonSelectCallback) {
var callerNameInput = $('#' + field + '_name');
var callerIdInput = $('#' + field + '_id');
if (!selectCallback) {
selectCallback = function (id, name) {
callerIdInput.val(id);
callerNameInput.val(name);
};
}
if (callerNameInput.val() === "") {
if (callerIdInput.val() == "0")
return;
selectCallback(0, "");
return;
}
if (!childClassId) {
childClassId = callerNameInput.attr('classId');
}
if (!relationshipId) {
relationshipId = callerNameInput.attr('relationshipId');
}
var resultForm = {
title: "Select a Parent Resource and click 'Select' below...",
columns: [
{ title: 'Name', isLabel: true, fieldName: 'label' }
],
selectCallback: selectCallback,
nonSelectCallback: nonSelectCallback,
getName: function (result) { return result.label; }
};
SelectionSearch('resource-search', createResultCallback(resultForm), { text: callerNameInput.val(), class_id: childClassId, relationship_id: relationshipId });
};
this.clear = function(name, callback) {
///This clear an resource selector
///The name of the resource selector
///this is the col
var form = document.forms[0];
form[name + '_id'].value = 0;
form[name + '_name'].value = '';
if (callback === undefined)
refreshPage();
else
callback();
};
this.showEquipment = function (classId, instanceId, stationId, onCloseNewEquip) {
///This show a resource or allow the user to create a resource.
///The base class id of the resource.
///This is the instance id or 0 if the item is new equipment.
///This is class ids list as a text string.
var url;
var windowId = 'showEquipmentDialog';
var dialogLoaded = function (dia) {
var diaWindow = getInlineDialogWindow(windowId);
diaWindow.caller = {
updateTitle: function (title) {
dia.dialog('option', 'title', title);
},
doClose: function (newInstanceId, newClassId, newStationId) {
dia.dialog('close');
if (onCloseNewEquip && newInstanceId)
onCloseNewEquip(newInstanceId, newClassId, newStationId);
},
selectStation: me.selectStation
};
if (diaWindow.callerReady)
diaWindow.callerReady(dia);
};
var newlabel = instanceId === 0 ? ' (New)' : '';
var options = { dialogLoaded: dialogLoaded, id: windowId, onClose: onCloseNewEquip };
options.width = 830;
options.height = 630;
if (classId == 191) {
url = '../Outages/add_nim_equipment.aspx?';
url += '&station_id=' + stationId;
options.height = 'auto';
options.title = 'Not In Model' + newlabel;
} else {
url = '../Instances/resource_form.ashx?instance_id=' + instanceId;
options.height = 630;
if (classId)
url += '&class_id=' + classId;
}
openInlineDialog(url, options);
};
this.createNewEquipment = function (allowedClassIds, stationId, onCloseNewEquip) {
var resultForm = {
title: 'Select Equipment Type',
columns: [{ title: 'Type', isLabel: true, fieldName: 'name'}],
selectCallback: function (id) {
me.showEquipment(id, 0, stationId, onCloseNewEquip);
},
multipleSelection: false
};
SelectionSearch('new-equipment-type', createResultCallback(resultForm), { allowedClassIdFilter: allowedClassIds });
};
this.showSelectOutageEquip = function (callbackName, allowedClassIds, multiSelect, outageReference, outageRevision, updateOR, updateEV) {
if (! updateOR ) { updateOR = ''; };
if (! updateEV ) { updateEV = ''; };
var url = '../Outages/outage_equip_search.aspx';
if (typeof callbackName != 'function')
url += "?callback=" + callbackName;
if (allowedClassIds)
url += (url.indexOf('?') > -1 ? '&' : '?') + 'allowed_class_ids=' + allowedClassIds;
if (multiSelect !== undefined) {
url += (url.indexOf('?') > -1 ? '&' : '?') + 'multi_select=' + (multiSelect ? 'y' : 'n');
}
if (outageReference)
url += "&outage_number=" + outageReference;
var width = window.lEquipSelectionWidth ? window.lEquipSelectionWidth : 550;
var options = {
width: width ,
height: window.lEquipSelectionHeight ? window.lEquipSelectionHeight : 350,
title: 'Select Circuits/Equipment...',
dialogLoaded: function (dia) {
var diaWindow = getInlineDialogWindow();
dia.dialog('option', 'width', diaWindow.dialogWidth);
var scrnHeight = findInlineDialog('#dialog-container').height() + 100;
dia.dialog('option', 'height', scrnHeight);
diaWindow.caller = {
doNew: me.createNewEquipment,
showEquipment:me.showEquipment,
doCancel: function () {
dia.dialog('close');
},
orginalWidth:width,
updateWidth: function (newWidth) { dia.dialog('option', 'width', newWidth); },
equipmentSelected: function (type, values) {
callbackName(type, values);
dia.dialog('close');
},
equipmentSearch: function (match, operation, componentOptions, noMatchText) {
var resultForm = {
columns: [{ title: 'Name', fieldName: 'label', isLabel: true}],
selectCallback: function (ids) {
if (multiSelect)
ids = ids.join();
callbackName('ids', ids);
},
onHasResults: function () { dia.dialog('close'); },
noMatchAlert: 'No circuits/equipment found matching your criteria.\n' + noMatchText,
multipleSelection: multiSelect
};
if (componentOptions.includeOptions) {
resultForm.filterDiv = function (dialog, divForFilter, updateTable) {
var html = '';
html += '';
divForFilter.html(html);
divForFilter.find('input').click(function () {
var checked = divForFilter.find('input:checked').val();
SelectionSearch("equipment-search", updateTable, { match_string: match, operation: operation, use_session: true, include_components: checked, outage_reference: outageReference, outage_revision: outageRevision, can_update_or: updateOR, can_update_ev: updateEV });
});
};
}
if (multiSelect)
resultForm.title = 'Select one or more circuit/equipment...';
else
resultForm.title = 'Select one circuit/equipment...';
//resultForm.heading = function() { return 'Select one or more circuits/equipment and click "OK" below...'; };
var resultCallback = createResultCallback(resultForm);
SelectionSearch("equipment-search", resultCallback, { match_string: match, operation: operation, use_session: true, outage_reference:outageReference, outage_revision:outageRevision, can_update_or: updateOR, can_update_ev: updateEV });
}
};
}
};
openInlineDialog(url, options);
};
this.showSelectIsolPoint = function (callback, multipleSels, cancelCallback, classIds, forSwitchOrder) {
var url = '../Outages/isol_point_search.aspx';
if (forSwitchOrder)
url += '?forSwitchOrder=1';
var options = {
width: 500,
height: 250,
title: 'Select Isolating Points...',
dialogLoaded: function(dia) {
var dialogWindow = getInlineDialogWindow();
dia.dialog('option', 'height', dialogWindow.dialogHeight);
if (dialogWindow.document.title !== "") {
dia.dialog('option', 'title', "Select " + dialogWindow.document.title + "...");
}
dialogWindow.caller = {
doCancel: function () {if (cancelCallback) cancelCallback(); dia.dialog('close'); },
showEquipment: me.showEquipment,
equipmentSelected: function(type, values) {
callback(type, values);
dia.dialog('close');
},
equipmentSearch: function (operation, match, noMatchText) {
var resultForm = {
columns: [{ title: 'Name', fieldName: 'label', isLabel: true }],
selectCallback: function (ids) {
if ($.isArray(ids))
ids = ids.join();
callback('ids', ids);
},
onHasResults: function () { dia.dialog('close'); },
//noMatchAlert: 'No ' + dialogWindow.document.title + ' found matching your criteria.\n' +
noMatchAlert: ((dialogWindow.document.title === "") ? 'No isolating points found matching your criteria.\n' : 'No ' + dialogWindow.document.title + ' found matching your criteria.\n') + noMatchText,
tooManyResultsAlert: function(result) {
return "This query has returned only the first " + result.maxRows + " items. \n" +
"If the equipment you want to select is not in this list, \n" +
"please perform a new query specifying the equipment \n" +
"name in more detail. E.g., if you want to select \n" +
'"CSQ T2", you can type "CSQ T" or "CSQ T2."';
},
title: 'Select an isolating device...',
multipleSelection: multipleSels === false ? false : true
/*heading: function (result) {
if (result.result.length > 0)
return "Select one or more isolating devices and click "OK" below...";
else
return "No isolating devices found.";
}*/
};
var resultCallback = createResultCallback(resultForm);
var parms = { match_string: match, operation: operation, for_type: 'IsolatingPoints' }
if (classIds)parms['allowed_class_ids'] = classIds;
SelectionSearch("equipment-search", resultCallback, parms);
}
};
}
};
openInlineDialog(url, options);
};
this.showTypeSelect = function (classId, field, shouldRefreshPage) {
/// This allows the user to select instances from a list for a instance textbox.
///Show all the instances for this crow class.
///The input field to read and update.
///refreshPage whether the update of the field should cause a page refresh.
var resultForm = {
titleOutput: function (results) { return results.title; },
columns: [{ title: 'Abbrev', isLabel: true, fieldName: 'abbrev',width:70 },
{ title: 'Name', isLabel: true, fieldName: 'name'}],
getName: function (r) { return r.abbrev ? r.abbrev : r.name; },
selectCallback: function (ids, names) {
// The names are in the format abbrev - name we need to get just the abbrev.
document.forms[0][field].value = names.join(',');
if (shouldRefreshPage)
refreshPage();
},
multipleSelection: true
};
SelectionPost('type-select', createResultCallback(resultForm), { text: document.forms[0][field].value, class_id: classId });
};
this.showFilteredTypeSelect = function (classId, search, callback, onHasResults, cancelCallback, fld, multiple) {
/// This allows the user to select instances from a list for a instance textbox.
///Show all the instances for this crow class.
///The input field to read and update.
///refreshPage whether the update of the field should cause a page refresh.
if (multiple !== false)
multiple = true;
var resultForm = {
titleOutput: function (results) { return results.title; },
columns: classId == 34 ? [{ title: 'Name', isLabel: true, fieldName: 'name'}] :
[{ title: 'Abbrev', isLabel: false, fieldName: 'abbrev', width: 70 },
{ title: 'Name', isLabel: true, fieldName: 'name'}],
getName: function (r) {return typeof (r.abbrev) != 'undefined' && r.abbrev ? r.abbrev : r.name; },
selectCallback: callback,
multipleSelection: multiple,
onHasResults: onHasResults,
cancelCallback: cancelCallback,
fld: fld
};
SelectionPost('filtered-type-select', createResultCallback(resultForm), { text: search, class_id: classId, fld: fld });
};
}
function jqPrompt(caption, title, callback) {
var ds = "
';
$(ds).dialog({
modal: true, resizable: false, width: 500, title: title, close: function () { $(this).remove(); },
open: function () {
$('input:text[name=name]').keypress(function(e) {
if (e.keyCode === $.ui.keyCode.ENTER)
$(this).parents('.ui-dialog').find('.ui-dialog-buttonpane button:eq(0)').trigger("click");
});
},
buttons: {
"OK": function () {
var result = $('input:text[name=name]').val();
$(this).dialog('close');
callback(result);
}, "Cancel": function () { $(this).dialog('close'); callback(null); }
}
});
}
function jqAlert(caption, title) {
if (!window.jQuery) {
alert(caption);
return;
}
var ds = "
';
$(ds).dialog({
modal: true, resizable: false, width: 400, title: title, close: function () { $(this).remove(); },
open: function () { $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus(); },
buttons: {"OK": function () {$(this).dialog('close');}}
});
}
function jqConfirm(caption, title, callback) {
var ds = "
';
$(ds).dialog({
modal: true, resizable: false, width: 400, title: title, close: function () { $(this).remove(); },
open: function () { $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus(); },
buttons: {
"Yes": function () { result = true; $(this).dialog('close'); callback(true) },
"No": function () { $(this).dialog('close'); callback(false) }
}
});
}
function newOutageRequest(category) {
var loc = "outage_req_summary.aspx?new_outage=1";
if (typeof newOutageRequestDefaultTab !== "undefined" )
loc = newOutageRequestDefaultTab + ".aspx?new_outage=1";
if (category == "UserChoose") {
SelectionPost("select-outage-categories",
function (results) {
var a = results.result;
var ds = "
";
for (var i = 0; i < a.length; i++) {
var cat = a[i];
ds += "" +
"\ ";
}
ds += "
";
$(ds).dialog({
modal: true, resizable: false, width: 400, title: "Please choose outage type: ", close: function () { $(this).remove(); },
open: function () { $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus(); },
buttons: {
"OK": function () {
var cat = $('input:radio[name=outage_type]:checked').val();
$(this).dialog('close');
document.location = loc + "&category=" + cat;
return false;
}, "Cancel": function () { $(this).dialog('close'); }
}
});
});
}
else {
document.location = loc + "&category=" + category;
}
return false;
}
function pasteReferenceNumber(e, server_id, ref_id) {
setTimeout("afterpasteReferenceNumber('" + (e.target || e.srcElement).name + "','" + server_id + "','" + ref_id + "')", 1);
}
function afterpasteReferenceNumber(t, server_id, ref_id) {
var frm = document.forms[0];
var svr = frm[server_id];
var s = frm[t].value;
var r = frm[ref_id];
var m = /^\s*([0-9])-([0-9]{1,9})\s*$/.exec(s);
if (m) {
svr.value = m[1];
r.value = m[2];
r.focus();
} else {
//r.value = svr.value = "";
//var svrCurr = svr.value;
//var rCurr = r.value;
if (t == server_id) {
svr.value = "";
}
else {
r.value = "";
}
var i = parseInt(s, 10);
if (!isNaN(i)) frm[t].value = i;
}
svr.maxLength = 1;
r.maxLength = 8;
}
function idnumber_onKeyDown(event) {
var c = event.keyCode;
if (event.ctrlKey) {
if (c == 86) (event.target || event.srcElement).maxLength = 255;
return true;
}
if ((c >= 48 && c <= 57) || // Numeric key -- do nothing
(c >= 96 && c <= 105) || // Numeric Keypad
c == 8 || c == 46 || c == 37 || c == 39 || c == 9 || c == 16 || c == 13) // Delete/backspace/arrow keys/tab/shift/return -- do nothing
return true;
// other -- filter keystroke
event.returnValue = false;
return false;
}
function serverNumber_onKeyDown(event, next) {
var c = event.keyCode;
if (event.ctrlKey) {
if (c == 86) (event.target || event.srcElement).maxLength = 255;
return true;
}
if ((c >= 48 && c <= 57) || // Numeric key -- do nothing
(c >= 96 && c <= 105) || // Numeric Keypad
c == 8 || c == 46 || c == 37 || c == 39 || c == 9
|| c == 16 || c == 13) { // Delete/backspace/arrow keys/tab/shift/return -- do nothing
return true;
}
if (c == 189 || c == 109) {
// hyphen key -- filter and go to event ID field
event.returnValue = false;
document.forms[0][next].focus();
return false;
}
// other -- filter keystroke
event.returnValue = false;
return false;
}
function serverNumber_onKeyUp(event, next) {
var c = event.keyCode;
if (c >= 48 && c <= 57 || (c >= 96 && c <= 105) || c == 13) {
// Numeric key -- jump to event ID field
document.forms[0][next].focus();
}
}
Date.prototype.addDays = function (days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
Date.prototype.addTimeString = function (timeString) {
var dat = new Date(this.valueOf());
var timeParts = timeString.split(':');
var milliSecondsToAdd = 0;
if (parseInt(timeParts[0])) {
milliSecondsToAdd = timeParts[0] * 60 * 60 * 1000;
}
if (parseInt(timeParts[1])) {
milliSecondsToAdd = milliSecondsToAdd + (timeParts[1] * 60 * 1000);
}
if (parseInt(timeParts[2])) {
milliSecondsToAdd = milliSecondsToAdd + (timeParts[1] * 1000);
}
var currentMilliSeconds = dat.getTime();
return new Date(currentMilliSeconds + milliSecondsToAdd);
};
/**
*/
function AttachmentPanel(numberType, referenceNumber, submit, changeReqNum) {
this.view = function (fileId) {
submit('action=view_attachment&attachment_id=' + fileId);
};
this.add = function () {
var added = false;
var dialog;
var url = '../Selection/select_file_attachment.aspx?' + numberType + '=' + referenceNumber + (changeReqNum ? "&change_req_number=" +changeReqNum : '');
var options = { title: 'Select File Attachment', width: 600, height: $.browser.msie ? 300 : 240,
dialogLoaded: function () { if (added) submit(); },
buttons: { " OK ": function () {
added = true;
dialog.dialog('option', 'buttons', {});
getInlineDialogWindow().doSubmit();
},
"Cancel": function () { $(this).dialog('close'); }
}
};
dialog = openInlineDialog(url, options);
};
this.deleteRow = function (row) {
submit('action=remove_attachment&row_num=' + row);
};
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function selectColumns() {
var ds = "";
var btns = {
OK: function () {
crow.controls.periods.setLayout(this.firstElementChild.contentWindow.getColumnConfiguration());
$(this).dialog('close');
}
};
btns["Cancel"] = function () { $(this).dialog('close'); };
$(ds).dialog({
dialogClass: 'modalDialog', bgiframe: true, modal: true, resizable: false,
title: 'Select Columns',
close: function (event, ui) { $('#newViewFrame').attr('src', "about:blank"); $(this).remove(); },
open: function (event, ui) { $('#newViewFrame').attr('src', '../Base/ColumnSelector.aspx'); },
width: 550, height: 450,
buttons: btns
});
return false;
}
function showHelp(helpFileInstanceAbbrev) {
var url = "../HelpService.ashx?abbrev=" + helpFileInstanceAbbrev;
window.open(url);
}
if (window.jQuery) {
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
}
function doCompleteLastAction() {
if (angular) {
var injector = $('.ng-scope[ng-controller]:first').injector();
if (injector) {
var ds = injector.get("dataService");
if (ds && ds.replayCommand())
return;
}
}
doSubmit("completeLastAction=Y");
}
Array.prototype.find || Object.defineProperty(Array.prototype, "find", { value: function (r) { if (null == this) throw new TypeError('"this" is null or not defined'); var t = Object(this), e = t.length >>> 0; if ("function" != typeof r) throw new TypeError("predicate must be a function"); for (var n = arguments[1], o = 0; o < e;) { var i = t[o]; if (r.call(n, i, o, t)) return i; o++ } } });
Array.prototype.findIndex || Object.defineProperty(Array.prototype, "findIndex", { value: function (r) { if (null == this) throw new TypeError('"this" is null or not defined'); var e = Object(this), t = e.length >>> 0; if ("function" != typeof r) throw new TypeError("predicate must be a function"); for (var n = arguments[1], o = 0; o < t;) { var i = e[o]; if (r.call(n, i, o, e)) return o; o++ } return -1 } });