﻿//this is nessacery for the infragistics grid to for in firefox3.6 as with out it you cant use the row click event
if (!document.getBoxObjectFor) {
    document.getBoxObjectFor = function (el) {
        if (!(el instanceof HTMLElement)) {
            return;
        } //else:
        var b = el.getBoundingClientRect(), p = el, x = sx = b.left - el.offsetLeft, y = sy = b.top - el.offsetTop, w = window;
        while (!(p instanceof HTMLHtmlElement)) {
            sx += p.scrollLeft;
            sy += p.scrollTop;
            p = p.parentNode;
        }
        return { x: sx, y: sy, width: Math.round(b.width), height: Math.round(b.height),
            element: el, firstChild: el, lastChild: el, previousSibling: null, nextSibling: null, parentBox: el.parentNode,
            screenX: x + w.screenX + (w.outerWidth - w.innerWidth) / 2, screenY: y + w.screenY + (w.outerHeight - w.innerHeight) / 2
        };
    };
}

function Alert(ErrMess) {

    alert(ErrMess);
}

function SetLocCon(Ctrl, Enable_It, ReadOnly, BGround, FGround, Height, Width) {

    //for height and width we must the through the desired size but remember to take into account the padding and widths
    // of borders also the unit of mesurement i.e. 350px of 30em
    //lets enable it

    //Standard height for a text box seems to be 22px, but after everything else is taken off
    // padding and border width it is 15 same goes for the width you need to add two px
    if (Height == "") {

        Height = "15px";
    }
    if (ReadOnly == "Y") {

        Ctrl.setAttribute("readOnly", "true");

    } else if (ReadOnly == "N") {

        Ctrl.removeAttribute("readOnly");
    }

    if (Enable_It == "Y") {

        Ctrl.disabled = false;

        // lets disable it
    } else if (Enable_It == "N") {

        Ctrl.disabled = true;

        // lets set its display to none
    } else if (Enable_It == "I") {

        Ctrl.style.display = 'none';

        // lets set its display to block
    } else if (Enable_It == "V") {

        Ctrl.style.display = 'block';
    }


    if (BGround == "W") {
        Ctrl.style.backgroundColor = "white";

    } else if (BGround == "G") {

        Ctrl.style.backgroundColor = "grey";

    } else if (BGround == "LG") {

        Ctrl.style.backgroundColor = "#E1E1E1";

    } else if (BGround == "L") {

        Ctrl.style.backgroundColor = "grey";
    }

    if (FGround == "B") {
        Ctrl.style.color = "black";

    } else if (FGround == "R") {

        Ctrl.style.color = "red";


    } else if (FGround == "LG") {

        Ctrl.style.color = "#E1E1E1";

    } else if (FGround == "B") {

        Ctrl.style.color = "#33CCFF";
    }

    //lets set change the size properties to what they should be
    Ctrl.style.border = "1px solid #7f9db9";
    Ctrl.style.width = Width;
    Ctrl.style.height = Height;
}

//---------------------------------------------------------POSTCODE SOFTWARE ADDIN----------------------------------------------------------------
var OLD_PostCode = "";
var PostCodeFound = "";

function SetUpRefreshButton() {
    var Refresh = document.getElementById("cmdRefresh");

    Refresh.setAttribute('src', '/images/final/TCL_Refresh.gif'); //Live version
    //Refresh.setAttribute('src', '/QE_BUA/images/final/TCL_Refresh.gif');
    Refresh.setAttribute('float', 'right');
    Refresh.setAttribute('display', 'none');
    Refresh.onclick = new Function("RefreshAddress();");
}

function RefreshAddress() {
    //right lets refresh the address, firstly we will need to set the oldpostcode to ""
    OLD_PostCode = "";

    Get_Address(document.getElementById("txtPostcode").value)

}



function SavePostCodeOnLoad() {
    SavePostCode(document.getElementById("txtPostcode").value);
    PostCodeFound = true;
}


function Get_Address(PostCode) {


    if (OLD_PostCode == PostCode) {
        return false;
    }

    //lets disable the button
    DisableNavButton('cmd_Find_Address');

    //Lets go off and get the address if there is one
    fncDoAjax("QE_BUA/Ajax_PostCodes.aspx?", "WhatToDo=GetAddress&PostCode=" + PostCode, false, null, null, null, null, null, Was_PostCode_Found)

}

function MT_R_Address() {
    var Building = document.getElementById("txtProperty");
    var Street = document.getElementById("txtStreet");
    var Locality = document.getElementById("txtLocality");
    var Town = document.getElementById("txtTown");
    var County = document.getElementById("txtCounty");

    Building.value = "";
    Street.value = "";
    Locality.value = "";
    Town.value = "";
    County.value = "";
}

function Was_PostCode_Found(data) {
    var ErrMess = "ERROR !!!\n\n";
    var arrData = data.split("!^*");

    //was it found or valid?
    if (arrData[0] != 'True') {
        //Lets tell them and display and alert of some sorts
        ErrMess = ErrMess = "Invalid Postcode.";
        Alert(ErrMess);
        MT_R_Address();
        //lets loc the controls again
        SetLocCon(document.getElementById("txtStreet"), "Y", "Y","LG", "B", "", "252px")
        SetLocCon(document.getElementById("txtProperty"), "Y", "Y", "LG", "B", "", "252px")

        PostCodeFound = false;

        return false
    }
    //Is this postcode enabled for web use ?
    if (arrData[1] == 'True') {

        //Lets tell them and display and alert of some sorts

        ErrMess = ErrMess = "Invalid Postcode.\n\nPlease contact BEECH.";
        Alert(ErrMess);
        MT_R_Address();
        SetLocCon(document.getElementById("txtStreet"), "Y", "Y", "LG", "B", "", "252px")
        SetLocCon(document.getElementById("txtProperty"), "Y", "Y", "LG", "B", "", "252px")

        PostCodeFound = false;

        return false
    }

    //Is this postcode active ?
    if (arrData[2] == 'True') {

        //Lets tell them and display and alert of some sorts
        ErrMess = ErrMess = "Invalid Postcode.\n\nPlease contact BEECH.";
        Alert(ErrMess);
        MT_R_Address();
        SetLocCon(document.getElementById("txtStreet"), "Y", "Y", "LG", "B", "", "252px")
        SetLocCon(document.getElementById("txtProperty"), "Y", "Y", "LG", "B", "", "252px")

        PostCodeFound = false;
        
        return false
    }

    //it was so lets go do the other bits
    Populate_Address(data);
}

function Populate_Address(data) {
    var arrData = data.split("!^*")

    var Building = document.getElementById("txtProperty");
    var Street = document.getElementById("txtStreet");
    var Locality = document.getElementById("txtLocality");
    var Town = document.getElementById("txtTown");
    var County = document.getElementById("txtCounty");
    var PostCode = document.getElementById("txtPostcode");

    Building.value = arrData[3];
    Street.value = arrData[4];
    Locality.value = arrData[5];
    Town.value = arrData[6];
    County.value = arrData[7];
    PostCode.value = arrData[8];

    SetLocCon(Building, "Y", "N", "W", "B", "", "252px")
    SetLocCon(Street, "Y", "N", "W", "B", "", "252px")

    SetMandatory(Building);

    PostCodeFound = true;

    SavePostCode(PostCode.value);

   }




function ValidatePostcode() {
    var PostCode = document.getElementById("txtPostcode").value;

    var Building = document.getElementById("txtProperty");
    var Street = document.getElementById("txtStreet");
    var Locality = document.getElementById("txtLocality");
    var Town = document.getElementById("txtTown");
    var County = document.getElementById("txtCounty");

    var Refresh = document.getElementById("cmdRefresh");

    //Lets see if it is blank
    //if its a valid postcode lets enable the find button
    if (PostCode == "") { //!Is_Postcode_Valid(PostCode) Dont need to validate it on the web

        MT_R_Address();

        //Theres no postcode so lets lock all the other fields up
        SetLocCon(Building, "Y", "Y", "LG", "B", "", "252px")
        SetLocCon(Street, "Y", "Y", "LG", "B", "", "252px")

       DisableNavButton('cmd_Find_Address')
        //let enable it
    } else {

        EnableNavButton('cmd_Find_Address', "Get_Address(document.getElementById('txtPostcode').value);")
    }
}

function SavePostCode(PostCode) {
    //Lets save the old postcode
    OLD_PostCode = PostCode;
}

function Is_Postcode_Valid(PostCode) {
    //Function to check that the postcode entered is in the correct format
    //    AN NAA
    //    ANN NAA
    //    AAN NAA
    //    AANN NAA
    //    ANA NAA
    //    AANA NAA
    var I = 0;
    var Test_Char = "";
    var Test_String = "";
    var ValidChars = "0123456789";
    var Valid = false;
    //lets go through each character
    for (I = 0; I < PostCode.length; I++) {
        Test_Char = PostCode.substr(I, 1);

        //lets see if it is the space
        if (Test_Char == ' ') {
            Test_String = Test_String + ' '
            //is the current character a number?
        } else if (ValidChars.indexOf(Test_Char) == -1) {
            Test_String = Test_String + "A"
        } else {
            Test_String = Test_String + "N"
        }
    }
    //Lets see if it is in the correct format
    if (Test_String == "AN NAA" || Test_String == "ANN NAA" || Test_String == "AAN NAA" || Test_String == "AANN NAA" 
        || Test_String == "ANA NAA" || Test_String == "AANA NAA") {
        //It matches our valid form
        Valid = true;
    }

    return Valid;
}



var RB_NO_VALUE = 0;
var RB_YES = 1;
var RB_NO = 2;
var FIELD_HIGHLIGHT_COLOUR = "White";
var LISTBOX_HEIGHT = '11px';
//the below is for getting focus in firefox... see www.webdeveloper.com/forum/archive/index.php/t-80404.html
var CheckEI = null;

function fncNavButtonClickedcm() {

    document.getElementById('navBack').style.backgroundImage = "url(../../images/final/yellow_buttonclicked_bg.jpg)";
    document.getElementById('navForward').style.backgroundImage = "url(../../images/final/yellow_buttonclicked_bg.jpg)";
}
// this will open the print in a new window so that when a users closes it it will return them to the summary screen rather than the quote registry
function fncOpenHelpWin(page_name, field_name) {
    var width = 450;
    var height = 300;
    var left = (screen.width - width) / 2;
    var top = (screen.height - height) / 2;
    var params = 'width=' + width + ', height=' + height;
    params += ', top=' + top + ', left=' + left;
    params += ', directories=no';
    params += ', location=no';
    params += ', menubar=no';
    params += ', resizable=no';
    params += ', scrollbars=yes';
    params += ', status=no';
    params += ', toolbar=no';
    newwin = window.open('../../helpPage.aspx?page_name=' + page_name, 'HelpWindow', params);


    if (window.focus) { newwin.focus() }

}




function fncSetTestValues(formname) {

    var elem = document.getElementById(formname).elements;

    //        str += "<b>Type:</b>" + elem[i].type + "&nbsp&nbsp";
    //        str += "<b>Name:</b>" + elem[i].name + "&nbsp;&nbsp;";
    //        str += "<b>Value:</b><i>" + elem[i].value + "</i>&nbsp;&nbsp;";
    //        str += "<BR>";
    //    
    //    document.write(str)


    var int = 1
    alert(elem.length + " fields populated")
    for (var i = 0; i < elem.length; i++) {
        switch (elem[i].type) {
            case "text":
            case "textarea":
            case "password":
                if (elem[i].id == 'txtPostcode') {
                    elem[i].value = 'S44 1AA'
                }
                else {
                    elem[i].value = int
                    int++
                } // eof if

                break;
            case "radio":
                fncClearRadio(elem[i].name)
                eval("var choice = document.forms[0]." + elem[i].name)
                choice[0].checked = true
                break;
            case "select-one":
                if (elem[i].options.length > 1) {
                    elem[i].selectedIndex = 1
                }
                else {
                    elem[i].selectedIndex = 0
                } // eof if
                break;

        } // eof switch
    } // eof for

} // eof function


