////////////////////////////////////////////////////////////////////////////////
// Special objects that allow outside routines to tap into the tabs code
////////////////////////////////////////////////////////////////////////////////

// activate_menulayer tests this flag to make sure the page is
// loaded before the pulldown menus are clicked.
var layerFlag = 0;
function setLayerFlag() {
    layerFlag = 1;
}

//Enable the event handler
createEventObj('clearActive_menulayer', 'MOUSEUP')

createOnLoadObj('layerFlag', setLayerFlag);

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


//browser detection
if (_version != '1.2') {
    window.onerror = new Function("return true;");
}
var isDynamic = ( ((document.layers && document.layers['test_menulayer']) || (document.all && document.all['test_menulayer'])) && !isMacIE );
//var isDynamic = ( isNSN6 || isMoz5 || (((document.layers && document.layers['test_menulayer']) || (document.all && document.all['test_menulayer']) )) );
var active_menulayer = '';
var lastActive_menulayer = '';
var form = 0;

if (isNSN6 || isMoz5) {
    var layerRef = "document";
} else if (isNSN) {
    var layerRef = "document";
} else {
    var layerRef = "document.all";
}

if (isNSN6 || isMoz5) {
    var styleRef = ".style";
} else if (isNSN) {
   var styleRef = "";
} else {
   var styleRef = ".style";
}

//  NOTE!  For this thing to work the anchor "barBottom" must be a *body-level* tag
//  or the menulayers will not render at the correct position   (or until Microsoft
//  provides another way of doing this...)
//  anchorId 
function activate_menulayer(menulayerId, type, anchorId) {  
    var maxWidth = 0;
    var left = 0;        
    var top = 0;
//   if (!layerFlag) {return};

    if (active_menulayer != menulayerId) {
        if (lastActive_menulayer == menulayerId) {
            lastActive_menulayer = '';
            return;
        }  
        if (active_menulayer != '') hideMenu(active_menulayer);
        active_menulayer = menulayerId;
        lastActive_menulayer = active_menulayer
        if (isNSN || isMoz5) {  
            if (anchorId == null) { 
                anchorId = menulayerId + "_a";
            } 
            var top = getAnchorTop(anchorId);
            var left =  getAnchorLeft(anchorId);
            maxWidth = parseInt(window.innerWidth);    
            if (isNSN6 || isMoz5) {    
                //left =  document.anchors[anchorId].offsetLeft + 5;
                //if (left + 330 > maxWidth) {left = maxWidth-330}
                if (left + 250 > maxWidth) {left = maxWidth-250}

                if (left < 0) {left = 0}
                document.getElementById(menulayerId).style.top = (top + 20) + "px"; 
                document.getElementById(menulayerId).style.left = left + "px";
                if (form) { document.getElementById(menulayerId).style.width = 250; }  
            } else {
                left =  document.anchors[anchorId].x - 2;
                if (left + 330 > maxWidth) {left = maxWidth-330}
                //if (left + 150 > maxWidth) {left = maxWidth-150}
                if (left < 0) {left = 0}
                // 1/21: do we really need to check if it's a form...??? mhu
                //if (form) {
                //    document[menulayerId].top = document.anchors[anchorId].y + 65;
                //    document[menulayerId].left = document.anchors[anchorId].x + 60;
                //} else {                
                    document[menulayerId].top = document.anchors[anchorId].y + 15;
                    document[menulayerId].left = left;
                //}
            }
        } else {
            var isIE4 = (navigator.userAgent.indexOf("IE 4") > -1) 
            maxWidth = document.body.scrollWidth;
            if (anchorId == null) {
                anchorId = menulayerId + "_a";
                left =  document.all[menulayerId+"_bottom"].offsetParent.offsetLeft + 7
            } 
            left =  document.all[anchorId].offsetParent.offsetLeft
            if (left <= 0) {left = 2}  
            if (isIE4) {
		        if (type == "context") {
			        document.all[menulayerId].style.pixelTop = document.all["barBottom"].offsetTop + 15; 
                    document.all[menulayerId].style.width = 150;
		        } else if (type == "tab")  {	
			        document.all[menulayerId].style.pixelTop = document.all["barBottom"].offsetTop + 40; 
		            document.all[menulayerId].style.width = 250;
                } else if (type == "toolbar") {                
                    document.all[menulayerId].style.width = 150;
                    document.all[menulayerId].style.pixelTop = document.all["barBottom"].offsetTop + 65;
                }
	        } else {                        
                if (form) {
                    document.all[menulayerId].style.pixelTop = getAnchorTop(anchorId);
                } else {
                    document.all[menulayerId].style.pixelTop = document.all[anchorId].offsetParent.offsetParent.offsetTop + 23;
                    //document.all[menulayerId].style.pixelTop = document.all[anchorId];
                }
            }
            //if (left + 320 > maxWidth) {left = maxWidth-320}
            if (left + 250 > maxWidth) {left = maxWidth-250}
            document.all[menulayerId].style.pixelLeft = left;
        }
//alert("activate_menulayer: "+left+" "+getAnchorTop(anchorId))
        showMenu(menulayerId);
    }
}

