function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function ValidateSearch(SearchString, Chapter) {
    alert(document.forms[1].SearchString + " " + SearchString);
    if ((document.forms[0].SearchString.value == "") && (document.forms[0].Chapter.selectedIndex == 0)) {
        alert("Please enter string to search for or select HVPQ chapter to view.");
    }
    else if (document.forms[0].SearchString.value != "") {
        if (document.forms[0].SearchString.value.length < 3) {
            alert("Please enter at least 3 characters in the search string.");
        }
        else {
        }
    }
    else {
    }
}

// Open a new window
function createWindow(link) {
    var URL = link;

    var windowName = 'Q88';

    if (document.all)
        var xMax = screen.width, yMax = screen.height;
    else
        if (document.layers)
        var xMax = window.outerWidth, yMax = window.outerHeight;
    else
        var xMax = 640, yMax = 480;

    var xOffset = (xMax - 200) / 2, yOffset = (yMax - 200) / 2;
    var features =
        'width=' + 660 +
        ',height=' + 400 +
        ',screenX=' + xOffset +
        ',screenY=' + yOffset +
        ',top=' + yOffset +
        ',directories=' + (0) +
        ',location=' + (0) +
        ',menubar=' + (0) +
        ',scrollbars=' + (1) +
        ',status=' + (0) +
        ',toolbar=' + (0) +
        ',resizable=' + (1);

    window.open(URL, windowName, features);
}

// Open a new window
function createWindowHeightWidth(link, width, height) {
    var URL = link;

    var windowName = 'Q88';

    if (document.all)
        var xMax = screen.width, yMax = screen.height;
    else
        if (document.layers)
        var xMax = window.outerWidth, yMax = window.outerHeight;
    else
        var xMax = 640, yMax = 480;

    var xOffset = (xMax - 200) / 2, yOffset = 50;
    var features =
        'width=' + width +
        ',height=' + height +
        ',screenX=' + xOffset +
        ',screenY=' + yOffset +
        ',top=' + yOffset +
        ',directories=' + (0) +
        ',location=' + (0) +
        ',menubar=' + (0) +
        ',scrollbars=' + (1) +
        ',status=' + (0) +
        ',toolbar=' + (0) +
        ',resizable=' + (1);

    window.open(URL, windowName, features);
}

function GetTimeZoneOffset() {
    now = new Date()
    var offset = now.getTimezoneOffset();
}

function ShowImgStatus(strField) {
    try {
        if (document["imgStatus" + strField].src.match("status_clear.gif") != null && document["imgStatus" + strField].title.length > 0)
            document["imgStatus" + strField].src = document["imgStatus" + strField].src.replace("status_clear.gif", "blue.png");
    }
    catch (err)
    { }
}

function HideImgStatus(strField) {
    try {
        if (document["imgStatus" + strField].src.match("blue.png") != null)
            document["imgStatus" + strField].src = document["imgStatus" + strField].src.replace("blue.png", "status_clear.gif");
    }
    catch (err)
    { }
}

function ReplaceData(fieldName) {
    if (window.event.keyCode == 45) {
        if (confirm('Replace answer with old value?')) {
            document.getElementById(fieldName).value = document.getElementById(fieldName).alt;
            //CheckData(fieldName);
            Page_ClientValidate();
        }
    }
}

function Search() {
    if (window.event.keyCode == 113) {
        wndSearch = window.open("Search.aspx?c=1&project=1", "wndSearch", "Top=50,Height=300,Width=750,scrollbars=1,location=no");
        wndSearch.focus();
    }
}

function ReplaceDataWControl(fieldName, imageID, e) {
    if (window.event.keyCode == 113) {
        Search();
    }
    else if (window.event.keyCode == 45) {
        if (fieldName != '') {
            if (confirm('Replace answer with old value?')) {
                document.getElementById(fieldName).value = document.getElementById(fieldName).alt.replace("\0 ", "\r\n");
                //if (imageID != null)
                //	CheckData(imageID);
                Page_ClientValidate();
            }
        }
    }
}

String.prototype.trim = function() { return this.replace(/^\s*|\s*$/g, ""); };

function trim(str) {
    return str.trim();
}

function DoubleConfirm(Message1, Message2) {
    answer = confirm(Message1);
    if (answer == 1) {
        return confirm(Message2);
    }
    return false;
}

function ConfirmAction(Message) {
    var Delimiter = ';';
    var answer = confirm(Message.substr(0, Message.indexOf(Delimiter)));
    if (answer == 1) {
        var URL = trim(Message.substr(Message.indexOf(Delimiter) + 1, Message.length)) + '&ref=' + URLEncode(window.location.href);
        window.location = URL;
    }

    return false;
}

function CharCount(objText, Limit) {
    if (objText.value.length >= Limit)
        if (window.event.keyCode != 8 && window.event.keyCode != 35 && window.event.keyCode != 36 && window.event.keyCode != 37 && window.event.keyCode != 38 && window.event.keyCode != 39 && window.event.keyCode != 40 && window.event.keyCode != 46 && document.selection.createRange().text.length == 0)
        window.event.returnValue = false;
}

// Get the browser type
var browser = new Browser();
function Browser() {
    var agt = navigator.userAgent.toLowerCase()
    this.major = parseInt(navigator.appVersion)
    this.nav = ((agt.indexOf('mozilla') != -1) && ((agt.indexOf('spoofer') == -1) && (agt.indexOf('compatible') == -1)))
    this.nav4 = (this.nav && (this.major == 4))
    this.nav4up = this.nav && (this.major >= 4)
    this.ie = (agt.indexOf("msie") != -1)
    this.ie4 = (this.ie && (this.major == 4))
    this.ie4up = this.ie && (this.major >= 4)
}