function fncDomContDis() {

    //this function will ensure that a broker can only give domestic contents  insurance if the proposer lives on the premises
    lopNo = document.getElementById("lopNo")
    txtDomContents = document.getElementById("txtDomContents")

    if (lopNo.checked == true) {
        //txtDomContents.style.
        txtDomContents.disabled = true;
        txtDomContents.style.background = 'white';
        txtDomContents.style.border = '1px solid #c9c7ba';
        txtDomContents.style.height = '15px'
        txtDomContents.style.width = '98px'
        txtDomContents.value = ''

    } else {

        txtDomContents.disabled = false;
        txtDomContents.style.background = 'white';
        txtDomContents.style.border = '1px solid #7f9db9';
        txtDomContents.style.height = '15px'
        txtDomContents.style.width = '98px'
    } //eof if
} //eof 



var visDiv = "divSOFCont" //the div that is currently visible
function fncStatNavWizard(scheme, button) {
    var navBack = document.getElementById("navBack")
    var navForward = document.getElementById("navForward")
    var direction = ""
    button.id == "navBack" ? direction = "back" : direction = "forward"
    switch (scheme) {
        case "package":
            switch (visDiv) {
                case "divSOFCont":
                    if (direction == "forward") {
                        if (fncValidate()) { // only move direction if validation passed
                            navBack.style.display = "block"
                            visDiv = "divPropDetailsCont"

                            fncWizardNav("divPropDetailsCont", 2, "novalidate")
                        } // eof if
                    } // eof if
                    break

                case "divPropDetailsCont":
                    if (direction == "forward") {
                        if (fncValidate()) { // only move direction if validation passed
                            visDiv = "divTypesOfTradeCont"
                            fncWizardNav("divTypesOfTradeCont", 3, "novalidate")
                        } // eof if
                    }
                    else {// direction must be backwards - no validation going backwards
                        navBack.style.display = "none"
                        visDiv = "divSOFCont"
                        fncWizardNav("divSOFCont", 1, "novalidate")
                        navBack.style.display = 'none'
                    } // eof if
                    break

                case "divTypesOfTradeCont":
                    // if (direction == "forward") {
                    //   if (fncValidate()) { // only move direction if validation passed
                    //  visDiv = "divLossHistoryCont"
                    //  fncWizardNav("divLossHistoryCont", 4, "novalidate")
                    //   } // eof if
                    //  }
                    //  else {// direction must be backwards - no validation going backwards
                    //    visDiv = "divPropDetailsCont"
                    //   fncWizardNav("divPropDetailsCont", 2, "novalidate")
                    // } // eof if
                    // break

                    //  case "divLossHistoryCont":
                    if (direction == "forward") {
                        if (fncValidate()) { // only move direction if validation passed
                            visDiv = "divSOSICont"
                            fncWizardNav("divSOSICont", 5, "novalidate");
                            fncDomContDis();
                        } // eof if
                    }
                    else {// direction must be backwards - no validation going backwards
                        visDiv = "divPropDetailsCont"
                        fncWizardNav("divPropDetailsCont", 3, "novalidate")
                    } // eof if
                    break
                case "divSOSICont":
                    if (direction == "forward") {
                        if (fncValidate()) { // only move direction if validation passed
                            visDiv = "divMoneyCont"
                            fncWizardNav("divMoneyCont", 6, "novalidate")
                            navForward.innerHTML = "Proceed to Quote"
                        } // eof if
                    }
                    else {// direction must be backwards - no validation going backwards
                        visDiv = "divTypesOfTradeCont"
                        fncWizardNav("divTypesOfTradeCont", 4, "novalidate")
                    } // eof if
                    break

                case "divMoneyCont":
                    if (direction == "forward") {
                        if (fncValidate()) { // only move direction if validation passed
                            fncWizardNav("divSummaryCont", 7, "novalidate", true)
                            navBack.style.display = "none"
                            navForward.style.display = "none"

                        } // eof if
                    }
                    else {// direction must be backwards - no validation going backwards
                        navForward.innerHTML = "Forward"
                        visDiv = "divSOSICont"
                        fncWizardNav("divSOSICont", 5, "novalidate")
                    } // eof if
                    break

            } // eof switch
            break
        case "treatment":

            break
    } // eof switch

} // eof function



function fncWizardNav(divToShow, progIndex, validate, submitForm) {
    /*  10.01.09 - Mark Mirfin
    divToShow = the container div on the form to show - all other container divs (identified by 
    attribute divType="leg") will be hidden 
    progToColor = the cell in the progress bar coressponding to this leg to colour in
    */

    //clear all arrSpans of the validation error class  'warningMessageText'
    var arrSpans = document.getElementsByTagName("span")
    for (var x = 0; x < arrSpans.length; x++) {
        if (arrSpans[x].className == 'warningMessageText') { arrSpans[x].className = '' }
    } // eof for

    // check any validation rules
    if (validate != 'novalidate') { // only 'forward' steps are validated
        if (!fncValidate()) { return false } // if we fail validation don't go to next step
    } // eof if

    // see if we are submitting the form, if so do it now as there is no point doing anything beyond this
    if (submitForm) { document.getElementById("form1").submit() }

    var divToShow = document.getElementById(divToShow)
    var progToColor = document.getElementById(progToColor)
    var tblProg = document.getElementById("tblProg")

    // get all the divs on the page with the attribute divType="leg"
    var arrDivs = document.getElementsByTagName("div")
    // hide all the divs with attribute:value = divType="leg"
    for (x = 0; x < arrDivs.length; x++) {
        if (arrDivs[x].getAttribute("divType") == "leg") {
            arrDivs[x].style.display = "none"
        } // eof if
    } // eof for

    //show the divToShow
    divToShow.style.display = "block"

    // colour in the progToColor

    //  var arrCells = tblProg.getElementsByTagName("td")
    //remove colour from all prog cells
    // for (var x = 0; x < arrCells.length; x++) {
    //     arrCells[x].className = "progNotSelected"
    // } // eof for

    //colour all prog cells up to and including this prog cell
    //  for (var x = 0; x < progIndex; x++) {
    //      arrCells[x].className = "progSelected"
    //  } // eof for

    //progToColor.className = "progSelected"    
} // eof function



function fncGetPos(elem) {
    pos = [elem.offsetLeft, elem.offsetTop];
    parentNode = elem.offsetParent;
    if (parentNode != elem) {
        while (parentNode) {
            pos[0] += parentNode.offsetLeft;
            pos[1] += parentNode.offsetTop;
            parentNode = parentNode.offsetParent;
        }
    }
    return pos
} // eof function

function fncFixNLSpace(thebox) {
    //prevents only carriage returns/line feeds being entered in multiline text boxes
    var theString = thebox.value
    theString = theString.replace(/(\r|\n)/g, "") //line spaces
    //theString = theString.replace(/\s/g, "^") //spaces
    if (theString.length == 0) { thebox.value = theString }
} // eof function

var task, quoteSeq, timestamp, qs, pr, qn, cr, ta, sc, sproc, se, spe, sef, scheme // sef = scheme entry form

sc = '<%=session("SchemeCode")%>'
sproc = '<%=session("ProceedToQuoteProc")%>'
se = '<%=session("SupportEntertainment")%>'
spe = '<%=session("SupportPlayEquipment")%>'
sef = '<%=session("SchemeEntryForm")%>'

function fncQuoteStatus(data) {

    var arrData = data.split("^")
    if (arrData.length == 1) {
        alert("There was an error retrieving the data for this quote.\nThe quote registry will now be refreshed.")
        location.href = location.href
        return false
    } // eof if
    var quote_changed = arrData[0]
    var allow_update = arrData[1]
    var allow_hold_cover = arrData[2]
    var allow_ntu = arrData[3]
    var allow_display = arrData[4]
    var allow_update_no_text = arrData[5]
    var allow_cover_no_text = arrData[6]
    var allow_ntu_no_text = arrData[7]
    var allow_display_no_text = arrData[8]

    if (allow_display != 'True') {
        alert(allow_display_no_text)

        location.href = location.href
    } // eof if
    // when quote registry has been changed and then update is clicked 2 and 3 appear

    if (quote_changed == 'True') {
        alert(allow_display_no_text)
        // alert("2")
        location.href = location.href
    } // eof if
    switch (task) {
        case "tbPrint":
            Printquote = dhtmlmodal.open("Printquote", "iframe", "../printQuote/previewPrintQuote.aspx?qs=" + qs + "&qn=" + qn + "&cr=", "Print Quote: " + qn, "width=900,height=620px,center=1,resize=0,scrolling=0")

            break

        case "tbSummary":
            viewSummary = dhtmlmodal.open("viewSummary", "iframe", "viewQuoteSummary.aspx?qs=" + qs, "Quote Summary: " + qn, "width=950,height=670px,center=1,resize=0,scrolling=0", "")
            return true
            break
        case "tbUpdate":

            if (allow_update == 'True') {
                //if (sef == 'TREATMENT') {
                var href = "quoteUpdater.aspx?qs=" + qs + "&sc="
                //}
                // else {
                //  var href = "/schemes/" +sef+ "/1.aspx?scheme=" + scheme + "&sproc=" + sproc + "&scheme_code=" + sc + "&se=" + se + "&spe=" + spe + "&qs=" + qs

                // }// eof if
                WinQuoteEntry = dhtmlmodal.open("WinQuoteEntry", "iframe", href, "Update Quote: " + qn, "width=950px,height=670px,center=1,resize=0,scrolling=0", "")
            }
            else {

                //alert(allow_update_no_text)
                //alert("3")
                return false
            } // eof if
            break
        case "tbHold":


            if (allow_hold_cover == 'True') {
                holdCover = dhtmlmodal.open("holdCover", "iframe", "holdCover.aspx?qs=" + qs + "&pr=" + pr + "&qn=" + qn, "Hold Cover :  " + qn, "width=820,height=510px,center=1,resize=0,scrolling=0", "")

            }
            else {
                // alert(allow_cover_no_text)

                return false

            } // eof if
            break
        case "tbNTU":
            if (allow_ntu == 'True') {
                NTUQuote = dhtmlmodal.open("NTUQuote", "iframe", "../QE_BUA/ntu_reason.aspx?qs=" + qs + "&pr=" + escape(pr) + "&qn=" + qn + "&ta=" + escape(ta), "Quote Not Taken Up: " + qn, "width=420px,height=320px,center=1,resize=0,scrolling=0", "")
            }
            else {
                //alert(allow_ntu_no_text)
                return false
            } // eof if
            break
        case "tbEmail":

            emailquote = dhtmlmodal.open("emailquote", "iframe", "../QE_BUA/emailQuote.aspx?qs=" + qs + "&qn=" + qn + "&cr=" + cr, "E-Mail Quote: " + qn, "width=525,height=325px,center=1,resize=0,scrolling=0")

            // var emailQuote = dhtmlmodal.open("emailQuote", "iframe", "../QE_BUA/emailQuote.aspx?qs=" + qs + "&qn=" + qn + "&cr=" + cr, "Email Quote: " + qn, "width=515px,height=320px,center=1,resize=0,scrolling=0", "")
            break

    } // eof switch

} // eo function