function activate_textlayer(menulayerId, type, anchorId) {
    form = 1;
    active_menulayer = '';
    activate_menulayer(menulayerId, type, anchorId);
    form = 0;
}

function showMenu(layerId) {
    if (isNSN6 || isMoz5) {    
        eval(layerRef + '.getElementById("' + layerId + '")' + styleRef + '.visibility = "visible"'); 
    } else {
        eval(layerRef + '["' + layerId + '"]' + styleRef + '.visibility = "visible"');
    //Hide the various form elements used by the product while the menu is up
        toggleSpannedAreas('attrformspan','hidden')
        toggleSpannedAreas('attrform2span','hidden')
        toggleSpannedAreas('viewentry','hidden')
    //Hide any form elements that may be visible
        for (var name in spannedAreasList) {
            spannedAreasList[name].hide()
        }
    }
}

function hideMenu(layerId) {
    if (isNSN6 || isMoz5) {
        eval(layerRef + '.getElementById("' + layerId + '")' + styleRef + '.visibility = "hidden"'); 
    } else {
        eval(layerRef + '["' + layerId + '"]' + styleRef + '.visibility = "hidden"');
    //Make the other form elements visible again
        toggleSpannedAreas('attrformspan','visible')
        toggleSpannedAreas('attrform2span','visible')
        toggleSpannedAreas('viewentry','visible')
    //Show any form elements that should be returned to the visible state
        for (var name in spannedAreasList) {
            spannedAreasList[name].show()
        }
    }

    // if we're in a form, don't do this
    form = 0;
}

// Clears (hides) the active menulayer (if any)
function clearActive_menulayer() {
    if (form) {return}
    form = 0;

    lastActive_menulayer = active_menulayer;
    if (active_menulayer != '') {
        menulayerId = active_menulayer;
        hideMenu(menulayerId);
        active_menulayer = '';
    }     
    if (self.clearActiveMenu) {self.clearActiveMenu()}
}

//Routine called at "onLoad" time
function init() {
    //Now, call any other routines that want to be called at onLoad time
    for (var name in onLoadList) {
        onLoadList[name].initRoutine();
    }
}

// Netscape Navigator requires a little push	
function reloadNSN() {
    top.location.reload();
}

// NN4.7 does not use this...added to "fix NN6 support"
// old test: ( (isNSN6 || isMoz5) || (isDynamic && isNSN) ) 
if (isNSN6 || isDynamic) {
    onresize = reloadNSN;
}

// this func is primarily for WFS, which is called in all contexts so this
// function is here rather than 3 or 4 other template files. 
function launchNew(url, width, height) {
    if (width == null || width == 0) {width=700}
    if (height == null || height == 0) {height=650}
    var win = self.window.open(url, 'new', 'width='+width+',height='+height+',resizable,scrollbars');
    if (self.window.focus && win) {win.focus()}
}


// this function takes a URL (typically from self.window.location.href) and
// tries to turn off portal mode by taking out the .portal piece of the URL
// note: it's argument must be a string
function turnOffPortalMode(url) {
  var loc = url.lastIndexOf('.portal');
  var pre = url.substring(0,loc);
  var len = url.length;
  var post = url.substring(loc+7,len);
  return pre+post;
}

// these functions set the date using the "datepicker" calendar