function EditableDDLAddNew(ddlAddItem, AddNewText) {

    var newItem;
    var MaxLength = 50;
    if (document.getElementById(ddlAddItem).options[document.getElementById(ddlAddItem).selectedIndex].value == AddNewText) {
        newItem = prompt("Enter item to add:", "");
        if (newItem == null) {
            document.getElementById(ddlAddItem).selectedIndex = 0;
        }
        else if (newItem.length > MaxLength) {
            alert("Max length is " + MaxLength + " characters.");
            document.getElementById(ddlAddItem).selectedIndex = 0;
        }
        else if (newItem.length > 0) {
            var newIndex = -1;

            for (var i = 0; i < document.getElementById(ddlAddItem).options.length; i++) {
                // check if item already exists in the dropdown
                if (document.getElementById(ddlAddItem).options[i].text.toUpperCase() == newItem.toUpperCase()) {
                    // item exists so note down its index.
                    newIndex = i;
                }
            }

            if (newIndex == -1) {
                // item does not exist. so add new item
                document.getElementById(ddlAddItem).options[document.getElementById(ddlAddItem).options.length] = new Option(newItem, newItem);
                document.getElementById(ddlAddItem).selectedIndex = document.getElementById(ddlAddItem).options.length - 1;
            }
            else {
                document.getElementById(ddlAddItem).selectedIndex = newIndex;
            }
        }
        else {
            document.getElementById(ddlAddItem).selectedIndex = 0;
        }
    }
}

var searchString = '';
var searchTimer = -1;

function EditableDDLonKeyDown(ddlAddItem) {
    var i;
    var j;
    var eltOpt;
    var elt = event.srcElement;
    if (searchTimer != -1)
        clearTimeout(searchTimer);
    switch (event.keyCode) {
        case 8: searchString = searchString.substr(0, searchString.length - 1); event.keyCode = 0; break;
        default: searchString += unescape('%' + event.keyCode.toString(16));
    }

    j = elt.options.length;
    for (i = 0; i < j; i++) {
        eltOpt = elt.options(i);
        if (eltOpt.text.toUpperCase().substr(0, searchString.length) == searchString.toUpperCase()) {
            eltOpt.selected = true;
            break;
        }
    }
    searchTimer = setTimeout('clearSearchString();', 1000);
    event.returnValue = false;
}

function clearSearchString() {
    searchTimer = -1;
    searchString = '';
}

// URL Encode
function URLEncode(plaintext) {
    // The Javascript escape and unescape functions do not correspond
    // with what browsers actually do...
    var SAFECHARS = "0123456789" + 				// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()"; 				// RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";

    var encoded = "";
    for (var i = 0; i < plaintext.length; i++) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+"; 			// x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode > 255) {
                alert("Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted.");
                encoded += "+";
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    } // for

    return encoded;
};

function URLDecode(encoded) {
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var plaintext = "";
    var i = 0;
    while (i < encoded.length) {
        var ch = encoded.charAt(i);
        if (ch == "+") {
            plaintext += " ";
            i++;
        } else if (ch == "%") {
            if (i < (encoded.length - 2)
					&& HEXCHARS.indexOf(encoded.charAt(i + 1)) != -1
					&& HEXCHARS.indexOf(encoded.charAt(i + 2)) != -1) {
                plaintext += unescape(encoded.substr(i, 3));
                i += 3;
            } else {
                alert('Bad escape combination near ...' + encoded.substr(i));
                plaintext += "%[ERROR]";
                i++;
            }
        } else {
            plaintext += ch;
            i++;
        }
    } // while
    return plaintext;
};  

// Validation
function Page_CustomClientValidate(DisableRequiredField) {
    var i;
    for (i = 0; i < Page_Validators.length; i++) {

        if (DisableRequiredField == true)	// disable required field validators
        {
            if (Page_Validators[i].evaluationfunction != null && Page_Validators[i].evaluationfunction.toString().indexOf("RequiredFieldValidatorEvaluateIsValid") > -1) {
                ValidatorEnable(Page_Validators[i], !DisableRequiredField);
            }
            else	// its not RFV. So validate
            {
                ValidatorValidate(Page_Validators[i]);
            }
        }
        else	// validate
        {
            ValidatorEnable(Page_Validators[i], !DisableRequiredField);
            ValidatorValidate(Page_Validators[i]);
        }
    }
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit();
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
}

// Check or Uncheck all Checkboxes
function SetAllCheckBoxes(FormName, FieldName, CheckValue) {
    if (!document.forms[FormName])
        return;
    var objCheckBoxes = document.forms[FormName].elements[FieldName];
    if (!objCheckBoxes)
        return;
    var countCheckBoxes = objCheckBoxes.length;
    if (!countCheckBoxes)
        objCheckBoxes.checked = CheckValue;
    else
    // set the check value for all check boxes
        for (var i = 0; i < countCheckBoxes; i++)
        objCheckBoxes[i].checked = CheckValue;
}

var saveBgColor = null;

function HighLight(obj, hoverBgColor) {
    saveBgColor = obj.style.backgroundColor;

    if (hoverBgColor == null || hoverBgColor == '')
        hoverBgColor = '#DFDFDF'

    if (obj.style != null)
        obj.style.backgroundColor = hoverBgColor;
}

function LowLight(obj) {
    if (obj.style != null)
        obj.style.backgroundColor = saveBgColor;
}

function ValidateCheckBox(ctl1, ctl2, message) {
    var objCheckBox1 = MM_findObj(ctl1);
    var objCheckBox2 = MM_findObj(ctl2);

    if (objCheckBox1.checked == false && objCheckBox2.checked == false) {
        if (message == null || trim(message) == '')
            message = "Please make a selection";

        alert(message);
        return false;
    }

    return true;
}