function fncOpenWin(url, name, w, h) {
    //        // Fudge factors for window decoration space.
    //        // In my tests these work well on all platforms & browsers.
    //       // if (screen.width < 1024 || screen.height < 764) {
    //           // alert("Error. Cannot start this application.\n\nThis application requires a minimum screen resolution of 1024 pixels by 768 pixels.\nIt appears that your screen resolution is " + screen.width + " pixels by " + screen.height + " pixels.\nPlease contact your technical support department.")
    //           // return false
    //        // } // eof if
    //        var appName = navigator.appName;
    //        var ie = (appName.indexOf('Microsoft Internet Explorer') != -1);
    //        var ff = (appName.indexOf('Netscape') != -1);
    //        alert(appName);
    //        if ((ff) && (screen.width <= 1024 || screen.height <= 768))
    //        
    //        
    //        //newwindow = window.open('http://www.yahoo.com', 'main', 'height=' + screen.height + ',width=' + screen.width + ',screenx=0,screeny=0,left=0,top=0,resizable=no');


    var appName = navigator.appName;

    var ie = (appName.indexOf('Microsoft Internet Explorer') != -1);
    var ff = (appName.indexOf('Netscape') != -1);

    if ((ff) && (screen.width <= 1024 || screen.height <= 768)) {

        //change these depending which site you are on be it the live beech site or one of the test sites
        newwindow = window.open("../login.aspx", "main", "Height=768,Width=1024,left=0,top=0,location=no, menubar=no, status=no,titlebar=no, toolbar=no, scrollbars=yes");
    } else {
        if (screen.width <= 1024 || screen.height <= 768) {
            //change these depending which site you are on be it the live beech site or one of the test sites
            var win = window.open("../login.aspx", "", "fullscreen=yes,scrollbars=auto")

            win.focus();

            window.open('', '_self', '');

            window.close();

            return false
        }
        else
            w += 32;
        h += 96;
        wleft = (screen.width - w) / 2;
        wtop = (screen.height - h) / 2;
        // IE5 and other old browsers might allow a window that is
        // partially offscreen or wider than the screen. Fix that.
        // (Newer browsers fix this for us, but let's be thorough.)
        if (wleft < 0) {
            w = screen.width;
            wleft = 0;
        }
        if (wtop < 0) {
            h = screen.height;
            wtop = 0;
        }
        var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=0, menubar=0, ' +
    'status=0, toolbar=0, scrollbars=0,navigation=0,titlebar=0, resizable=1');
        // Just in case width and height are ignored
        win.resizeTo(w, h);
        // Just in case left and top are ignored
        win.moveTo(wleft, wtop);
        win.focus();

        window.open('', '_self', '');

        window.close();
    }
} // eof function  

//CE 2009-08-05  Add CSS Rule, allowing for the change of page formatting on the fly (i.e. as the page loads)
// The stysheet is the relative path to the stylesheet, the selector is the element or class to change,
// and attributes are a list of attributes to assign to the element or class, in a format like "attribute1:value1;
// attribute2:value2;"
function fncAddCSSRule(stysheet, selector, attributes) {
    //Below variable finds which element of the document.styleSheets array points to the css file passed above
    var cssindex = -1;
    var i;
    //Iterate through stylesheets, looking for the one with the href passed.  href is relative
    for (i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].href == stysheet) {
            cssindex = i;
        }
    }

    //if we haven't found it, cssindex will not change from the initialised value
    if (cssindex == -1) {
        //Therefore return false
        return false;  //TODO: insert error handling
    }
    // The below was taken from webdeveloper.com/forum/archive/index.php/t-93091.html
    // There are two ways to add a rule, try each of them in turn
    // First see if insertRule is supported.
    if (document.styleSheets[cssindex].insertRule) {
        // Pass something like "p{attribute1:value1;attribute2:value2;}" to insertRule
        document.styleSheets[cssindex].insertRule(selector + '{' + attributes + '}',
                                                    document.styleSheets[cssindex].cssRules.length);
        //Leave the function
        return true;
    }

    //Then see if addRule is supported
    else if (document.styleSheets[cssindex].addRule) {
        // addRule takes selector, attributes, so e.g. "p", "attribute1:value1;attribute2:value2;"
        document.styleSheets[cssindex].addRule(selector, attributes);
        // Leave the function
        return true;
    }
    else {
        // Neither way has worked, we're leaving...
        return false;
    }
}

// CE 2009-08-05 The below function calls fncAddCSSRule.  It is called by fncCheckIE6 in the various schemes
// if the browser is IE6
// The purpose of the function is to fix the formatting of the scheme update / news
function fncFixIE6CSS() {
    fncAddCSSRule("../../css/main.css", ".navButtonCont", "position:absolute;top:56.2em;left:0.5em;width:84.3em");
    fncAddCSSRule("../../css/main.css", ".companyNameCont", "width:40em;");
    fncAddCSSRule("../../css/main.css", ".nameOfScheme", "width:270em;");
    fncAddCSSRule("../../css/main.css", ".txtLossComment", "height:3.5em;width:95%;");
    return true;
}

function fncFixSmallScreenCSS() {
    fncAddCSSRule("../../css/main.css", ".sofFirstSpace", "height:5px;");
    fncAddCSSRule("../../css/main.css", ".sofSecondSpace", "height:5px;");
    fncAddCSSRule("../../css/main.css", ".txtLossComment", "height:3.5em;");
    fncAddCSSRule("../../css/main.css", ".navButtonCont", "position:absolute; top:53.6em;");
    fncAddCSSRule("../../css/main.css", ".navButtonContQS", "position:absolute; top:52.6em;");
    fncAddCSSRule("../../css/main.css", ".navButtonContHC", "position:absolute; top:45em;");
    return true;
}

// CE 2009-08-11 The below function changes the position of the navigation buttons for each scheme, for the case
// where the form elements overflow the page.  The function puts the buttons below the lowest form element when 'true'
// is passed, and sets the the buttons to their previous settings when 'false' is passed.
function fncToggleNavButtonFloat(on) {
    //If we want to float the nav buttons
    if (on) {
        // fncToggleNavButtonFloat.X are effectively static variables.  The next time the function is called,
        // these variables will retain their value.  Note this only works while on the same page, they are not saved
        // like session variables are.
        // The below variable determines if we've stored the width, top and position of navButtonCont
        fncToggleNavButtonFloat.settingsapplied = true;
        // Store the width, top and position
        fncToggleNavButtonFloat.navposition = document.getElementById("navButtonCont").style.position
        fncToggleNavButtonFloat.navtop = document.getElementById("navButtonCont").style.top;
        fncToggleNavButtonFloat.navwidth = document.getElementById("navButtonCont").style.width;
        if ('<%=session("IsIe6")%>' == 'True') {
            document.getElementById("navButtonCont").style.position = "fixed";
            document.getElementById("navButtonCont").style.top = "630px";
            document.getElementById("navButtonCont").style.width = String(document.body.clientWidth - 40) + "px";
        }
        else {
            document.getElementById("navButtonCont").style.position = "static";
            document.getElementById("navButtonCont").style.width = String(document.body.clientWidth - 40) + "px";
        }
    }
    else {
        // If we previously saved the width and position of navButtonCont
        if (fncToggleNavButtonFloat.settingsapplied) {
            // Restore the width and position
            document.getElementById("navButtonCont").style.top = fncToggleNavButtonFloat.navtop;
            document.getElementById("navButtonCont").style.position = fncToggleNavButtonFloat.navposition;
            document.getElementById("navButtonCont").style.width = fncToggleNavButtonFloat.navwidth;
        }
        // Reset the 'settings applied' variable.
        fncToggleNavButtonFloat.settingsapplied = false;
    }
}
// The below is a function to determine which radio button is selected in a span containing only radio buttons, and
// then to return an integer corresponding to this button.
function fncRadioButtonValue(span) {
    //Todo:  Add some sort of error checking to determine that it's actually a span.
    // The below is a modified version of Gladys's code.
    var spanfields = span.getElementsByTagName("input");
    var i;
    for (i = 0; i < spanfields.length; i++) {

        if (spanfields[i].checked) {
            return i + 1;
        }
    }
    return RB_NO_VALUE;
}

// The below outlines the program's generic response when validation fails
function fncValidationFailed() {
    alert("Mandatory Information not complete:\n\n* Required field");
}

//The function below colours a field yellow if it doesn't have anything in it, otherwise colours it white.
function fncFormatMandatory(field) {
    if (field.value == "") {

        field.style.backgroundColor = FIELD_HIGHLIGHT_COLOUR;
        field.style.border = '1px solid #7f9db9';
        if (field.type == 'text') {
            field.style.height = '15px';
        }
        if (field.type == 'select-one') {
            //fix listbox background colour
        }
    }
    else {
        field.style.backgroundColor = 'white';
        field.style.border = '1px solid #7f9db9';
        if (field.type == 'text') {
            field.style.height = '15px';
        }
        if (field.type == 'select-one') {
            if (field.options[0].value == '' && (field.options[1].value != '1')) {
                field.remove(0);
            }
        }
    }
}

function fncFormatMandatoryGroup(fieldarray) {
    var i;
    var s = "";
    var colour;
    for (i = 0; i < fieldarray.length; i++) {
        s = s + fieldarray[i].value;
    }
    if (s == "") {
        colour = FIELD_HIGHLIGHT_COLOUR;
    }
    else {
        colour = "white";
    }
    for (i = 0; i < fieldarray.length; i++) {
        fieldarray[i].style.backgroundColor = colour;
        fieldarray[i].style.border = '1px solid #7f9db9';
        if (fieldarray[i].type == 'text') {
            fieldarray[i].style.height = '15px';
        }
    }
}

//Remove the blank item from the top of a listbox - CE
function fncRemoveBlankItem(listbox) {
    if (listbox.options[0].value == '') {
        listbox.remove(0);
    }
}

function fncAddBlankItemToListbox(Listbox) {
    //Add a blank item to the top of a listbox.  Firefox doesn't recognise
    //options.count or options.length, so I'm using this method
    // create a listbox item
    if (Listbox.value != "") {
        var opt = document.createElement("OPTION");
        //set it to blank.
        opt.text = "";
        opt.value = "";
        //add it to the bottom of the listbox
        Listbox.options.add(opt);
        var p = 0;
        //the ++p adds one to p, then options[p] is checked, if it's blank the loop ends.
        //i.e. the below line increases p until Listbox.option[p] is blank.
        while (!(Listbox.options[++p].value == ""));
        while (p > 0) {
            //set each item to be the value of the item above it.
            Listbox.options[p].value = Listbox.options[p - 1].value;
            Listbox.options[p].text = Listbox.options[p - 1].text;
            p--;
        }
        //set the top item to blank.
        Listbox.options[0].text = "";
        Listbox.options[0].value = "";
    }
}

function fncAdd0ItemToListbox(Listbox) {
    //Add a blank item to the top of a listbox.  Firefox doesn't recognise
    //options.count or options.length, so I'm using this method
    // create a listbox item
    if (Listbox.value != "") {
        var opt = document.createElement("OPTION");
        //set it to blank.
        opt.text = "";
        opt.value = "";
        //add it to the bottom of the listbox
        Listbox.options.add(opt);
        var p = 0;
        //the ++p adds one to p, then options[p] is checked, if it's blank the loop ends.
        //i.e. the below line increases p until Listbox.option[p] is blank.
        while (!(Listbox.options[++p].value == ""));
        while (p > 0) {
            //set each item to be the value of the item above it.
            Listbox.options[p].value = Listbox.options[p - 1].value;
            Listbox.options[p].text = Listbox.options[p - 1].text;
            p--;
        }
        //set the top item to blank.
        Listbox.options[0].text = "0";
        Listbox.options[0].value = "0";
    }
}
function IntegersOnly(txtBox) {
    txtBox.value = txtBox.value.replace(/[^0-9]/g, "");

}