function setdate(date, formName, id, seqNum, opt, funcCall) {
    var day;
    if (date.substring(3,4) == '0') {
        day = date.substring(4,5);
    } else {
        day = date.substring(3,5);
    }
    
    day = parseInt(day);

    dayele = id + 'day' + seqNum;
    eval('self.document.' + formName + '.' + dayele + '.options[' + day + '].selected = true');

    var month;
    if (date.substring(0,1) == '0') {
        month = date.substring(1,2);
    } else {
        month = date.substring(0,2);
    }

    month = parseInt(month);
    monele = id + 'month' + seqNum;
    eval('self.document.' + formName + '.' + monele + '.options[' + month + '].selected = true');

    // year range slides from -3 to +3 years from the current year; see ssf_support.html, 
    // Date proc. The following gyrations calculate the index into the year options array.
    var year;
    year = date.substring(6,10);
    today = new Date();
    thisYear = new Date();
    thisYear = today.getYear();

    // some browsers return an offset from 1900; IE returns the year. Opera, in IE mode,
    // returns the offset (which is correct; IE is the rogue browser: what a surprise).
    if (isNSN || isNSN6 || isMoz5 || isMacIE || thisYear < 1900) {
        thisYear = eval(thisYear + 1900);
    }

    year = eval(parseInt(year) - (thisYear - 7));
    yearele = id + 'year' + seqNum;
    eval('self.document.' + formName + '.' + yearele + '.options[' + year + '].selected = true');  
    if (funcCall != '') {
        eval(funcCall);
    }
}

function ThisMonth(divName) {
        x = getClickPositionX();
        y = getClickPositionY();
        ShowHideDiv(divName, x, y)
}

function NextMonth(divName) {
        x = getClickPositionX();
        y = getClickPositionY();
        ShowHideDiv(divName, x, y)
}

// call for each time specified in the form
// assumes Date widget is used to supply start and end times, with 'allday' an option
function allday(formName, hourName1, minuteName1, hourName2, minuteName2) {

    eval('self.document.' + formName + '.' + hourName1 + '.options[25].selected = true');
    eval('self.document.' + formName + '.' + hourName2 + '.options[25].selected = true');
    eval('self.document.' + formName + '.' + minuteName1 + '.options[1].selected = true');
    eval('self.document.' + formName + '.' + minuteName2 + '.options[1].selected = true');
}

// Sets the current date and time in the date/time select boxes.
// Called by Now proc in ssf_support.html, which specifies the
// current date and time in the user's time zone.
function now(formName, id, seqNum, date, hours, minutes) {
    setdate(date, formName, id, seqNum,"","");

    if (hours != "" && minutes != "") {
        hrfield = id+"hour"+seqNum;
        minfield = id+"minute"+seqNum;

        sethr(hours, formName, hrfield);
        setmin(minutes, formName, minfield);
    }
}

// The "time picker" (MakeTimeGrid) calls these two functions
function sethr(hr, formName, hourName, funcCall, minuteName) {
    var valref;
    var time;

    valref = eval('self.document.' + formName + '.' + hourName);

    // switch the minute from '--' to '00' 
    if (valref.options[0].selected == true && minuteName != null) {
        setmin('00',formName, minuteName,'');
    }
   
    if (hr.substring(0,1) == '0') {
        hr = hr.substring(1,2);
    }
    timeIndex = eval(parseInt(hr) + 1);
    valref.options[timeIndex].selected = true;
    if (funcCall != '') {
        eval(funcCall);
    }
}

function setmin(min, formName, minuteName, funcCall) {
    var valref;
    var time;
    valref = eval('self.document.' + formName + '.' + minuteName);
   
    if (min.substring(0,1) == '0') {
        min = min.substring(1,2);
    }

    minIndex = eval(parseInt(min) / 5);
    minIndex = eval(parseInt(minIndex) + 1)

    valref.options[minIndex].selected = true;
    if (funcCall != '') {
        eval(funcCall);
    }
}


// check if only one field was selected: invalid
// check that both fields are selected if time is required
function checkTime(formName, hourName, minName, fieldLabel, required, timeText) {
    if (fieldLabel == null) {var fieldLabel = "time"}

    var hourLength = eval('self.document.' + formName + '.' + hourName + '.length');
    for (var i = 0; i < hourLength; i++) {
        if (eval('self.document.' + formName + '.' + hourName + '.options[i].selected')) {
            var hour = eval('self.document.' + formName + '.' + hourName + '.options[i].value');
            break;
        }
    } 

    var minLength = eval('self.document.' + formName + '.' + minName + '.length');
    for (var j = 0; j < minLength; j++) {
        if (eval('self.document.' + formName + '.' + minName + '.options[j].selected')) {
            var minute = eval('self.document.' + formName + '.' + minName + '.options[j].value');
            break;
        } 
    }

    if ((hour == 99 && minute == 99) || (hour != 99 && minute != 99)) {
    // this is ok if dates are optional,otherwise...
        if ((required != null) && (hour == 99 || minute == 99)) {
            // alert defined in ssf_support.html for translation
            alert(alert1+" "+fieldLabel);     
            return false;
        }
    } else {
        // alert defined in ssf_support.html for translation
        alert(alert2+" "+fieldLabel);     
        return false;
    }

    return true;
}