// swap display & set text of div
function SwapDisplay(textareaControlID, divLabelControlID) {
    var objDivTextArea = MM_findObj("div_" + textareaControlID); // div containing comments textarea
    var objDivLabel = MM_findObj(divLabelControlID);  // div containing text label
    var objTextArea = MM_findObj(textareaControlID);    // textarea

    objDivTextArea.style.display = (objDivTextArea.style.display == 'none' ? 'block' : 'none');
    objDivLabel.style.display = (objDivTextArea.style.display == 'none' ? 'block' : 'none');

    objDivLabel.innerHTML = objTextArea.value;
}

function SetHiddenFieldValue(sourceControlID, targetControlID) {
    var objSourceHiddenField = MM_findObj(sourceControlID);
    var objTargetHiddenField = MM_findObj(targetControlID);

    if (objTargetHiddenField)
        objTargetHiddenField.value = objSourceHiddenField.innerHTML;
}

function checkall(checkname, thestate) {
    var el_collection = eval("document.forms[0]." + checkname);
    alert(el_collection.length);
    for (c = 0; c < el_collection.length; c++)
        el_collection[c].checked = thestate
}

String.prototype.endsWith = function(s) {
    var reg = new RegExp(s + "$");
    return reg.test(this);
}

function selectAllRadioButton(endingWithID, message) {
    var answer = 1;

    if (message != '')
        answer = confirm(message);

    if (answer == 1) {
        var numberForms = document.forms[0].length;
        var formIndex;
        var hiddenName;
        var labelName;
        var init = false;
        for (formIndex = 0; formIndex < numberForms; formIndex++) {
            var control = document.forms[0].elements[formIndex];
            var controlType = control.type;

            if (controlType == 'radio') {
                if (control.id.endsWith(endingWithID) == true) {
                    //Defined the hidden field name associated with the data row
                    hiddenName = control.id.replace(endingWithID, "hdOtherAnswer");
                    //Define the label name associated with the selected boat answer value
                    labelName = control.id.replace(endingWithID, "lblAnswer") + endingWithID.replace("rbVessel", "");
                    control.checked = true;
                    SetHiddenFieldValue(labelName, hiddenName)
                }
            }
        }
        return true;
    }
    return false;
}

function selectAllCheckbox(endingWithID, message) {
    var answer = 1;

    if (message != '')
        answer = confirm(message);

    if (answer == 1) {
        var numberForms = document.forms[0].length;
        var formIndex;
        var name;
        var init = false;
        var firstCheck = false;
        for (formIndex = 0; formIndex < numberForms; formIndex++) {
            var control = document.forms[0].elements[formIndex];
            var controlType = control.type;

            if (controlType == 'checkbox' && !control.disabled) {
                //check if first checkbox is checked (this adds 'uncheck' functionality)
                if (firstCheck == false) {
                    firstCheck = true;
                    init = !control.checked;
                }

                if (control.id.endsWith(endingWithID) == true) {
                    control.checked = init;
                    try {
                        control.onclick();
                    }
                    catch (err)
                    { }
                }
            }
        }
        return true;
    }
    return false;
}

function GoToReportDetail() {
    window.location = window.location.search.replace("tabid=415", "tabid=413");
}

function RedirectToUrl(url) {
    window.location.href = url;
}

function RedirectParentUrl(url) {
    window.opener.location.href = url;
    window.close();
}

function searchTextChange(obj) {
    var t;

    if (obj.value == "") {

        clearTimeout(t);
    }
    else {
        hidePopup();
        t = setTimeout('hidePopup()', 5);
    }

    if (window.event.keyCode == 13)
        getQ88(obj);
}

function hideIfEmpty(val) {
    if (val == "") {
        hidePopup();
        setTimeout('hidePopup()', 5);
    }
}

function IAmSelected(source, eventArgs) {
    EnableLoadingMsg(source, eventArgs);
    showQ88(eventArgs.get_value());
}
function DisableLoadingMsg(source, eventArgs) {
    var hfBypassLoadingMsg = document.getElementById("hfBypassLoadingMsg");
    if (hfBypassLoadingMsg != null) {
        hfBypassLoadingMsg.value = 'true';
    }
}
function EnableLoadingMsg(source, eventArgs) {
    var hfBypassLoadingMsg = document.getElementById("hfBypassLoadingMsg");
    if (hfBypassLoadingMsg != null) {
        hfBypassLoadingMsg.value = 'false';
    }
}

function getQ88(obj) {
    var imo = obj.value;
    if (imo == 'Enter name or IMO#') {
        alert('Enter name or IMO#');
        obj.focus();
    }
    else if (imo.length < 3) {
        alert('Enter at least 3 characters');
        obj.focus();
    }
    else {
        showQ88(imo);
    }
}

function showQ88(vessel) {
    var imo = vessel.toString();
    var quickSearchID = "";
    if (imo.lastIndexOf("(") == imo.length - 9) {
        imo = imo.substr(imo.lastIndexOf("(") + 1, 7);
    }
    // Find Control
    for (i = 1; i < document.forms[0].elements.length; i++) {
        field = document.forms[0].elements[i];
        if (field.value != "" && field.id.indexOf("txtQuickSearch") != -1) {
            quickSearchID = field.id;
            break;
        }
    }   
    document.getElementById(quickSearchID).value = vessel;
    document.getElementById('hfBypassLoadingMsg').value = 'false';
    DisplayLoading(false);

    if (window.location.host.indexOf("baltic") > 0) {
        document.location.href = '/Ships.aspx?v=result&s=' + imo;
    }
    else {
        var randNumber = randomString(8);
        document.location.href = '/Q88Search.aspx?v=result&s=' + imo + "&x=" + randNumber;
    }
}

function SetControlState(chkBox, txtBoxID, validatorID) {
    var txtBox = MM_findObj(txtBoxID);
    var validator = MM_findObj(validatorID);
    var enabled = chkBox.checked ? true : false;
    txtBox.disabled = !enabled;
    ValidatorEnable(validator, enabled);
}