function EnableNavButton(BtnID, Onclick) {
    var Btn = document.getElementById(BtnID);
    Btn.setAttribute("className", "navButton");
    Btn.setAttribute("class", "navButton");
    Btn.onmouseover = new Function("this.className='NavButtonOver';");
    Btn.onmouseout = new Function("this.className='navButton';");
    Btn.onmousedown = new Function("this.className='navButtonDown';");
    Btn.onmouseup = new Function("this.className='navButton';");
    Btn.onclick = new Function("this.className='navButtonDown'; " + Onclick + ";");
}
function DisableNavButton(BtnID) {
    var Btn = document.getElementById(BtnID);
    Btn.setAttribute("className", "navButtonDown");
    Btn.setAttribute("class", "navButtonDown");
    Btn.onmouseover = new Function("");
    Btn.onmouseout = new Function("");
    Btn.onmousedown = new Function("");
    Btn.onmouseup = new Function("");
    Btn.onclick = new Function("");

}

function TechnicianDetails(Mode) {
    var EntryType = "Modify";

    if (Mode == "NEW") {
        EntryType = "New";
    }

    WinTechnicianDetails = dhtmlmodal.open("WinTechnicianDetails", "iframe", "Treatment_Operatives_Details.aspx?Mode=" + Mode, EntryType + " Technician", "width=700,height=160px,center=1,resize=0,scrolling=0")

}






function AddItemToLIstBox(ListBox, Value, Text) {
    //create the element
    var opt = document.createElement("OPTION");
    //set its value and text
    opt.text = Text;
    opt.value = Value;
    //lets add it to the list
    ListBox.options.add(opt);
}
function OpenDivModal() {

    document.getElementById("div_Modal").style.display = "block";

}
function fncCheckAddStar(field, starid) {
    //create a star, add it after the field, set the id
    var newElement = document.createElement('img');
    if (document.getElementById(starid) == null) {
        newElement.setAttribute('src', '../../images/final/red_star_10_10.gif');
        newElement.setAttribute('align', 'top');
        newElement.setAttribute('id', starid);
        newElement.style.float = "left"
        newElement.style.marginLeft = "2px"
        insertAfter(newElement, field);
    }
}

function fncCheckRemoveStar(field, starid, parentid) {
    //hide a star if it exists

    if (document.getElementById(starid) != null) {
        var parent = document.getElementById(parentid);
        parent.removeChild(document.getElementById(starid));
    }
}
function GetParent(Object) {
    //lets get the parent for an object
    var Object = document.getElementById(Object);
    var Parent = Object.parentNode;


    return Parent;
}

function fncAddStar_II(Object) {
    //create a star, add it after the field, set the id
    //Lets create the stars ID based on the field/ object id
    var StarID = "";
    StarID = Object.id + "_STAR";
    //lets put in some code to see if it is an infragistics object!!!
    if (Object.id == undefined) {
        StarID = Object.ID + "_STAR";
        if (Object.ID == undefined) {
            StarID = Object.Id + "_STAR";
        }
    }

    var newElement = document.createElement('img');

    //if you try to add the same star twice with out removing it we get a blank square
    if (document.getElementById(StarID) != null) {
        var ParentObj = GetParent(StarID);
        ParentObj.removeChild(document.getElementById(StarID));
    }
    if (document.getElementById(StarID) == null) {
        newElement.setAttribute('src', '/images/final/red_star_10_10.gif'); //Live version
        //newElement.setAttribute('src', '/QE_BUA/images/final/red_star_10_10.gif');
        newElement.setAttribute('align', 'top');
        newElement.setAttribute('id', StarID);
        newElement.style.float = "left"
        newElement.style.marginLeft = "2px"
        insertAfter(newElement, Object);
    }
}

function fncRemoveStar_II(Object) {
    //hide a star if it exists
    //Lets create the stars ID based on the field/ object id
    StarID = Object.id + "_STAR";
    //lets put in some code to see if it is an infragistics object!!!
    if (Object.id == undefined) {
        StarID = Object.ID + "_STAR";
        if (Object.ID == undefined) {
            StarID = Object.Id + "_STAR";
        }
    }
    if (document.getElementById(StarID) != null) {
        var ParentObj = GetParent(StarID);
        ParentObj.removeChild(document.getElementById(StarID));
    }
}

function HideGrid() {
    var Grid = igtbl_getGridById("UltraWebGrid1");
    Grid.hide();
}

function ShowGrid() {
    var Grid = igtbl_getGridById("UltraWebGrid1");
    Grid.show();
}



function Get_Expriy_Date(Inception_Date) {
    //This function will calculate the expiry date based on the inception date.
    //The expiry date will be 1 year from the inception date
    var Year = "";
    var Month = "";
    var Day = "";
    var Expiry_Date = "";
    //lets see if there is something here first
    if (StringOrUndefined(Inception_Date) == '') {
        Expiry_Date = '';
        return Expiry_Date;
    }
    //lets create the date
    Inception_Date = new Date(Inception_Date);
    //now lets get the bits
    Month = Inception_Date.getMonth();
    Day = Inception_Date.getDate();
    Year = Inception_Date.getFullYear();
    //lets add 1 year and minus a day
    Inception_Date = new Date(Year + 1, Month, Day - 1);
    //lets build the string
    Month = Inception_Date.getMonth() + 1;
    Day = Inception_Date.getDate();
    Year = Inception_Date.getFullYear();
    Expiry_Date = Format_Date(Day, Month, Year);
    //send it back
    return Expiry_Date
}

function Set_Expiry_Date(Expiry_ID, Inception_Date) {

    var Expiry_Date_Field = document.getElementById(Expiry_ID);
    var txt_Expiry = document.getElementById("txt_Expiry");
    var Expiry =Get_Expriy_Date(Inception_Date);
    Expiry_Date_Field.innerHTML = Expiry;
    txt_Expiry.value = Expiry;
}

function Format_Date(Day, Month, Year) {
    //lets function will take a date in as day month year and build the appropriate string
    var ReturnString = "";

    if (Day.toString().length < 2) {
        Day = "0" + Day;
    }
    if (Month.toString().length < 2) {
        Month = "0" + Month;
    }

    ReturnString = Day + "/" + Month + "/" + Year;
    return ReturnString;
}

function Validate_Inception_Date(Date_Object) {

    var Date = StringOrUndefined(Date_Object.getValue());
    var Date_Cell = document.getElementById("td_Date");


    if (Date == '') {
        Date_Cell.style.backgroundImage = "url(/QE_BUA/images/final/red_star_10_10.gif)";

        return false;

    } else {
        Date_Cell.style.backgroundImage = "";

        return true;
    }
}

function Validate_Date(Date_Object, Date_Cell) {

    var Date = StringOrUndefined(Date_Object.getValue());
    var Date_Cell = document.getElementById(Date_Cell);


    if (Date == '') {
        Date_Cell.style.backgroundImage = "url(/QE_BUA/images/final/red_star_10_10.gif)";

        return false;

    } else {
        Date_Cell.style.backgroundImage = "";

        return true;
    }
}
function StringOrUndefined(Value) {
    //similar to string or null lets check to see if it is just undefined
    var Return_Value = "";

    if (Value == undefined || Value == "undefined") {

        Return_Value = "";

    } else {

        Return_Value = Value;
    }

    return Return_Value;

}

function SetMandatory(Object) {
    var GroupName = "";
    var arrRadioButtons = "";
    var RadioButton = "";
    var GroupLength = 0;


    //this should work for all standard controls other controls ie infragistics will need another function
    if (Object.type == 'checkbox') {

        if (Object.checked == false) {

            fncAddStar_II(Object);
            return false;

        } else {

            fncRemoveStar_II(Object);
            return true;
        }

        return true;
    }
    //lets see if it is a radio button, we only need to pass the one of the radio buttons to validate the group
    if (Object.type == 'radio') {
        //its a radio button so lets check to see if any of its group are checked
        GroupName = Object.getAttribute("name");
        arrRadioButtons = document.getElementsByName(GroupName);
        //now lets see if any are selected
        if (!Is_Group_Selected(GroupName)) {
            //lets get the size of the group
            GroupLength = arrRadioButtons.length - 1;
            //none are selected so lets go through the array and fine the last one
            for (i = 0; i < arrRadioButtons.length; i++) {
                //if any of them are selected then lets set it to true
                if (i == GroupLength) {
                    fncAddStar_II(arrRadioButtons[i].parentNode);
                    return false;
                }
            }
        } else {
            //lets get the size of the group
            GroupLength = arrRadioButtons.length - 1;
            //none are selected so lets go through the array and fine the last one
            for (i = 0; i < arrRadioButtons.length; i++) {
                //if any of them are selected then lets set it to true
                if (i == GroupLength) {
                    fncRemoveStar_II(arrRadioButtons[i].parentNode);
                    return true;
                }
            }
        }
        return true;
    }

    if (StringOrUndefined(Object.value) == '') {
        fncAddStar_II(Object);
        return false;

    } else {
        fncRemoveStar_II(Object);
        return true;
    }
}