function checkDateTime (formName, hourName, minName, dayName, monthName, yearName, now) {
    if (hourName != null) {
        var hourLength = eval('self.document.' + formName + '.' + hourName + '.length');
        for (var i = 0; i < hourLength; i++) {
            if (eval('self.document.' + formName + '.' + hourName + '.options[i].selected')) {
                var hour = eval('self.document.' + formName + '.' + hourName + '.options[i].value');
                break;
            }
        }
    } 

    if (minName != null) {
        var minLength = eval('self.document.' + formName + '.' + minName + '.length');
        for (var j = 0; j < minLength; j++) {
            if (eval('self.document.' + formName + '.' + minName + '.options[j].selected')) {
                var minute = eval('self.document.' + formName + '.' + minName + '.options[j].value');
                break;
            } 
        }
    } 

    var monthLength = eval('self.document.' + formName + '.' + monthName + '.length');
    for (var k = 0; k < monthLength; k++) {
        if (eval('self.document.' + formName + '.' + monthName + '.options[k].selected')) {
            var month = eval('self.document.' + formName + '.' + monthName + '.options[k].value');
            if (month > 0) {month--}
            break;
        }
    }

    var dayLength = eval('self.document.' + formName + '.' + dayName + '.length');
    for (var l = 0; l < dayLength; l++) {
        if (eval('self.document.' + formName + '.' + dayName + '.options[l].selected')) {
            var day = eval('self.document.' + formName + '.' + dayName + '.options[l].value');
            break;
        } 
    }

    var yearLength = eval('self.document.' + formName + '.' + yearName + '.length');
    for (var m = 0; m < yearLength; m++) {
        if (eval('self.document.' + formName + '.' + yearName + '.options[m].selected')) {
            var year = eval('self.document.' + formName + '.' + yearName + '.options[m].value');
            break;
        }
    }

    // date specified, no time: set time to 11:55 (virtual midnight)
    if ((hour == 99 && minute == 99) && (month != 0 && day != 0 && year != 0)) {
        eval('self.document.' + formName + '.' + hourName + '.options[i].value = "23"');
        eval('self.document.' + formName + '.' + minName + '.options[j].value = "55"');
        return true;
    }

    //time specified, not date: alert to correct this
    if (hourName != null && minName != null) {
        if ((hour != 99 && minute != 99) && (month == 0 && day == 0 && year == 0)) {
            alert(alert13);
            return false;
        }
    }


    if ((now != null) && (month != 0 && day != 0 && year != 0)) {
        if (hourName == null && minName == null) {
            var date = new Date(year, month, day);
        } else {
            var date = new Date(year, month, day, hour, minute);
        }
        var diff = eval(now.getTime() > date.getTime());
        if (diff) {
            return (confirm(alert14));
        }
    }

    return true;
}

// This function checks for valid date info for Date widget. This function should be 
// called in an onSubmit event handler in the form. If there is already an onSubmit
// handler called, it can be called within that function (see the calendar's 
// checkAnswers function); checkDate displays an alert with an error message and
// returns false if date info is incorrect. Otherwise, it returns true. The calling
// function may need to conditionalize the call so that it checks only on OK, not
// cancel or any other button (again, see the calendar's checkAnswers function).
// Forms that require a date but do not preset it must use the required arg: if it
// is non-null, an alert will be issued and false returned.