//iterates a form and returns an object given the ID
function getObject(objectID) {
    var theObject
    for (i = 0; i < document.forms[0].elements.length; i++) {
        field = document.forms[0].elements[i];
        if (field.name.indexOf(objectID) != -1 || field.id.indexOf(objectID) != -1) {
            theObject = field;
        }
    }
    //alert(theObject);
    return theObject;
}

function SelectSubscription(btnID, subscriptionID) {//
    //alert('test');
    
    var CommonID = btnID.substring(0, btnID.lastIndexOf('_') + 1);
    var subNumber = btnID.substring(btnID.length - 1);
    
    var CallerBtn = document.getElementById(CommonID + "btnSubscription" + subNumber);   
    var alertResult = true;

    if (CallerBtn.id.lastIndexOf("btnSubscription1") > 0) {
        alert("You will NOT have access to view the Questionnaire 88's for any vessels under this subscription!");
    }
    
    if (alertResult) {
        (document.getElementById(CommonID + "btnSubscription1")).className = "LinkButton";
        (document.getElementById(CommonID + "btnSubscription2")).className = "LinkButton";
        (document.getElementById(CommonID + "btnSubscription3")).className = "LinkButton";
        CallerBtn.className = "LinkButtonClicked";

        document.getElementById(CommonID + 'txtSubscriptionType').value = subscriptionID;
        
        // show helper continue
        document.getElementById(CommonID + 'helperSubscriptionType').style.display = "none";
        document.getElementById(CommonID + 'helperContinue').style.display = "";
        return false;
    }
    // show helper continue
    document.getElementById(CommonID + 'helperSubscriptionType').style.display = "none";
    document.getElementById(CommonID + 'helperContinue').style.display = "";
    return false;
}

function DisableBillingAddressFields(sender) {
    var commonID = sender.id.substring(0, sender.id.lastIndexOf('_') + 1);
    var txtBillAddress = (document.getElementById(commonID + "txtBillAddress"));
    var txtBillAddress2 = (document.getElementById(commonID + "txtBillAddress2"));
    var txtBillCity = (document.getElementById(commonID + "txtBillCity"));
    var txtBillStateProvince = (document.getElementById(commonID + "txtBillProvince"));
    var txtBillPostalCode = (document.getElementById(commonID + "txtBillPostalCode"));
    var ddlBillCountry = (document.getElementById(commonID + "ddlBillCountry"));
    var chkSameAsCompany = (document.getElementById(commonID + "chkSameAsCompany"));

    //alert(chkSameAsCompany.checked);
    readOnlyMode = chkSameAsCompany.checked;
    var readOnlyMode = readOnlyMode;

    var cssName = "textDisabled";
    if (!readOnlyMode) {
        cssName = "InputField";
    }

    txtBillAddress.readOnly = readOnlyMode;
    txtBillAddress.className = cssName;
    txtBillAddress2.readOnly = readOnlyMode;
    txtBillAddress2.className = cssName;
    txtBillCity.readOnly = readOnlyMode;
    txtBillCity.className = cssName;
    txtBillStateProvince.readOnly = readOnlyMode;
    txtBillStateProvince.className = cssName;
    txtBillPostalCode.readOnly = readOnlyMode;
    txtBillPostalCode.className = cssName;
    ddlBillCountry.disabled = readOnlyMode;
    ddlBillCountry.className = cssName;
}

function MoveListBoxItemsToAnotherListBox(listBoxCtrlIDFrom, listBoxCtrlIDTo, hfFromID, hfToID, isAll) {
    listBoxCtrlFrom = document.getElementById(listBoxCtrlIDFrom);
    listBoxCtrlTo = document.getElementById(listBoxCtrlIDTo);
    hfFrom = document.getElementById(hfFromID);
    hfTo = document.getElementById(hfToID);

    for (i = 0; i < listBoxCtrlFrom.options.length; i++) {
        if (listBoxCtrlFrom.options[i].selected || isAll) {
            if (listBoxCtrlIDTo.indexOf("lbOutputOptionsSelected") > 0 && listBoxCtrlTo.options.length >= 10) {
                alert("A Maximum of 10 items can be added to the search output results.");
                i = 9999;
            }
            else {
                listBoxCtrlFrom.options[i].selected = false;
                try {
                    //listBoxCtrlTo.options.add(listBoxCtrlFrom.options[i]);
                    listBoxCtrlTo.options.add(new Option(listBoxCtrlFrom.options[i].text, listBoxCtrlFrom.options[i].value));
                }
                catch (e) {
                    listBoxCtrlTo.options.add(new Option(listBoxCtrlFrom.options[i].text, listBoxCtrlFrom.options[i].value), listBoxCtrlTo.options.length);
                }
                listBoxCtrlFrom.options[i] = null;
                i = i - 1;
            }
        }
    }

    hfTo.value = "";
    arrOptions = new Array(listBoxCtrlTo.options.length);
    for (i = 0; i < listBoxCtrlTo.options.length; i++) {
        hfTo.value += listBoxCtrlTo.options[i].value + "~" + listBoxCtrlTo.options[i].text + ";";
        hfFrom.value = hfFrom.value.replace(listBoxCtrlTo.options[i].value + "~" + listBoxCtrlTo.options[i].text + ";", "");
        arrOptions[i] = new Array(2)
        arrOptions[i][0] = listBoxCtrlTo.options[i].text;
        arrOptions[i][1] = listBoxCtrlTo.options[i].value;

    }
    //Do not sort selected columns
    if (listBoxCtrlIDTo.indexOf("lbOutputOptionsSelected") <= 0) {
        arrOptions.sort();
        for (i = 0; i < listBoxCtrlTo.options.length; i++) {
            listBoxCtrlTo.options[i].text = arrOptions[i][0];
            listBoxCtrlTo.options[i].value = arrOptions[i][1];
        }
    }


}