function Can_We_OK_Hold_Cover() {

    var CanWeOK = true;

    var Property = document.getElementById("txtProperty");
    var Street = document.getElementById("txtStreet");
    var Locality = document.getElementById("txtLocality");
    var Town = document.getElementById("txtTown");
    var County = document.getElementById("txtCounty");
    var PostCode = document.getElementById("txtPostcode");

    var Refresh = document.getElementById("cmdRefresh");

    //lets SetMandatory
    if (PostCodeFound && PostCode.value != "") {

        SetMandatory(Property);
    }



    SetLocCon(Locality, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(Town, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(County, "Y", "Y", "LG", "B", "", "252px")

    //SetMandatory(Locality);
    //SetMandatory(Town);
    //lets disable the refresh button
    

    //Does the current postcode match the old one?
    if (OLD_PostCode != PostCode.value) {
        CanWeOK = false;
        fncAddStar_II(PostCode);
        Refresh.style.display = "none";

    } else {
        fncRemoveStar_II(PostCode);
        Refresh.style.display = "inline";
    }

    //Firstly lets see if the address is ok or not!?!
    if (Property.value == '') {
        CanWeOK = false;
    } else {
        fncRemoveStar_II(Property);
    }
    if (PostCode.value == '') {
        CanWeOK = false;
    }

    if (!SetMandatory(PostCode)) {
        Refresh.style.display = "none";
    }

    if (!Validate_Inception_Date(igdrp_getComboById('datInceptionDate'))) {
        CanWeOK = false;
    }
    //lets disable the holdcover button
    if (CanWeOK == false) {
        DisableNavButton('btn_HoldCover')
        //let enable it
    } else {
        EnableNavButton('btn_HoldCover', "Hold_Cover();")
    }
}

function Hold_Cover() {

    if (Can_We_OK_Hold_Cover) {

        document.getElementById("form1").submit();
    }


}

function Can_We_OK_Terror_C() {

    var CanWeOK = true;


    var Proposer = document.getElementById("txtProposer");
    var Property = document.getElementById("txtProperty");
    var Street = document.getElementById("txtStreet");
    var Locality = document.getElementById("txtLocality");
    var Town = document.getElementById("txtTown");
    var County = document.getElementById("txtCounty");
    var PostCode = document.getElementById("txtPostcode");
    var Type_of_Cover = document.getElementById("lstTypeOfCover");
    var Occupancy_Trade = document.getElementById("txtOccupancyTrade");
    var Buildings = document.getElementById("txtBuildings");
    var Contents = document.getElementById("txtContents");
    var LOR = document.getElementById("txtLossOfRent");
    var BI = document.getElementById("txtBusinessInterruption");
    var ICOW = document.getElementById("txtCostOfWorking");
    var TBA = document.getElementById("chk_TBA");
    var Date_Cell = document.getElementById("td_Date");
    var Date_Chooser = igdrp_getComboById('datInceptionDate');
    var Refresh = document.getElementById("cmdRefresh");

    //lets SetMandatory

    if (!SetMandatory(Proposer)) {
        CanWeOK = false;
    }



    SetMandatory(Type_of_Cover);
    SetMandatory(Occupancy_Trade);

    SetMandatory(Buildings);
    SetMandatory(Contents);
    SetMandatory(LOR);
    SetMandatory(BI);
    SetMandatory(ICOW);

    SetMandatory(TBA);

    //have they entered a valid postcode 
    if (PostCodeFound && PostCode.value != "") {

        SetMandatory(Property);
    }
    SetLocCon(Locality, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(Town, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(County, "Y", "Y", "LG", "B", "", "252px")
    
    //Does the current postcode match the old one?
    if (OLD_PostCode != PostCode.value) {
        CanWeOK = false;
        fncAddStar_II(PostCode);
        Refresh.style.display = "none";

    } else {
        fncRemoveStar_II(PostCode);
        Refresh.style.display = "inline";
    }

    if (!SetMandatory(PostCode)) {
        Refresh.style.display = "none";
    }

    //Firstly lets see if the address is ok or not!?!
    if (Property.value == '') {
        CanWeOK = false;
    } else {
        fncRemoveStar_II(Property);
    }
    if (PostCode.value == '') {
        CanWeOK = false;
    }
    if (TBA.checked == false && !Validate_Inception_Date(igdrp_getComboById('datInceptionDate'))) {
        CanWeOK = false;
    } else {
        Date_Cell.style.backgroundImage = "";
        fncRemoveStar_II(TBA);
        //lets either uncheck or blank the inception date we cant have both
    }
    //lets deal with the type of cover and trade
    if (Type_of_Cover.value == '') {
        CanWeOK = false;
    }
    if (Occupancy_Trade.value == '') {
        CanWeOK = false;
    }

    //lets sort out the SI's must have atleat one
    if (Buildings.value == '' && Contents.value == '' && LOR.value == '' && BI.value == '' && ICOW.value == '') {
        CanWeOK = false;
    } else {
        fncRemoveStar_II(Buildings);
        fncRemoveStar_II(Contents);
        fncRemoveStar_II(LOR);
        fncRemoveStar_II(BI);
        fncRemoveStar_II(ICOW);
    }



    //lets disable the holdcover button
    if (CanWeOK == false) {
        DisableNavButton('divFinalStepButton')
        //let enable it
    } else {
        EnableNavButton('divFinalStepButton', "fncWizardNav('divSummaryCont', 3, 'novalidate', true);")
    }
}

function Clear_Date_Chooser(Date_Chooser_ID) {

    var Date_Chooser = igdrp_getComboById(Date_Chooser_ID)
    var TBA = document.getElementById("chk_TBA");

    if (TBA.checked == true) {
        Date_Chooser.setText("");
    }
}

function Clear_TBA(Date_Chooser_ID) {

    var Date_Chooser = igdrp_getComboById(Date_Chooser_ID)
    var TBA = document.getElementById("chk_TBA");

    if (Date_Chooser.getText() != "") {
        TBA.checked = false;
    }
}
function Can_We_OK_Terror_R() {

    var CanWeOK = true;


    var Proposer = document.getElementById("txtProposer");
    var Property = document.getElementById("txtProperty");
    var Street = document.getElementById("txtStreet");
    var Locality = document.getElementById("txtLocality");
    var County = document.getElementById("txtCounty");
    var Town = document.getElementById("txtTown");
    var PostCode = document.getElementById("txtPostcode");
    var Type_of_Cover = document.getElementById("lstTypeOfCover");
    var Buildings = document.getElementById("txtBuildings");
    var Contents = document.getElementById("txtContents");
    var LOR = document.getElementById("txtLossOfRent");
    var TBA = document.getElementById("chk_TBA");
    var Date_Cell = document.getElementById("td_Date");
    var Date_Chooser = igdrp_getComboById('datInceptionDate');
    var Refresh = document.getElementById("cmdRefresh");

    //lets SetMandatory
    if (!SetMandatory(Proposer)) {
        CanWeOK = false;
    }

    SetMandatory(Type_of_Cover);

    SetMandatory(Buildings);
    SetMandatory(Contents);
    SetMandatory(LOR);

    SetMandatory(TBA);
    //have they entered a valid postcode 
    if (PostCodeFound && PostCode.value != "") {

        SetMandatory(Property);
    }
    SetLocCon(Locality, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(Town, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(County, "Y", "Y", "LG", "B", "", "252px")
   

    //Does the current postcode match the old one?
    if (OLD_PostCode != PostCode.value) {
        CanWeOK = false;
        fncAddStar_II(PostCode);
        Refresh.style.display = "none";

    } else {
        fncRemoveStar_II(PostCode);
        Refresh.style.display = "inline";
    }

    if (!SetMandatory(PostCode)) {
        Refresh.style.display = "none";
    }

    //Firstly lets see if the address is ok or not!?!
    if (Property.value == '') {
        CanWeOK = false;
    } else {
        fncRemoveStar_II(Property);
    }
    if (PostCode.value == '') {
        CanWeOK = false;
    }

    if (TBA.checked == false && !Validate_Inception_Date(igdrp_getComboById('datInceptionDate'))) {
        CanWeOK = false;
    } else {
        Date_Cell.style.backgroundImage = "";
        fncRemoveStar_II(TBA);
        //lets either unckec or blank the inception date we cant have both
    }
    //lets deal with the type of cover and trade
    if (Type_of_Cover.value == '') {
        CanWeOK = false;
    }

    //lets sort out the SI's must have atleat one
    if (Buildings.value == '' && Contents.value == '' && LOR.value == '') {
        CanWeOK = false;
    } else {
        fncRemoveStar_II(Buildings);
        fncRemoveStar_II(Contents);
        fncRemoveStar_II(LOR);
    }



    //lets disable the holdcover button
    if (CanWeOK == false) {
        DisableNavButton('divFinalStepButton')
        //let enable it
    } else {
        EnableNavButton('divFinalStepButton', "fncWizardNav('divSummaryCont', 3, 'novalidate', true);")
    }
}

function Clear_Date_Chooser(Date_Chooser_ID) {

    var Date_Chooser = igdrp_getComboById(Date_Chooser_ID)
    var TBA = document.getElementById("chk_TBA");

    if (TBA.checked == true) {
        Date_Chooser.setText("");
        Date_Chooser.setValue(null);

    }
}

function Clear_TBA(Date_Chooser_ID) {

    var Date_Chooser = igdrp_getComboById(Date_Chooser_ID)
    var TBA = document.getElementById("chk_TBA");

    if (Date_Chooser.getText() != "") {
        TBA.checked = false;
    }
}

//this is the variable used to set the date chooser to blank, for some strange reason you have to do it on the on value changed event as well!?!?!?
var Found_Invalid_Date = false;

function Invalid_Date(Object_ID, Calling_Event) {
    //this event fires when an invalid date is entered and will set the date to "".
    //but then a hidden event fires which sets it to its max or min date???
    //this is why we call the second event fncdatinceptiondatevaluechanged

    if (Found_Invalid_Date == false && Calling_Event == 'InvalidDateEntered') {

        alert("Invalid Date For Inception");

        igdrp_getComboById(Object_ID).setText("00/00/0000");

        Found_Invalid_Date = true;

        return true;
    }

    if (Found_Invalid_Date == true) {
        //this function is called from the client side events property of the webdate chooser
        //value changed event and fires after the invalid date entered event
        igdrp_getComboById(Object_ID).setText("");
        igdrp_getComboById(Object_ID).focus();

        Found_Invalid_Date = false;
    }
}

function Is_Group_Selected(GroupName) {
    //this will cycle through all the objects in a group i.e. radio buttons and see if any are selected
    var Group = document.getElementsByName(GroupName);
    var Is_Selected = false;
    //lets go through each element
    for (i = 0; i < Group.length; i++) {
        //if any of them are selected then lets set it to true
        if (Group[i].checked == true) {
            Is_Selected = true;
        }
    }

    return Is_Selected;
}

function RadioButtonValue_By_Group(GroupName) {
    //lets go through the group and return the value of the selected one, yes = 1 no = 0
    var Group = document.getElementsByName(GroupName);
    var Selected_value = "";
    //lets go through each element
    for (i = 0; i < Group.length; i++) {
        //Get the value of the selected one, we can only have one which is selected
        if (Group[i].checked == true) {
            Selected_value = Group[i].value;

            return Selected_value;
        }
    }
}
//------------------------------------------------------------------START OF TREATMENT----------------------------------------------------------
function AtLeast_One_Trade() {

    var HaveWeAtLeastOneTrade = false;
    var Tattooists = false;
    var Body_Piercing = false;
    var Hairdressers = false;
    var Beauty_Salons = false;
    var Tanning = false;

    Tattooists = Is_Group_Selected('tattooists');
    Body_Piercing = Is_Group_Selected('piercing');
    Hairdressers = Is_Group_Selected('hair');
    Beauty_Salons = Is_Group_Selected('beauty');
    //Tanning = Is_Group_Selected('tan');
    Nail_bars = Is_Group_Selected('nail');

    //lets see if any of the trades are selected first if not lets bugger off ski
    if (Tattooists == false && Body_Piercing == false && Hairdressers == false && Beauty_Salons == false
        && Nail_bars == false && Tanning == false) {

        return false;
    }

    Tattooists = RadioButtonValue_By_Group('tattooists');
    Body_Piercing = RadioButtonValue_By_Group('piercing');
    Hairdressers = RadioButtonValue_By_Group('hair');
    Beauty_Salons = RadioButtonValue_By_Group('beauty');
    Tanning = RadioButtonValue_By_Group('tan');
    Nail_bars = RadioButtonValue_By_Group('nail');
    //lets check that they have said to atleast one trade
    if (Tattooists == 0 && Body_Piercing == 0 && Hairdressers == 0 && Beauty_Salons == 0
        && Nail_bars == 0 && Tanning == 0) {

        return false;
    }

    return true;
}


function Can_We_OK_Treatment() {

    var CanWeOK = true;


    var Proposer = document.getElementById("txtProposer");
    var Property = document.getElementById("txtProperty");
    var Street = document.getElementById("txtStreet");
    var Locality = document.getElementById("txtLocality");
    var Town = document.getElementById("txtTown");
    var County = document.getElementById("txtCounty");
    var PostCode = document.getElementById("txtPostcode");
    var Limit_Of_Cover = document.getElementById("lstLimitOfCover");
    var Public_Liability = document.getElementById("ddl_PL_Limit");
    var No_Technicians = document.getElementById("txtTechnicians");
    var IPL_Make_Model = document.getElementById("txtIPLModel");
    var Tattooists = false;
    var Body_Piercing = false;
    var Hairdressers = false;
    var Beauty_Salons = false;
    var SPMUYes = document.getElementById('SPMUYes');
    var SPMU_Operatives = document.getElementById('txt_SPMU_Operatives');
    var IPLYes = document.getElementById('iplYes');

    var AtLeastOneTrade = "";

    var Nail_bars = false;
    var Tanning = false;

    var TBA = document.getElementById("chk_TBA");
    var Date_Cell = document.getElementById("td_Date");
    var Date_Chooser = igdrp_getComboById('datInceptionDate');
    var ErrMess;

    var Refresh = document.getElementById("cmdRefresh");
    //lets SetMandatory
    if (!SetMandatory(Proposer)) {
        CanWeOK = false;
    }


    if (PostCodeFound && PostCode.value != "") {

        SetMandatory(Property);
    }



    SetLocCon(Locality, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(Town, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(County, "Y", "Y", "LG", "B", "", "252px")
    
    //SetMandatory(Locality);
    //SetMandatory(Town);
    

    //Does the current postcode match the old one?
    if (OLD_PostCode != PostCode.value) {
        CanWeOK = false;
        fncAddStar_II(PostCode);
        Refresh.style.display = "none";

    } else {
        fncRemoveStar_II(PostCode);
        Refresh.style.display = "inline";
    }

    if (!SetMandatory(PostCode)) {
        Refresh.style.display = "none";
    }

    //have they selected the limit of cover??
    if (!SetMandatory(Limit_Of_Cover)) {
        CanWeOK = false;
    }
    //have they entered the technicians??
    if (!SetMandatory(No_Technicians)) {
        CanWeOK = false;
    }
    //all trades must be selected and at least one must be true
    if (!SetMandatory(document.getElementById('tatYes'))) {
        CanWeOK = false;
    }
    if (!SetMandatory(document.getElementById('bpYes'))) {
        CanWeOK = false;
    }
    if (!SetMandatory(document.getElementById('hairYes'))) {
        CanWeOK = false;
    }
    if (!SetMandatory(document.getElementById('beautyYes'))) {
        CanWeOK = false;
    }
    if (!SetMandatory(document.getElementById('nailYes'))) {
        CanWeOK = false;
    }

    if (!AtLeast_One_Trade()) {
        CanWeOK = false;
    } else {
        //if they have beauty then what about ipl and spmu
        if (RadioButtonValue_By_Group('beauty') == 1) {
            if (!SetMandatory(IPLYes)) {
                CanWeOK = false;
            } else {
                //ipl make and model
                if (RadioButtonValue_By_Group('ipl') == 1) {
                    //lets set / unset the red astris
                    SetMandatory(IPL_Make_Model);
                    //if the make/ model is blank but they do use one then they cant ok
                    if (IPL_Make_Model.value == "") {
                        CanWeOK = false;
                    }
                }
            }
            //lets see if spmu has been selected at all 
            if (!SetMandatory(SPMUYes)) {
                //they havent said yay or ney
                CanWeOK = false;
            } else {
                //they have selected it was it a yes???
                if (RadioButtonValue_By_Group('SPMU') == 1) {
                    //It was a yes but have they entered the operatives
                    if (!SetMandatory(SPMU_Operatives)) {
                        CanWeOK = false;
                    }
                }
            }
        }
    }

    SetMandatory(TBA);

    //Firstly lets see if the address is ok or not!?!
    if (Property.value == '' ) {
        CanWeOK = false;
    } else {
        fncRemoveStar_II(Property);
    }
    if (PostCode.value == '') {
        CanWeOK = false;
    }
    if (TBA.checked == false && !Validate_Inception_Date(igdrp_getComboById('datInceptionDate'))) {
        CanWeOK = false;
    } else {
        Date_Cell.style.backgroundImage = "";
        fncRemoveStar_II(TBA);
        //lets either unccheck or blank the inception date we cant have both
    }

    //lets disable the holdcover button
    if (CanWeOK == false) {
        DisableNavButton('divFinalStepButton')
        //let enable it
    } else {                                 //if(fncValidateSOF()) fncWizardNav('divPropDetailsCont', 2, 'novalidate');'
        EnableNavButton('divFinalStepButton', "if(ValidateTechnicians()){Calculate_ARs();HideGrid(); fncWizardNav('divSummaryCont', 3, 'novalidate', true)}")
    }
}

function ValidateTechnicians() {

    //lets get the grid
    var GridName = "UltraWebGrid1";
    var Grid = igtbl_getGridById(GridName);

    var ErrMess = "";
    var ErrMess_New_Line = "New_Line_Here_OK";
    var ErrReply = false;

    var txtTechnicians = document.getElementById("txtTechnicians");

    var Alert_Result = document.getElementById("txt_Alert_Result");
    //lets get the row count
    var RowCount = igtbl_getGridById(GridName).Rows.length;
    //have they got Zero technicians

    if (txtTechnicians.value == 0) {
        ErrMess = "No. of Technicians can not be 0" + ErrMess_New_Line + ErrMess_New_Line + "Please enter Number of Technicians."
        WinAlert_MSG_BOX = dhtmlmodal.open("WinAlert_MSG_BOX", "iframe", "../../QE_BUA/Alert_Msg.aspx?ErrMess=" + ErrMess + "&MSG_Type=OK" + "&Where_From=" + "WinQuoteEntry" + "&Icon_To_Show=WARNING" + "&Return_Function=" + "", "Number of Technicians", "width=350,height=200px,center=1,resize=0,scrolling=0")
        Alert_Result.value = "";
        return false;
    }

    //lets check they have entered enough details
    if (RowCount < txtTechnicians.value) {
        ErrMess = "No. of Technicians does not match" + ErrMess_New_Line + "the number of details entered." + ErrMess_New_Line + ErrMess_New_Line + "Please enter Technicians Details."
        WinAlert_MSG_BOX = dhtmlmodal.open("WinAlert_MSG_BOX", "iframe", "../../QE_BUA/Alert_Msg.aspx?ErrMess=" + ErrMess + "&MSG_Type=OK" + "&Where_From=" + "WinQuoteEntry" + "&Icon_To_Show=WARNING" + "&Return_Function=" + "", "Number of Technicians", "width=350,height=200px,center=1,resize=0,scrolling=0")
        Alert_Result.value = "";
        return false;
    }
    //    //lets see how many they have
    if (txtTechnicians.value < RowCount) {
        //have they already answered this yet?
        if (StringOrUndefined(Alert_Result.value) == "") {
            //obviously not so lets ask the question
            ErrMess = "No. of Technicians does not match" + ErrMess_New_Line + "the number of details entered." + ErrMess_New_Line + ErrMess_New_Line + "Please enter No. of Technicians ?";
            //lets try the alert box dhtmlmodal
            WinAlert_MSG_BOX = dhtmlmodal.open("WinAlert_MSG_BOX", "iframe", "../../QE_BUA/Alert_Msg.aspx?ErrMess=" + ErrMess + "&MSG_Type=OK" + "&Where_From=" + "WinQuoteEntry" + "&Icon_To_Show=INFORMATION" + "&Return_Function=" + "", "Number of Technicians", "width=350,height=200px,center=1,resize=0,scrolling=0")
            //was it a no if so lets send them on and ok it
        } else if (StringOrUndefined(Alert_Result.value) == "NO") {
            Alert_Result.value = "";
            Calculate_ARs();
            HideGrid();
            fncWizardNav('divSummaryCont', 3, 'novalidate', true);
            return true;
            //was it a yes  if so lets update the technicians
        } else if (StringOrUndefined(Alert_Result.value) == "YES") {
            //lets update the techs field , and ok it
            txtTechnicians.value = RowCount;
            Alert_Result.value = "";
            Calculate_ARs();
            HideGrid();
            fncWizardNav('divSummaryCont', 3, 'novalidate', true);
            return true;
            //if it was cancelled then set the result to "" and return this will close the div window properly.
        } else if (StringOrUndefined(Alert_Result.value) == "CANCEL") {
            Alert_Result.value = "";
            return true;
        }
    } else {
        //all must be ok so let them go ahead.
        return true;
    }
}

function TreatmentCheckForDuplicateNames(Mode) {

    var NewName = "";
    var ExistingName = "";
    var GridName = "UltraWebGrid1";
    var Grid = parent.window.frames["_iframe-WinQuoteEntry"].igtbl_getGridById(GridName);
    var CurrentRow = "";
    var RowCount = 0;
    var Row = "";
    var I;
    var ErrMess = "";


    ErrMess = "Duplicate Name Detected!!!\n\n";
    ErrMess = ErrMess + "Name MUST Be Unique.";
    //lets get the new name
    NewName = document.getElementById("txt_Name").value;

    NewName = NewName.toUpperCase();

    RowCount = Grid.Rows.length;

    if (RowCount > 0) {

        parent.window.frames["_iframe-WinQuoteEntry"].igtbl_selectRow(GridName, 0, true)

        CurrentRow = parent.window.frames["_iframe-WinQuoteEntry"].igtbl_getActiveRow(GridName);

        CurrentRow = CurrentRow.Id;

        for (I = 0; I < RowCount; I++) {
            //lets if if the new name is the same as the old one
            ExistingName = Grid.Rows.getRow(I).getCellFromKey("Operative_Name").getValue();
            ExistingName = ExistingName.toUpperCase();
            if (ExistingName == NewName) {
                //now if we are update then they can have the same name
                if (Mode != "NEW") {
                    //lets get the row id
                    Row = Grid.Rows.getRow(I).Id;
                    if (CurrentRow != Row) {
                        //lets tell them they cant have this
                        alert(ErrMess);
                        //lets go bye bye
                        return true;
                    }
                } else {
                    alert(ErrMess);
                    //lets go bye bye
                    return true;
                }
            }
        }
    }
}
function DeleteTechnician() {
    //set the grid name
    var GridName = "UltraWebGrid1";
    //lets get the grid
    var Grid = igtbl_getGridById(GridName);
    //lets get the active cell
    var Row = igtbl_getActiveRow(GridName);
    var RowCount = 0;
    var RowNumber = 0;
    var ErrReply = true;
    var ErrMess = "This Action will DELETE this Technicians Details\n\nAre You Sure ?";
    //shall we ask them if they are sure??
    ErrReply = confirm(ErrMess);
    //lets see what the answer was
    if (!ErrReply) {
        //bye bye
        return;
    }

    //now lets delete the row from the grid, must enable the AllowDelete property or it wont work
    Grid.AllowDelete = 1;
    igtbl_deleteRow(Grid, Row.Id);
    //now disable the grid allow delete
    Grid.AllowDelete = 2;
    //lets set the row count now we have deleted the row
    RowCount = Grid.Rows.length;
    //lets work out the top row as if we delete 0 we are in trouble



    //lets see if there are any left
    if (RowCount == 0) {
        //lets disable the buttons
        DisableNavButton("div_Modify_Operative");
        DisableNavButton("div_Delete_Operative");
    } else {
        //lets see how many rows we have and take 1 off
        RowCount = Grid.Rows.length - 1;
        //lets get the row number / id and reference it
        RowNumber = Grid.Rows.getRow(RowCount).Id;
        //now lets put us at the top row again
        igtbl_setActiveRow(GridName, igtbl_getElementById(RowNumber));
        igtbl_selectRow(GridName, RowNumber, true)
        //NOW LETS GET THE ACTIVE ONE AND SCROLL TO IT
        Row = igtbl_getActiveRow(GridName);
        Row.scrollToView();
    }

}

function Calculate_ARs() {
    var txt_HowManyAllRisks = document.getElementById("txt_HowManyAllRisks");
    var HowManyAllRisks = 0;
    var RowCount = 0;
    var I = 0;
    //set the grid name
    var GridName = "UltraWebGrid1";
    //lets get the grid
    var Grid = igtbl_getGridById(GridName);
    //lets see how many we have
    RowCount = Grid.Rows.length;

    for (I = 0; I < RowCount; I++) {
        //lets sort out the all risks(6)
        //getCellFromKey('Operative.All_Risks').getValue() 
        if (Grid.Rows.getRow(I).getCell(6).getValue() == true) {
            HowManyAllRisks = HowManyAllRisks + 1;
        }
    }
    //now lets fill up the textboxes
    txt_HowManyAllRisks.value = HowManyAllRisks;
}

//------------------------------------------------------------------END OF TREATMENT----------------------------------------------------------

//-------------------------------------------------------------------START OF PACKAGE---------------------------------------------------------

function Can_We_OK_Package() {

    var CanWeOK = true;
    //SECTION 1
    var Proposer = document.getElementById("txtProposer");
    var Property = document.getElementById("txtProperty");
    var Street = document.getElementById("txtStreet");
    var Locality = document.getElementById("txtLocality");
    var Town = document.getElementById("txtTown");
    var County = document.getElementById("txtCounty");
    var PostCode = document.getElementById("txtPostcode");
    var TBA = document.getElementById("chk_TBA");
    var Date_Cell = document.getElementById("td_Date");
    var Date_Chooser = igdrp_getComboById('datInceptionDate');

    var Trade = document.getElementById("lstTrade");

    var AnyLosses = document.getElementById("loss5Yes");
    var HowManyLosses = document.getElementById("lstHowMany");
    var HowManyLosses_Selected = document.getElementById("lstHowMany").value;
    var MoreThanThreeLosses = document.getElementById("lstHowMany").value;

    var Loss_Date_Cell_1 = document.getElementById("divDatLoss1Cont");
    var Loss_Date_Chooser_1 = igdrp_getComboById('datLoss1');
    var Type_Of_Loss_1 = document.getElementById("lstTypesOfLoss1");
    var Loss_Value_1 = document.getElementById("txtLoss1");

    var Loss_Date_Cell_2 = document.getElementById("divDatLoss2Cont");
    var Loss_Date_Chooser_2 = igdrp_getComboById('datLoss2');
    var Type_Of_Loss_2 = document.getElementById("lstTypesOfLoss2");
    var Loss_Value_2 = document.getElementById("txtLoss2");

    var Loss_Date_Cell_3 = document.getElementById("divDatLoss3Cont");
    var Loss_Date_Chooser_3 = igdrp_getComboById('datLoss3');
    var Type_Of_Loss_3 = document.getElementById("lstTypesOfLoss3");
    var Loss_Value_3 = document.getElementById("txtLoss3");

    var Loss_Comment = document.getElementById("txtLossComment");

    var Refresh = document.getElementById("cmdRefresh");

    //SECTION 2
    var Support_Play_Equipment = 'True';
    var Support_Entertainment = 'True';
    //lets see if they need entertainment of play
    if (document.getElementById("divSE").style.display == 'none') {
        Support_Entertainment = 'False';
    }
    if (document.getElementById("divSPE").style.display == 'none') {
        Support_Play_Equipment = 'False';
    }
    //SECTION 3
    var All_Risks_Description_1 = document.getElementById('txtAllRiskDesc1');
    var All_Risks_Value_1 = document.getElementById('txtAllRisksValue1');

    var All_Risks_Description_2 = document.getElementById('txtAllRiskDesc2');
    var All_Risks_Value_2 = document.getElementById('txtAllRisksValue2');

    var All_Risks_Description_3 = document.getElementById('txtAllRiskDesc3');
    var All_Risks_Value_3 = document.getElementById('txtAllRisksValue3');



    //lets sort out our number of losses if it is greater than 3 we want to set it to 3
    //as we use another variable MoreThanThreeLosses for more than 3 losses

    HowManyLosses_Selected = MoreThanThreeLosses.replace("> ", "");


    //lets SetMandatory
    if (!SetMandatory(Proposer)) {
        CanWeOK = false;
    }

    SetMandatory(TBA);

    if (!SetMandatory(Trade)) {
        CanWeOK = false;
    }
    //now lets do the loss history
    if (!SetMandatory(AnyLosses)) {
        CanWeOK = false;
    }


    //have they entered a valid postcode 
    if (PostCodeFound && PostCode.value != "") {

        SetMandatory(Property);
    }
    SetLocCon(Locality, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(Town, "Y", "Y", "LG", "B", "", "252px")
    SetLocCon(County, "Y", "Y", "LG", "B", "", "252px")
    
    //Does the current postcode match the old one?
    if (OLD_PostCode != PostCode.value) {
        CanWeOK = false;
        fncAddStar_II(PostCode);
        Refresh.style.display = "none";

    } else {
        fncRemoveStar_II(PostCode);
        Refresh.style.display = "inline";
    }

    if (!SetMandatory(PostCode)) {
        Refresh.style.display = "none";
    }

    //Firstly lets see if the address is ok or not!?!
    if (Property.value == '') {
        CanWeOK = false;
    } else {
        fncRemoveStar_II(Property);
    }
    if (PostCode.value == '') {
        CanWeOK = false;
    }


    if (TBA.checked == false && !Validate_Inception_Date(igdrp_getComboById('datInceptionDate'))) {
        CanWeOK = false;
    } else {
        Date_Cell.style.backgroundImage = "";
        fncRemoveStar_II(TBA);
        //lets either unckec or blank the inception date we cant have both
    }

    if (RadioButtonValue_By_Group('loss5') == 1) {
        if (!SetMandatory(HowManyLosses)) {
            CanWeOK = false;
        }
        fncEnDisLossHow('spnHowMany', 'en');
    } else {
        //lets set it to no losses
        HowManyLosses.selectedIndex = 0;
        //have to remove the star properly
        fncRemoveStar_II(HowManyLosses)
        fncEnDisLossHow('spnHowMany', 'dis', 1);
    }

    if (HowManyLosses_Selected == "") {
        HowManyLosses_Selected = 0;
        //lets enable the loss objects 0 will disable them all
        fncLoss(0);
        fncRemoveStar_II(Loss_Comment);
    }


    //if we have 1 loss we must have the 3 fields date, type and value
    if (HowManyLosses_Selected > 0) {
        //lets enable the loss objects

        if (HowManyLosses_Selected == 1) {
            fncLoss(1);
        }
        if (!SetMandatory(Type_Of_Loss_1)) {
            CanWeOK = false;
        }
        if (!SetMandatory(Loss_Value_1)) {
            CanWeOK = false;
        }
        if (!Validate_Date(igdrp_getComboById('datLoss1'), "divDatLoss1Cont")) {
            CanWeOK = false;
        } else {
            Loss_Date_Cell_1.style.backgroundImage = "";

        }
    } else {
        //must remeber to remove the stars
        fncRemoveStar_II(Type_Of_Loss_1);
        fncRemoveStar_II(Loss_Value_1);
        Loss_Date_Cell_1.style.backgroundImage = "";
    }
    //if we have 2 losses we must have the 3 fields date, type and value
    if (HowManyLosses_Selected > 1) {
        //lets enable the loss objects
        if (HowManyLosses_Selected == 2) {
            fncLoss(2);
        }
        if (!SetMandatory(Type_Of_Loss_2)) {
            CanWeOK = false;
        }
        if (!SetMandatory(Loss_Value_2)) {
            CanWeOK = false;
        }
        if (!Validate_Date(igdrp_getComboById('datLoss2'), "divDatLoss2Cont")) {
            CanWeOK = false;
        } else {
            Loss_Date_Cell_2.style.backgroundImage = "";

        }
    } else {
        //must remeber to remove the stars
        fncRemoveStar_II(Type_Of_Loss_2);
        fncRemoveStar_II(Loss_Value_2);
        Loss_Date_Cell_2.style.backgroundImage = "";
    }



    //if we have 3 losses we must have the 3 fields date, type and value
    if (HowManyLosses_Selected > 2) {
        //lets enable the loss objects
        if (HowManyLosses_Selected == 3) {
            fncLoss(3);
        }
        if (!SetMandatory(Type_Of_Loss_3)) {
            CanWeOK = false;
        }
        if (!SetMandatory(Loss_Value_3)) {
            CanWeOK = false;
        }
        if (!Validate_Date(igdrp_getComboById('datLoss3'), "divDatLoss3Cont")) {
            CanWeOK = false;
        } else {
            Loss_Date_Cell_3.style.backgroundImage = "";

        }
    } else {
        //must remeber to remove the stars
        fncRemoveStar_II(Type_Of_Loss_3);
        fncRemoveStar_II(Loss_Value_3);
        Loss_Date_Cell_3.style.backgroundImage = "";
    }


    //if we have > 3 losses we must have to make the comment mandatory
    if (MoreThanThreeLosses == '> 3') {
        fncLoss(4);
        if (!SetMandatory(Loss_Comment)) {
            CanWeOK = false;
        }
    } else {

        fncRemoveStar_II(Loss_Comment);
    }

    //lets disable the holdcover button
    if (CanWeOK == false) {
        DisableNavButton('btn_Demographics_Next')
        //let enable it
    } else {

        EnableNavButton('btn_Demographics_Next', "Navigation('divPropDetailsCont', 'divTypesOfTradeCont');Show_ERN_Message();")
    }
    //SECTION 2 
    //The first dive has been validated now for the secound one
    //-------------------------------------------------------divTypesOfTradeCont---------------------------------------------------------------
    //All types of trade must be selected
    //legal expenses
    if (!SetMandatory(document.getElementById('lecYes'))) {
        CanWeOK = false;
    }
    //how long trading
    if (!SetMandatory(document.getElementById('lstHLT'))) {
        CanWeOK = false;
    }
    //felt on timber roofs
    if (!SetMandatory(document.getElementById('fotrYes'))) {
        CanWeOK = false;
    }
    //felt on timber roofs must have age and percent if true
    if (RadioButtonValue_By_Group('fotr') == 1) {
        if (!SetMandatory(document.getElementById('lstFOTAge'))) {
            CanWeOK = false;
        }
        if (!SetMandatory(document.getElementById('lstPercentage'))) {
            CanWeOK = false;
        }
    }
    //subsidence
    if (!SetMandatory(document.getElementById('subYes'))) {
        CanWeOK = false;
    }
    //accidental damage
    if (!SetMandatory(document.getElementById('adcYes'))) {
        CanWeOK = false;
    }
    //Proposer live on premises
    if (!SetMandatory(document.getElementById('lopYes'))) {
        CanWeOK = false;
    }
    //Alarm Type
    if (!SetMandatory(document.getElementById('lstAlarm'))) {
        CanWeOK = false;
    }
    //Grilles or shutters
    if (!SetMandatory(document.getElementById('grillYes'))) {
        CanWeOK = false;
    }
    //CCTV
    if (!SetMandatory(document.getElementById('cctvYes'))) {
        CanWeOK = false;
    }

    if (Support_Entertainment != 'False') {
        //Entertainment
        if (!SetMandatory(document.getElementById('entYes'))) {
            CanWeOK = false;
        }
    }
    if (Support_Play_Equipment != 'False') {
        //Paly equipment
        if (!SetMandatory(document.getElementById('equYes'))) {
            CanWeOK = false;
        }
    }
    //Employ People
    if (!SetMandatory(document.getElementById('ERNYes'))) {
        CanWeOK = false;
        //lets hide it just incase
        document.getElementById('td_ERN').style.visibility = "hidden"
        document.getElementById('td_txt_ERN').style.visibility = "hidden"


    } else {
        //if it is yes we need to show the text box ok.
        if (RadioButtonValue_By_Group('ERN') == 1) {
            document.getElementById('td_ERN').style.visibility = "visible";
            document.getElementById('td_txt_ERN').style.visibility = "visible";
            //now lets check its not empty
            if (!SetMandatory(document.getElementById('txt_ERN'))) {
                CanWeOK = false;
            }
            //lets show the message
            Show_ERN_Message();

        } else {
        //lets hide it and clear it, the astris will take care of its self
            document.getElementById('td_ERN').style.visibility = "hidden";
            document.getElementById('td_txt_ERN').style.visibility = "hidden";
            document.getElementById('txt_ERN').value = "";
            //Lets hide the message
            Hide_ERN_Message();
        }
    }

    // Navigation('divTypesOfTradeCont', 'divSOSICont');
    //lets disable / enable the next button
    if (CanWeOK == false) {
        DisableNavButton('btn_TypesOfTrade_Next')
        //let enable it
    } else {

        EnableNavButton('btn_TypesOfTrade_Next', "Navigation('divTypesOfTradeCont', 'divSOSICont');fncDomContDis();Hide_ERN_Message();")
    }
    //SECTION 3
    //The first + Second div has been validated now for the Third one
    //-------------------------------------------------------divSOSICont---------------------------------------------------------------
    //ATrade contents is the only mandatory one but there are 3 all risks boxes so normal rules for them
    if (!SetMandatory(document.getElementById('txtFixFit'))) {
        CanWeOK = false;
    }
    //now lets do the all risks
    if (All_Risks_Description_1.value != '') {
        if (!SetMandatory(All_Risks_Value_1)) {
            CanWeOK = false;
        }
    } else {
        fncRemoveStar_II(All_Risks_Value_1);

    }
    if (All_Risks_Value_1.value != '') {
        if (!SetMandatory(All_Risks_Description_1)) {
            CanWeOK = false;
        }
    } else {
        fncRemoveStar_II(All_Risks_Description_1);

    }
    if (All_Risks_Description_2.value != '') {
        if (!SetMandatory(All_Risks_Value_2)) {
            CanWeOK = false;
        }
    } else {
        fncRemoveStar_II(All_Risks_Value_2);

    }
    if (All_Risks_Value_2.value != '') {
        if (!SetMandatory(All_Risks_Description_2)) {
            CanWeOK = false;
        }
    } else {
        fncRemoveStar_II(All_Risks_Description_2);

    }
    if (All_Risks_Description_3.value != '') {
        if (!SetMandatory(All_Risks_Value_3)) {
            CanWeOK = false;
        }
    } else {
        fncRemoveStar_II(All_Risks_Value_3);

    }
    if (All_Risks_Value_3.value != '') {
        if (!SetMandatory(All_Risks_Description_3)) {
            CanWeOK = false;
        }
    } else {
        fncRemoveStar_II(All_Risks_Description_3);

    }

    //lets disable / enable the next button
    if (CanWeOK == false) {
        DisableNavButton('btn_SumsInsured_Next')
        //let enable it
    } else {

        EnableNavButton('btn_SumsInsured_Next', "Navigation('divSOSICont', 'divMoneyCont');")
    }
    //SECTION 4 MONEY
    //The first + Second + Third div has been validated now for the Fourth one
    //-------------------------------------------------------divMoneyCont---------------------------------------------------------------
    //ATM QUESTIONAIRE
    //ATM 
    if (!SetMandatory(document.getElementById('atmYes'))) {
        CanWeOK = false;
    }

    if (RadioButtonValue_By_Group('atm') == 1) {
        //money in atm during business hours
        if (!SetMandatory(document.getElementById('cashInATMDuringBusHours'))) {
            CanWeOK = false;
        }
        //atm located
        if (!SetMandatory(document.getElementById('txtATMLoc'))) {
            CanWeOK = false;
        }
        //observe activity
        if (!SetMandatory(document.getElementById('obATMYes'))) {
            CanWeOK = false;
        }
        //merchant fill
        if (!SetMandatory(document.getElementById('merFillATMYes'))) {
            CanWeOK = false;
        }
        //company fill
        if (!SetMandatory(document.getElementById('citYes'))) {
            CanWeOK = false;
        }
        //responsible for atm
        if (!SetMandatory(document.getElementById('resATMYes'))) {
            CanWeOK = false;
        }
        //if responsible is yes then make model and owner are mandatory
        if (RadioButtonValue_By_Group('resATM') == 1) {
            //make and model
            if (!SetMandatory(document.getElementById('txtATMMakeModel'))) {
                CanWeOK = false;
            }
            //atm owner
            if (!SetMandatory(document.getElementById('txtATMOwner'))) {
                CanWeOK = false;
            }
        } else {
            fncRemoveStar_II(document.getElementById('txtATMMakeModel'))
            fncRemoveStar_II(document.getElementById('txtATMOwner'))
        }
        //cash during business hours
        if (!SetMandatory(document.getElementById('txtATMMax'))) {
            CanWeOK = false;
        }
        //cash Out side business hours
        if (!SetMandatory(document.getElementById('txtATMMaxOut'))) {
            CanWeOK = false;
        }

        //Cash from atm in safe
        if (!SetMandatory(document.getElementById('radATMSafeYes'))) {
            CanWeOK = false;
        }
        //Cash from atm in safe if yes then make and model is mandatory
        if (RadioButtonValue_By_Group('atmSafe') == 1) {
            //make and model
            if (!SetMandatory(document.getElementById('txtSafeMakeModel'))) {
                CanWeOK = false;
            }
        } else {
            fncRemoveStar_II(document.getElementById('txtSafeMakeModel'))
        }
        //Accessible doors and windows
        if (!SetMandatory(document.getElementById('radGrillesBarsYes'))) {
            CanWeOK = false;
        }
        //Ram Bars
        if (!SetMandatory(document.getElementById('radAntiRamYes'))) {
            CanWeOK = false;
        }
        //Alarm system
        if (!SetMandatory(document.getElementById('radAlarmSysYes'))) {
            CanWeOK = false;
        }
        //Smoke Cloak
        if (!SetMandatory(document.getElementById('radSmokeCloakYes'))) {
            CanWeOK = false;
        }
        //Bank note degradation system
        if (!SetMandatory(document.getElementById('radBanknoteYes'))) {
            CanWeOK = false;
        }
        //Tracking devices
        if (!SetMandatory(document.getElementById('radTrackDeviceYes'))) {
            CanWeOK = false;
        }
        //CCTV
        if (!SetMandatory(document.getElementById('radATMCCTVYes'))) {
            CanWeOK = false;
        }
    }

    //lets disable / enable the next button
    if (CanWeOK == false) {
        DisableNavButton('btn_Proceed_To_Quote')
        //let enable it
    } else {

        EnableNavButton('btn_Proceed_To_Quote', "Navigation('divMoneyCont', 'divSummaryCont');document.getElementById('form1').submit();")
    }
}
function Show_ERN_Message() {
    var ERN_Top = document.getElementById("tbl_ERN").offsetTop;
    var ERN_Left = document.getElementById("td_ERN").offsetLeft;
    var Div_ERN_Msg = document.getElementById("Div_ERN_Msg");
    var divTypesOfTradeCont = document.getElementById("divTypesOfTradeCont");

    //lets see if we are on the right page
    if (divTypesOfTradeCont.style.display == 'block') {

        if (RadioButtonValue_By_Group('ERN') == 1) {

            Div_ERN_Msg.style.top = ERN_Top + 50 + "px";
            Div_ERN_Msg.style.left = ERN_Left + "px";
            Div_ERN_Msg.style.display = 'block';
        }
    }
}

function Hide_ERN_Message() {
    var Div_ERN_Msg = document.getElementById("Div_ERN_Msg");

    Div_ERN_Msg.style.display = 'none';


} 
//-------------------------------------------------------------------END OF PACKAGE---------------------------------------------------------

function Navigation(Div_To_Hide, Div_To_Show) {

    Div_To_Hide = document.getElementById(Div_To_Hide);
    Div_To_Show = document.getElementById(Div_To_Show);

    //lets hide the div or show the div this will replace nav wizard function
    Div_To_Hide.style.display = 'none';
    Div_To_Show.style.display = 'block';

}
function Integers_And_Commas_Only(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    //allow for comma
    if (charCode == 44) {
        return true;
    }
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}


///*
//Date formating function from http://blog.stevenlevithan.com/archives/date-time-format very good but not used


//* Date Format 1.2.3
//* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
//* MIT license
//*
//* Includes enhancements by Scott Trenda <scott.trenda.net>
//* and Kris Kowal <cixar.com/~kris.kowal/>
//*
//* Accepts a date, a mask, or a date and a mask.
//* Returns a formatted version of the given date.
//* The date defaults to the current date/time.
//* The mask defaults to dateFormat.masks.default.
//*/

//var dateFormat = function () {
//    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
//		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
//		timezoneClip = /[^-+\dA-Z]/g,
//		pad = function (val, len) {
//		    val = String(val);
//		    len = len || 2;
//		    while (val.length < len) val = "0" + val;
//		    return val;
//		};

//    // Regexes and supporting functions are cached through closure
//    return function (date, mask, utc) {
//        var dF = dateFormat;

//        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
//        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
//            mask = date;
//            date = undefined;
//        }

//        // Passing date through Date applies Date.parse, if necessary
//        date = date ? new Date(date) : new Date;
//        if (isNaN(date)) throw SyntaxError("invalid date");

//        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

//        // Allow setting the utc argument via the mask
//        if (mask.slice(0, 4) == "UTC:") {
//            mask = mask.slice(4);
//            utc = true;
//        }

//        var _ = utc ? "getUTC" : "get",
//			d = date[_ + "Date"](),
//			D = date[_ + "Day"](),
//			m = date[_ + "Month"](),
//			y = date[_ + "FullYear"](),
//			H = date[_ + "Hours"](),
//			M = date[_ + "Minutes"](),
//			s = date[_ + "Seconds"](),
//			L = date[_ + "Milliseconds"](),
//			o = utc ? 0 : date.getTimezoneOffset(),
//			flags = {
//			    d: d,
//			    dd: pad(d),
//			    ddd: dF.i18n.dayNames[D],
//			    dddd: dF.i18n.dayNames[D + 7],
//			    m: m + 1,
//			    mm: pad(m + 1),
//			    mmm: dF.i18n.monthNames[m],
//			    mmmm: dF.i18n.monthNames[m + 12],
//			    yy: String(y).slice(2),
//			    yyyy: y,
//			    h: H % 12 || 12,
//			    hh: pad(H % 12 || 12),
//			    H: H,
//			    HH: pad(H),
//			    M: M,
//			    MM: pad(M),
//			    s: s,
//			    ss: pad(s),
//			    l: pad(L, 3),
//			    L: pad(L > 99 ? Math.round(L / 10) : L),
//			    t: H < 12 ? "a" : "p",
//			    tt: H < 12 ? "am" : "pm",
//			    T: H < 12 ? "A" : "P",
//			    TT: H < 12 ? "AM" : "PM",
//			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
//			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
//			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
//			};

//        return mask.replace(token, function ($0) {
//            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
//        });
//    };
//} ();

//// Some common format strings
//dateFormat.masks = {
//    "default": "ddd mmm dd yyyy HH:MM:ss",
//    shortDate: "m/d/yy",
//    mediumDate: "mmm d, yyyy",
//    longDate: "mmmm d, yyyy",
//    fullDate: "dddd, mmmm d, yyyy",
//    shortTime: "h:MM TT",
//    mediumTime: "h:MM:ss TT",
//    longTime: "h:MM:ss TT Z",
//    isoDate: "yyyy-mm-dd",
//    isoTime: "HH:MM:ss",
//    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
//    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
//};

//// Internationalization strings
//dateFormat.i18n = {
//    dayNames: [
//		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
//		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
//	],
//    monthNames: [
//		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
//		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
//	]
//};

//// For convenience...
//Date.prototype.format = function (mask, utc) {
//    return dateFormat(this, mask, utc);
//};