function checkDate(formName, dayName, monthName, yearName, fieldLabel, required, yearText) {
    if (fieldLabel == null) {var fieldLabel = "date"}
    var monthLength = eval('self.document.' + formName + '.' + monthName + '.length');
    for (var i = 0; i < monthLength; i++) {
        if (eval('self.document.' + formName + '.' + monthName + '.options[i].selected')) {
            var month = eval('self.document.' + formName + '.' + monthName + '.options[i].value');
            break;
        }
    }

    var dayLength = eval('self.document.' + formName + '.' + dayName + '.length');
    for (var j = 0; j < dayLength; j++) {
        if (eval('self.document.' + formName + '.' + dayName + '.options[j].selected')) {
            var day = eval('self.document.' + formName + '.' + dayName + '.options[j].value');
            break;
        } 
    }

    if (yearText == null) {
        var yearLength = eval('self.document.' + formName + '.' + yearName + '.length');

        for (var k = 0; k < yearLength; k++) {
            if (eval('self.document.' + formName + '.' + yearName + '.options[k].selected')) {
                var year = eval('self.document.' + formName + '.' + yearName + '.options[k].value');
                break;
            }
        }
    } else {
        var year = eval('self.document.'+formName+'.'+yearName+'.value');       
        if (isNaN(year)) {
            // alert defined in ssf_support.html for translation
            alert(alert3)
            return false;
        }
        if (year < 1970 || year > 2037) {
            // alert defined in ssf_support.html for translation
            alert(alert4)
            return false;
        }
    }

    if ((month == 0 && day == 0 && year == 0) || (month != 0 && day != 0 && year != 0)) {
        // this is ok if dates are optional,otherwise...
        if ((required != null) && (month == 0 && day == 0 && year == 0)) {
            // alert defined in ssf_support.html for translation
            alert(alert5+" "+fieldLabel);     
            return false;
        }
    } else {
        // alert defined in ssf_support.html for translation
        alert(alert6+" "+fieldLabel);
        return false;
    }

    if (month == 4 || month == 6 || month == 9 || month == 11) {
        if (day > 30) {
            // alert defined in ssf_support.html for translation
            alert(alert7);
            return false;
        }
    }
    
    //check if leap year; fortunately this is easy until 2100
    if (month == 2) {
        leap = parseInt(year) % 4;
        if (leap == 0) {
           if (day > 29) {
                // alert defined in ssf_support.html for translation
                alert(alert8);
                return false;
            } 
        } else if (day > 28) {
            // alert defined in ssf_support.html for translation
            alert(alert9)
            return false;
        }
    }
    return true;
}

 
function checkDateRange(formName, dayName1, monthName1, yearName1, dayName2, monthName2, yearName2, fieldLabel) {
    if (fieldLabel == null) {var fieldLabel = "date"}

    date1 = evalDate(formName, yearName1, monthName1, dayName1);
    date2 = evalDate(formName, yearName2, monthName2, dayName2);

    date1Int = date1.getTime();
    date2Int = date2.getTime();

//alert("here "+date2Int+" "+date1Int+" "+eval(date2Int >= date1Int))

    // neither specified.
    if (eval(date1Int == date2Int) && eval(date2Int < 0)) {
        return true;
    } 

// Do not require a start date. 
//    if (date1Int == -2211735600000 && date2Int != -2211735600000) {
        // alert defined in ssf_support.html for translation: no start date
//        return confirm(alert10);
//    } 

    if (eval(date1Int > 0) && eval (date2Int < 0)) {
        // alert defined in ssf_support.html for translation: no end date
        return confirm(alert11);
    } 

    // see if due date is later than start date
    if (eval(date2Int >= date1Int)) {
        return true;
    } else {
        // alert defined in ssf_support.html for translation: start later than end
        alert(alert12);
        return false;
    }
}

function evalDate(formName, yearName, monthName, dayName) {
    var monthLength = eval('self.document.' + formName + '.' + monthName + '.length');
    // months start at 0 in JS; our options don't. So adjust.
    for (var i = 0; i < monthLength; i++) {
        if (eval('self.document.' + formName + '.' + monthName + '.options[i].selected')) {
            var month = eval('self.document.' + formName + '.' + monthName + '.options[i].value') - 1;
            break;
        }
    }

    var dayLength = eval('self.document.' + formName + '.' + dayName + '.length');
    for (var j = 0; j < dayLength; j++) {
        if (eval('self.document.' + formName + '.' + dayName + '.options[j].selected')) {
            var day = eval('self.document.' + formName + '.' + dayName + '.options[j].value');
            break;
        } 
    } 
    var yearLength = eval('self.document.' + formName + '.' + yearName + '.length');

    for (var k = 0; k < yearLength; k++) {
        if (eval('self.document.' + formName + '.' + yearName + '.options[k].selected')) {
            var year = eval('self.document.' + formName + '.' + yearName + '.options[k].value');
            break;
        }
    }
    var date = new Date(year, month, day);
//    alert("evalDate: "+date+" "+year+" "+month+" "+day);
    return date
}