function ResetOptions(listBoxCtrl, listBoxCtrlFrom, hfFrom, hfTo, hfItemsID) {
    listBoxCtrl = (typeof listBoxCtrl == "string") ? document.getElementById(listBoxCtrl) : listBoxCtrl;
    hfItemsID = (typeof hfItemsID == "string") ? document.getElementById(hfItemsID) : hfItemsID;

    listBoxCtrlFrom = (typeof listBoxCtrlFrom == "string") ? document.getElementById(listBoxCtrlFrom) : listBoxCtrlFrom;
    hfFrom = (typeof hfFrom == "string") ? document.getElementById(hfFrom) : hfFrom;
    hfTo = (typeof hfTo == "string") ? document.getElementById(hfTo) : hfTo;
    //remove any changes
    while (listBoxCtrl.length > 0) {
        listBoxCtrl.remove(0);
    }
    //Repopulate list with original selections and remove items from the available list
    aBaseOptions = hfItemsID.value.split(";"); //Get list of value/text pairs
    for (i = 0; i < aBaseOptions.length; i++) {
        aBaseOption = aBaseOptions[i].split("~"); //0=text 1=value
        if (aBaseOption[0] != null && aBaseOption[1] != null) {
            listBoxCtrl.add(new Option(aBaseOption[1], aBaseOption[0]), i);
            for (j = 0; j < listBoxCtrlFrom.options.length; j++) {
                if (listBoxCtrlFrom.options[j].value === listBoxCtrl.options[i].value) {
                    listBoxCtrlFrom.remove(j); //Remove item from the available list
                }
            }
        }
    }
    //reset the hidden values
    hfTo.value = "";
    for (k = 0; k < listBoxCtrl.options.length; k++) {
        hfTo.value += listBoxCtrl.options[k].value + "~" + listBoxCtrl.options[k].text + ";";
        hfFrom.value = hfFrom.value.replace(listBoxCtrl.options[k].value + "~" + listBoxCtrl.options[k].text + ";", "");
    }

}


function MoveListBoxItemsUp(listBoxCtrl, hfItemsID) { /*updated from version 1.2*/
    obj = (typeof listBoxCtrl == "string") ? document.getElementById(listBoxCtrl) : listBoxCtrl;
    if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
        return false;
    var sel = new Array();
    for (var i = 0; i < obj.length; i++) {
        if (obj[i].selected == true) {
            sel[sel.length] = i;
        }
    }
    for (i in sel) {
        if (sel[i] != 0 && !obj[sel[i] - 1].selected) {
            var tmp = new Array((document.body.innerHTML ? obj[sel[i] - 1].innerHTML : obj[sel[i] - 1].text), obj[sel[i] - 1].value, obj[sel[i] - 1].style.color, obj[sel[i] - 1].style.backgroundColor, obj[sel[i] - 1].className, obj[sel[i] - 1].id);
            if (document.body.innerHTML) {
                obj[sel[i] - 1].innerHTML = obj[sel[i]].innerHTML;
            }
            else {
                obj[sel[i] - 1].text = obj[sel[i]].text;
            }
            obj[sel[i] - 1].value = obj[sel[i]].value;
            obj[sel[i] - 1].style.color = obj[sel[i]].style.color;
            obj[sel[i] - 1].style.backgroundColor = obj[sel[i]].style.backgroundColor;
            obj[sel[i] - 1].className = obj[sel[i]].className;
            obj[sel[i] - 1].id = obj[sel[i]].id;
            if (document.body.innerHTML) {
                obj[sel[i]].innerHTML = tmp[0];
            }
            else {
                obj[sel[i]].text = tmp[0];
            }
            obj[sel[i]].value = tmp[1];
            obj[sel[i]].style.color = tmp[2];
            obj[sel[i]].style.backgroundColor = tmp[3];
            obj[sel[i]].className = tmp[4];
            obj[sel[i]].id = tmp[5];
            obj[sel[i] - 1].selected = true;
            obj[sel[i]].selected = false;
        }
    }
    UpdateListBoxSelectedValues(obj, hfItemsID);
}

function MoveListBoxItemsDown(listBoxCtrl, hfItemsID) {
    obj = (typeof listBoxCtrl == "string") ? document.getElementById(listBoxCtrl) : listBoxCtrl;
    if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
        return false;
    var sel = new Array();
    for (var i = obj.length - 1; i > -1; i--) {
        if (obj[i].selected == true) {
            sel[sel.length] = i;
        }
    }
    for (i in sel) {
        if (sel[i] != obj.length - 1 && !obj[sel[i] + 1].selected) {
            var tmp = new Array((document.body.innerHTML ? obj[sel[i] + 1].innerHTML : obj[sel[i] + 1].text), obj[sel[i] + 1].value, obj[sel[i] + 1].style.color, obj[sel[i] + 1].style.backgroundColor, obj[sel[i] + 1].className, obj[sel[i] + 1].id);
            if (document.body.innerHTML) {
                obj[sel[i] + 1].innerHTML = obj[sel[i]].innerHTML;
            }
            else {
                obj[sel[i] + 1].text = obj[sel[i]].text;
            }
            obj[sel[i] + 1].value = obj[sel[i]].value;
            obj[sel[i] + 1].style.color = obj[sel[i]].style.color;
            obj[sel[i] + 1].style.backgroundColor = obj[sel[i]].style.backgroundColor;
            obj[sel[i] + 1].className = obj[sel[i]].className;
            obj[sel[i] + 1].id = obj[sel[i]].id;
            if (document.body.innerHTML) {
                obj[sel[i]].innerHTML = tmp[0];
            }
            else {
                obj[sel[i]].text = tmp[0];
            }
            obj[sel[i]].value = tmp[1];
            obj[sel[i]].style.color = tmp[2];
            obj[sel[i]].style.backgroundColor = tmp[3];
            obj[sel[i]].className = tmp[4];
            obj[sel[i]].id = tmp[5];
            obj[sel[i] + 1].selected = true;
            obj[sel[i]].selected = false;
        }
    }
    UpdateListBoxSelectedValues(obj, hfItemsID);
}
function UpdateListBoxSelectedValues(listBoxCtrl, hfItemsID) {
    hfSelectedValues = document.getElementById(hfItemsID);
    hfSelectedValues.value = "";
    var selectedValues = "";
    for (i = 0; i < listBoxCtrl.options.length; i++) {
        selectedValues = selectedValues + listBoxCtrl.options[i].value + "~" + listBoxCtrl.options[i].text + ";";
    }
    hfSelectedValues.value = selectedValues;

}
function MoveListBoxItemsDownUp(controlID, direction, hfItemsID) {
    listBoxCtrl = document.getElementById(controlID);
    hfSelectedValues = document.getElementById(hfItemsID);

    for (i = 0; i < listBoxCtrl.options.length; i++) {
        if (listBoxCtrl.options[i].selected) {
            textVal = listBoxCtrl.options[i].text;
            valueVal = listBoxCtrl.options[i].value;
            var newIndex = i - 1;
            if (direction == "down") {
                newIndex = i + 1;
            }
            if (
                    (i > 0 && direction == "up")
                    ||
                    (i < listBoxCtrl.options.length - 1 && direction == "down")
               ) {
                listBoxCtrl.remove(i);
                try {
                    listBoxCtrl.add(new Option(textVal, valueVal), listBoxCtrl.options[newIndex]);
                }
                catch (e) {
                    listBoxCtrl.add(new Option(textVal, valueVal), newIndex);
                }
                listBoxCtrl.options[newIndex].selected = true;
            }
            //i = 9999;
        }
    }

    hfSelectedValues.value = "";
    var selectedValues = "";
    for (i = 0; i < listBoxCtrl.options.length; i++) {
        selectedValues = selectedValues + listBoxCtrl.options[i].value + "~" + listBoxCtrl.options[i].text + ";";
    }
    hfSelectedValues.value = selectedValues;
}

function Downgrade() {
    var result = false;
    result = confirm('You will NOT have access to view the Questionnaire 88\'s for any vessels under this subscription!\nDo you wish to continue?')

    if (result) {
        var modalPopupBehavior = $find('ModalPnl');
        modalPopupBehavior.show();
    }

    return false;
}
function ShowHint(hint) {
    if (document.getElementById(hint).style.display != "inline") {
        document.getElementById(hint).style.display = "inline";
    }
    else {
        document.getElementById(hint).style.display = "none";
    }
}
function HideHint(hint) {
    document.getElementById(hint).style.display = "none";
}

function HasPageValidators() {  
    var hasValidators = false;  
    try {  
        if (Page_Validators.length > 0) {  
            hasValidators = true;  
        }  
    }  
    catch (error) { }    
    return hasValidators;
}

var loadingImagePostBackControl = null;
var inpostback = null;
function DisplayLoading(validatePage) {
    DisplayLoading(null, validatePage);
}
function DisplayLoading(ctrl, validatePage) {
    DisplayLoading(ctrl, validatePage, false)
}
function DisplayLoading(ctrl, validatePage, blockLoadingTimeout) {
    //alert('start displayloading');
    result = false;
    if (validatePage) {
        if ((HasPageValidators() == false || (HasPageValidators() == true && Page_ClientValidate()))) {
            onInvoke(null, blockLoadingTimeout);
            return true;
        }
        loadingImagePostBackControl = ctrl;
        result = true;
    }
    else if (!validatePage) {
        onInvoke(null, blockLoadingTimeout);
        result = true;
    }
    return result;
}

function randomString(stringLength) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i = 0; i < stringLength; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }
    return randomstring;
}

function qaCheckForErrors() {
    var errorFound = false;
    if (document.getElementById('ctl00_cphMiddle_ctl00_cpViewQuestionnaire_chkCompleteOffline').checked == true) {
        if (Page_CustomClientValidate(true) != true) {
            errorFound = true;
        }
    }
    else {
        if (Page_ClientValidate() == false) {
            errorFound = true;
        }
    }

    if (errorFound) {
        alert('Please review the questionnaire and correct the answers that have an error message.');
    }
    else {
        alert('No errors found.');
    }
    return false;
}

function addClickFunction(id) {
    var b = document.getElementById(id);
    if (b && typeof (b.click) == 'undefined') b.click = function() {
        var result = true; if (b.onclick) result = b.onclick();
        if (typeof (result) == 'undefined' || result) {
            eval(b.getAttribute('href'));
        }
    }
}

function ChangeClassVIAID(caller, newClass) {
    document.getElementById(caller).className = newClass;
}
function ChangeClassVIASender(caller, newClass) {
    caller.className = newClass;
}

function ChangeCSSRBLBlurCust(button, caller, normalCSS, changeCss) {
    var rbl = document.getElementById(caller);
    var selectedVal = false;
    if (button.checked)
        selectedVal = true;

    if (selectedVal) {
        rbl.className = changeCss;
    }
    else {
        rbl.className = normalCSS;
    }
}

function ChangeCSSCBLBlurCust(caller, normalCSS, changeCss) {
    var chkList = document.getElementById(caller);
    var options = chkList.getElementsByTagName('input');
    var selectedVal = false;
    //for (i = 0; i < options.length; i++) {
        //if (options[i].checked) {
            selectedVal = true;
        //}
    //}   
    
    if (selectedVal) {
        chkList.className = changeCss;
    }
    else {
        chkList.className = normalCSS;
    }
}

function isInteger(s) {
    var i;
    
    if (isEmpty(s)) {
        return false;
    }

    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (c!='-' && !isDigit(c)) { //allow negative and numeric fail everything else
            return false;
        }
    }

    return true;
}

function isEmpty(s) {
    return ((s == null) || (s.length == 0))
}

function isDigit(c) {
    return ((c >= "0") && (c <= "9"))
}


function ShowUDF(url) {
    var iframe = document.getElementById("ifUDF");
    var modalPopupBehavior = $find('mpeUDF');
  
    modalPopupBehavior.show();
    iframe.src = url;
}

function HideUDFModal() {
    var iframe = parent.document.getElementById("ifUDF");
    var modalPopupBehavior = parent.$find('mpeUDF');
    if (modalPopupBehavior != null) {
        modalPopupBehavior.hide();
        iframe.src = "/DesktopModules/Loading.aspx";
    }
}
function ShowModal(behaviorID, show) {
    var modalBehavior = $find(behaviorID);
    if (show) {
        modalBehavior.show();
    } else {
        modalBehavior.hide();
    }
}
function ProcessHttpRequest(url) {
    var sep = (-1 < url.indexOf("?")) ? "&" : "?"
    url = url + sep + "__=" + encodeURIComponent((new Date()).getTime()); // make url unique. prevents caching url
    var theHttpRequest = getNewHttpObject();
    theHttpRequest.open("GET", url, false);
    try {
        theHttpRequest.send(null);
    }
    catch (e) {
        return false;
    }
    if (theHttpRequest.status == 200) {
        return true;
    }
    else {
        return false;
    }
}
var curCalTxt;
var curCalPop;
function ShowCal(hlk, popupCalID, txtID, showTime, Options, dpdMonthClientID, dpdDayClientID, dpdYearClientID, ddlHourClientID, ddlMinuteClientID) {
    txt = document.getElementById(txtID);
    curCalTxt = txt;
    curCalPop = $find(popupCalID);
    var CommonID = dpdMonthClientID.substring(0, dpdMonthClientID.lastIndexOf('_') + 1);
    var timeSpan = document.getElementById(CommonID + "spanTimeCtrls");
    ddlMonth = document.getElementById(dpdMonthClientID);
    ddlDay = document.getElementById(dpdDayClientID);
    ddlYear = document.getElementById(dpdYearClientID);
    if (txt.value != null && txt.value.trim() != "") {        
        var date = new Date(txt.value);
        if (date == "NaN") { // Reset all drop downs
            ddlMonth.options[0].selected = true;
            ddlDay.options[0].selected = true;
            ddlYear.options[0].selected = true;
        }
        else { // Date Exists
            setSelectedIndex(ddlMonth, date.getUTCMonth() + 1);
            setSelectedIndex(ddlDay, date.getDate());
            setSelectedIndex(ddlYear, date.getUTCFullYear());
        } 
    }

    timeSpan.style.display = "none";
    if (showTime) {
        timeSpan.style.display = "";
    }    
    spanCalCustOptsCtrl = document.getElementById('spanCalCustOpts');
    spanCalCustOptsCtrl.style.display = "";    
    
    var rbl1 = document.getElementById(CommonID + "rbl1");
    var rbl2 = document.getElementById(CommonID + "rbl2");
    var rbl3 = document.getElementById(CommonID + "rbl3");
    var rbl4 = document.getElementById(CommonID + "rbl4");
    var rbl5 = document.getElementById(CommonID + "rbl5");
    rbl1.disabled = false;
    rbl2.disabled = false;
    rbl3.disabled = false;    
    rbl4.disabled = false;
    rbl5.disabled = false;
    if (Options == "0" || Options == "2") {
        spanCalCustOptsCtrl.style.display = "none";
    }
    else if (Options == "3") {
        rbl1.disabled = true;
        rbl2.disabled = true;
        rbl4.disabled = true;
    }
    if (Options == "4") {
        rbl1.disabled = true;
        rbl2.disabled = true;
        rbl4.disabled = true;
        rbl5.disabled = true;
    }
    rbl1.checked = false;
    rbl2.checked = false;
    rbl3.checked = false;
    rbl4.checked = false;
    rbl5.checked = false;
    if (txt.value == "None") { rbl1.checked = true; }
    if (txt.value == "Unknown") { rbl2.checked = true; }
    if (txt.value == "Not Applicable") { rbl3.checked = true; }
    if (txt.value == "Reverting") { rbl4.checked = true; }
    if (txt.value == "Permanent") { rbl5.checked = true; }
}

function setDateCUS(txt, pop, dateFormat, ddlMonthID, ddlDayID, ddlYearID, ddlHourID, ddlMinuteID) {
    var txtField = curCalTxt; //document.getElementById(txt);
    var popupBehavior = curCalPop;
    var ddlMonth = document.getElementById(ddlMonthID);
    var ddlDay = document.getElementById(ddlDayID);
    var ddlYear = document.getElementById(ddlYearID);
    var ddlHour = document.getElementById(ddlHourID);
    var ddlMinute = document.getElementById(ddlMinuteID);
    var CommonID = ddlMonthID.substring(0, ddlMonthID.lastIndexOf('_') + 1);
    var dateTime = "";
    timeSpan = document.getElementById(CommonID + "spanTimeCtrls");
    dateTime = ddlMonth.value + '/' + ddlDay.value + '/' + ddlYear.value;

    if (dateTime == "0/0/0") {
        txtField.value = "";
        txtField.focus();
        popupBehavior.hidePopup();
    }
    else {
        // Check date validity
        var isValid = /^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/.test(dateTime);
        if (!isValid) {
            alert('Invalid Date.\nPlease check your entry and try again.');
        }
        else {
            // Add Time (cannot be invalid b/c it is a drop down    
            if (timeSpan.style.display == "") {
                dateTime = dateTime + " " + ddlHour.value + ":" + ddlMinute.value;
                dateTime = new Date(dateTime).format(dateFormat + " HH:mm");
            }
            else {
                dateTime = new Date(dateTime).format(dateFormat);
            }
            // set text box value
            txtField.value = dateTime;
            txtField.focus();
            popupBehavior.hidePopup();
        }
    }
}

function CalDDLChanged(ddl) {
    var CommonID = ddl.id.substring(0, ddl.id.lastIndexOf('_') + 1);
    var selectedVal = ddl.value;
    var dpdMonth = document.getElementById(CommonID + "dpdMonth");
    var dpdDay = document.getElementById(CommonID + "dpdDay");
    var dpdYear = document.getElementById(CommonID + "dpdYear");
    if (ddl.value == "0") { // Set all drop downs to '-'
        dpdMonth.value = "0";
        dpdDay.value = "0";
        dpdYear.value = "0";
    }
    else if(dpdMonth.value == "0" || dpdDay.value == "0" || dpdYear.value == "0")
    { // Set all drop downs to first available value (only do this when the original value was '-'
        dpdMonth.options[1].selected = true;
        dpdDay.options[1].selected = true;
        dpdYear.options[11].selected = true; // Set to this year
        ddl.value = selectedVal; // reselect originally selected value
    }
}

function CalCustOption(rbl, popBhID) {
    curCalTxt.value = rbl.attributes.getNamedItem("TextValue").value;
    rbl.checked = false;
    curCalTxt.focus();
    var popupBehavior = curCalPop;
    popupBehavior.hidePopup();
}

function setSelectedIndex(s, v) {
    for (var i = 0; i < s.options.length; i++) {
        if (s.options[i].value == v) {
            s.options[i].selected = true;
            return;
        }
    }
}

// Combobox js ComponentArt
function cbColumnOptions_collapse(sender, e) {
    // avoid recursion on collapsing
    if (isCollapsing) {
        isCollapsing = false;
        return;
    }
    // allow blank
    if (sender.get_text() == "") {
        return;
    }
    var i = 0;
    while (sender.getItem(i)) {
        if (sender.get_text() == sender.getItem(i).get_text()) {
            lastText = sender.get_text();
            return;
        }
        i++;
    }
    var oldExpandDuration = sender.ExpandDuration;
    var oldCollapseDuration = sender.CollapseDuration;
    sender.ExpandDuration = 0;
    sender.CollapseDuration = 0;
    sender.set_text("");

    // setting the text will cause an expand, so collapse it here
    isCollapsing = true;
    sender.collapse();
    sender.ExpandDuration = oldExpandDuration;
    sender.CollapseDuration = oldCollapseDuration;
}

function LimitTextLength(obj, mlength) {

    if (obj.getAttribute && obj.value.length > (mlength)) {
        obj.value = obj.value.substring(0, (mlength));
        alert('The value you entered exceeds the maximum length of ' + mlength + ' characters. Only the first ' + mlength + ' characters have been retained');
        
    }
}

function ClickMe(buttonID) {
    ASPButton = document.getElementById(buttonID);
    try {
        ASPButton.click();
    }
    catch (err) {
        window.location.href = ASPButton.href;
    }
}

function checkAllNone(objectID, checked) {
    for (i = 0; i < document.forms[0].elements.length; i++) {
        field = document.forms[0].elements[i];
        if (field.id.indexOf(objectID) != -1) {
            field.checked = checked;
        }
    }
}

function showAlert(initialLoad, val, hfID) {
    var hfCtrl = document.getElementById(hfID);
    popupBehavior = $find('pceAB')
    if ((initialLoad && hfCtrl.value == "false") || !initialLoad) {
        hfCtrl.value = "true";
        if (popupBehavior != null) {
            if (val) { popupBehavior.showPopup(); }
            else { popupBehavior.hidePopup(); }
        }
    }
}
// *** These two functions allow the clicking of a checkbox within a div ***
    workingCheckBoxInDiv = false;
    function CheckCheckBoxInDiv(divID, checkBoxID) {
        if (workingCheckBoxInDiv == false) {
            var CommonID = divID.substring(0, divID.lastIndexOf('_') + 1);
            var cb = document.getElementById(CommonID + checkBoxID);
            cb.checked = !cb.checked;
        }
        workingCheckBoxInDiv = false;
    }
    function CheckCheckBoxInDivCheckBox() {
        workingCheckBoxInDiv = true;
    }

function RoundValue(value, decimalPercision) {
    if (decimalPercision == 0) {
        return Math.round(value);
    }
    else {
        return Math.round(value * 10 * decimalPercision) / (10 * decimalPercision);
    }
}
function GetCommonID(id) {
    return id.substring(0, id.lastIndexOf('_') + 1);
}

// checks if a date is today or earlier
//********************************************************************************************************************************
function ValDatePast(source, args) {
    var dtToday = new Date();
    var dtEnteredDate = (document.getElementById(source.controltovalidate)).value;
    if (Date.parse(dtEnteredDate) > Date.parse(dtToday)) {
        args.IsValid = false;
    }
    else {
        args.IsValid = true;
    }
}
// checks if a date is today or later
//********************************************************************************************************************************
function ValDateFuture(source, args) {
    var dtToday = new Date();
    var dtEnteredDate = (document.getElementById(source.controltovalidate)).value;
    if (Date.parse(dtEnteredDate) < Date.parse(dtToday)) {
        args.IsValid = false;
    }
    else {
        args.IsValid = true;
    }
}
//Checks for at least one checkbox in an checkbox list being checked
//*******************************************************************
function checkboxListValidation(objectID, message) {
    isValid = false;
    for (i = 0; i < document.forms[0].elements.length; i++) {
        field = document.forms[0].elements[i];
        if (field.id.indexOf(objectID) != -1) {
            if (field.checked) {
                isValid = true;
            }
        }
    }
    if (!isValid) {
        alert(message);
    }
    return isValid;
}